Skip to content

Compare token sequences for hasPhrase over a postprocessed text index - #119367

Closed
alexey-milovidov wants to merge 4 commits into
masterfrom
fix-text-index-phrase-postprocessor-117075
Closed

alexey-milovidov wants to merge 4 commits into
masterfrom
fix-text-index-phrase-postprocessor-117075

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Fix wrong results of hasPhrase on a column indexed with a text index that has a postprocessor: a phrase present in the document was not matched (and one whose tokens are not adjacent was), on every execution path, when the index tokenizer does not split on spaces or a postprocessed token is itself a separator.

Documentation entry for user-facing changes

...

hasPhrase on a column indexed with a text index that has a postprocessor returned wrong results on every execution path — with the index, with use_skip_indexes = 0 and with query_plan_direct_read_from_text_index = 0 — in both directions:

CREATE TABLE tab (id UInt64, doc String,
  INDEX idx doc TYPE text(tokenizer = splitByString(['()']), postprocessor = lower(doc)) GRANULARITY 1)
ENGINE = MergeTree ORDER BY id;
INSERT INTO tab VALUES (1, 'a()bc()d');
SELECT count() FROM tab WHERE hasPhrase(doc, 'bc()d');  -- 0, the phrase is right there

and, with a tokenizer whose separators include x, a document 'A X B' matched the phrase 'a b' although the index keeps a and b two positions apart.

To give the row-level function the index's analyzer semantics, the rewrite postprocessed the tokens of both sides and rejoined them with a space for hasPhrase to re-tokenize. That assumed a space is a separator of the index tokenizer. For splitByString(['()']) it is not: the rejoined haystack came back as the single token 'a bc d', so no multi-token phrase could match. And when a postprocessed token is itself a separator, the re-split dissolved it and made tokens adjacent that the index keeps apart. The validation next to the rejoin checked tokens against the splitByNonAlpha alphabet rather than the tokenizer's own separators, so neither case was noticed.

Compare the two token sequences directly instead: the haystack's postprocessed tokens against the phrase's postprocessed tokens with hasSubstr, which is true exactly when the second array occurs in the first as a contiguous run. No string is rebuilt and nothing is re-tokenized, so the tokenizer's separators no longer matter. The tokens the postprocessor emptied are filtered out of the haystack array (the index has no position for them), which is what the rejoin achieved by collapsing them into adjacent separators. A phrase the postprocessor empties entirely still matches nothing, as before.

Two existing tests recorded the restriction that the rejoin imposed and are updated: a postprocessor that emits a separator (concat(message, ' x')) in 02346_text_index_function_hasPhrase_postprocessor and a gram that spans a separator in 04353_text_index_explicit_tokenizer_argument were rejected with BAD_ARGUMENTS; both now answer, consistently on every read path and in agreement with the same data without an index.

Also, MergeTreeIndexConditionText::traverseFunctionNode rejected hasPhrase on a splitByRegexp index with a postprocessor with BAD_ARGUMENTS, for exactly the two assumptions above: the rejoin collapsed tokens when the regexp separator is not a space, and the validation rejected a token such as c#. selectConditions builds the search query before the rewrite runs, so those queries never reached the new token-sequence path on any read path. The guard is removed, and with it the footnote in the text index documentation and the note in the hasPhrase FunctionDocumentation that declared the combination unsupported. The index side needed no change - it tokenizes and postprocesses the phrase with the index's own tokenizer and postprocessor, and positions are dense on both sides, so it is symmetric with every other tokenizer, in match_tokens mode too. 02346_text_index_SplitByRegexp_tokenizer and 02346_text_index_split_by_regexp_extract recorded the rejection and now assert real answers on all three read paths.

New test: 05204_text_index_phrase_postprocessor. Verified in both directions, and a differential run of the text_index/hasphrase/hastoken/tokenizer/postprocessor/full_text stateless tests (221 tests) shows no failures other than the two references updated here.

Closes: #117075

🤖 Generated with Claude Code


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

`hasPhrase` on a column indexed with a `text` index that has a postprocessor returned wrong results on
every execution path - with the index, with `use_skip_indexes = 0` and with
`query_plan_direct_read_from_text_index = 0` - in both directions:

    CREATE TABLE tab (id UInt64, doc String,
      INDEX idx doc TYPE text(tokenizer = splitByString(['()']), postprocessor = lower(doc)) GRANULARITY 1)
    ENGINE = MergeTree ORDER BY id;
    INSERT INTO tab VALUES (1, 'a()bc()d');
    SELECT count() FROM tab WHERE hasPhrase(doc, 'bc()d');  -- 0, the phrase is right there

and, with a tokenizer whose separators include `x`, a document `'A X B'` matched the phrase `'a b'`
although the index keeps `a` and `b` two positions apart.

To give the row-level function the index's analyzer semantics, the rewrite postprocessed the tokens of
both sides and rejoined them with a space for `hasPhrase` to re-tokenize. That assumed a space is a
separator of the index tokenizer. For `splitByString(['()'])` it is not: the rejoined haystack came
back as the single token `'a bc d'`, so no multi-token phrase could match. And when a postprocessed
token is itself a separator, the re-split dissolved it and made tokens adjacent that the index keeps
apart. The validation next to the rejoin checked tokens against the `splitByNonAlpha` alphabet rather
than the tokenizer's own separators, so neither case was noticed.

Compare the two token sequences directly instead: the haystack's postprocessed tokens against the
phrase's postprocessed tokens with `hasSubstr`, which is true exactly when the second array occurs in
the first as a contiguous run. No string is rebuilt and nothing is re-tokenized, so the tokenizer's
separators no longer matter. The tokens the postprocessor emptied are filtered out of the haystack
array (the index has no position for them), which is what the rejoin achieved by collapsing them into
adjacent separators. A phrase the postprocessor empties entirely still matches nothing, as before.

Two existing tests recorded the restriction that the rejoin imposed and are updated: a postprocessor
that emits a separator (`concat(message, ' x')`) in
`02346_text_index_function_hasPhrase_postprocessor` and a gram that spans a separator in
`04353_text_index_explicit_tokenizer_argument` were rejected with `BAD_ARGUMENTS`; both now answer,
consistently on every read path and in agreement with the same data without an index.

Closes: #117075
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b2942ee]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the hasPhrase row-scan rewrite for text indexes with a postprocessor by comparing postprocessed token sequences directly instead of round-tripping them back through a space-joined string. That closes the reported false-positive/false-negative cases, removes the stale splitByRegexp rejection, and the updated coverage exercises the indexed path, use_skip_indexes = 0, and query_plan_direct_read_from_text_index = 0. I did not find a remaining correctness issue in the current code.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit b2942ee.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.70% +0.10%

Changed lines: Changed C/C++ lines covered: 57/58 (98.28%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 10, 2026
@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 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit b2942ee754b2fd9b685366d6b7665d9632117cf9 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

alexey-milovidov and others added 2 commits September 18, 2026 12:02
`MergeTreeIndexConditionText::traverseFunctionNode` rejected `hasPhrase` on a `splitByRegexp` text
index that also has a postprocessor with `BAD_ARGUMENTS`. The rejection existed for exactly the two
assumptions this pull request removed from the row-level rewrite: it rejoined the postprocessed
tokens with a space for `hasPhrase` to re-tokenize (a regexp separator need not be a space, so the
rejoin collapsed tokens) and it validated every token against the `splitByNonAlpha` alphabet (which
rejects a token such as `c#`). Because `selectConditions` builds the search query before
`optimizeDirectReadFromTextIndex` runs, those queries never reached the new token-sequence path on
any read path, so this one supported tokenizer family still could not use `hasPhrase`.

The rewrite compares the two postprocessed token sequences directly with `hasSubstr` now, so no
separator and no alphabet is assumed and the tokenizer needs no special case - in `match_tokens`
mode either, where the index positions are exactly the matches the rewrite reproduces. Remove the
guard, and with it the footnote in the text index documentation and the note in the `hasPhrase`
`FunctionDocumentation` that declared the combination unsupported.

The two tests that recorded the rejection now assert real answers, cross-checked on the index path,
with `use_skip_indexes = 0` and with `query_plan_direct_read_from_text_index = 0`:
`02346_text_index_SplitByRegexp_tokenizer` matches the phrase `C# and` only in the row that has the
token `c#` (not the one with `c++`) and lowercases the phrase too, and
`02346_text_index_split_by_regexp_extract` matches `tag:RED tag:GREEN` against a document indexed
with `splitByRegexp('tag:(\w+)', 1)`, while the reversed phrase and a phrase the tokenizer finds no
token in match nothing.

A differential run of the `text_index`/`hasphrase`/`hastoken`/`tokenizer`/`postprocessor`/`full_text`
stateless tests (230 tests) passes, except for two failures that are local-environment only (an
interserver connection over the loopback cluster and the missing `test.hits` dataset).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Sep 18, 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 Sep 19, 2026, 8:41 PM

@ahmadov

ahmadov commented Sep 18, 2026

Copy link
Copy Markdown
Member

I suppose this case would be solved by allowing hasPhrase to accept an Array(String) instead of using hasSubstr. I opened this PR (#120859) to do that.

This branch was successfully deployed

1 active deployment
staging - docs — b2942ee7 Deployed Sep 19, 2026 by mintlify[bot]
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index with splitByString tokenizer + postprocessor: hasPhrase returns wrong results on every execution path (silent row loss and false positives)

3 participants