Skip to content

Use the text index when a tokenizer argument matches the index tokenizer - #115348

Merged
CurtizJ merged 12 commits into
ClickHouse:masterfrom
groeneai:text-index-explicit-tokenizer-argument
Aug 29, 2026
Merged

CurtizJ merged 12 commits into
ClickHouse:masterfrom
groeneai:text-index-explicit-tokenizer-argument

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

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

A text index is now used for hasAnyTokens, hasAllTokens and hasPhrase called with an explicit tokenizer argument, when that argument denotes the same tokenizer as the index. Previously the three-argument form always fell back to a full scan. Closes #115275.

Description

Closes: #115275
Related: #108808
Related: #107186

MergeTreeIndexConditionText::traverseAtomNode rejected any non-binary function node before looking at the function name, so a three-argument hasAnyTokens / hasAllTokens / hasPhrase never reached isSupportedFunction. The predicate became an unknown atom: no granule pruning, no direct read. Since the three-argument form is the documented workaround for #108808, users of a non-splitByNonAlpha tokenizer had no option that was both correct and indexed.

The gate now admits three arguments for those functions when the argument's tokenizer canonicalizes to the index tokenizer, comparing ITokenizer::getDescription() so aliases compare equal while parameters still discriminate (ngrams(3) is not ngrams(4)). A different, non-constant or invalid argument still full-scans, without raising an error.

An index carrying a preprocessor or postprocessor behaves like the two-argument form, per @ rschu1ze's review: the direct-read pass rewrites the two-argument form into the three-argument form and applies both transforms, so the spellings reach the same code.

One combination is excluded: hasPhrase on a postprocessor index with a splitByString tokenizer. The row-level rewrite hands hasPhrase the postprocessed tokens joined by a space and re-splits them, which a separator list need not reconstruct - separators without a space merge the tokens into one, and a postprocessor can turn a stored token into a configured separator, dropping it so a non-consecutive phrase matches. Both depend on postprocessed token values, unknown while planning, so that case full-scans. hasAnyTokens and hasAllTokens are unaffected (tokens matched verbatim as an array), as are splitByNonAlpha, ngrams, asciiCJK and icu.

hasPhrase is included at @ CurtizJ's request (#115275 (comment)).

The 02346_text_index_function_hasPhrase* cells that asserted the old full-scan behavior now assert agreement with the two-argument form, with a mismatching-tokenizer sibling at each site. In 04353 that agreement is a query emitting a row only on disagreement, verified to print rows without this change and nothing with it.


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

…izer matches

MergeTreeIndexConditionText::traverseAtomNode rejected any function node that was
not binary before it looked at the function name, so a three-argument
hasAnyTokens / hasAllTokens / hasPhrase never reached isSupportedFunction, which
already lists all three. The predicate became an unknown atom: no granule pruning
and no direct read. The three-argument form is the documented workaround for
issue 108808, so users of a non-splitByNonAlpha tokenizer had no option that was
both correct and indexed.

Admit three arguments for those three functions when the argument's tokenizer
canonicalizes to the index tokenizer. Comparing ITokenizer::getDescription() is
what the direct-read pass already synthesizes for the two-argument case, so
registered aliases and spelling variants compare equal while parameters still
discriminate: ngrams(3) is not ngrams(4). Comparing ITokenizer::Type instead
would erase the parameters and prune granules with the wrong tokenization, which
was measured to drop rows.

Every other combination keeps full-scanning, without raising an error: a
different tokenizer, a non-constant or invalid argument, and an index with a
postprocessor. The postprocessor case is not merely conservative. Such an index
stores postprocessed tokens that the argument's bare tokenizer never produces, so
admitting it made the same query return different rows depending on whether the
index was consulted: hasAnyTokens silently lost rows and hasAllTokens gained
false positives.

The tokenizer comparison deliberately does not catch exceptions. The definition
has already been parsed by the function's own overload resolver by the time the
predicate runs, so a throw would signal a real invariant failure rather than a
bad definition, and swallowing it would convert that into a silent full scan.

Keep the direct-read pass argument-count-preserving: assign the tokenizer
argument in place when one is already present instead of appending. That pass can
legitimately run over the same node more than once, and appending built a
four-argument call rejected with NUMBER_OF_ARGUMENTS_DOESNT_MATCH.

hasToken is excluded because its third argument is a start position rather than a
tokenizer, and HasTokenImpl::supports_start_pos is false, so a three-argument
hasToken cannot be constructed at all.

02346_text_index_function_hasPhrase and its positions variant asserted the old
full-scan behaviour for this exact case. Those sections are retitled and
regenerated, and a mismatching-tokenizer sibling case is added at the same site so
the full-scan boundary keeps a pinned oracle.
…ansformed index

A text index carrying a preprocessor option stores tokens of a transformed value, so a
bare tokenizer over the raw third argument cannot answer the same predicate even when the
tokenizer definitions are equal. Admitting the 3-argument form there made the result
depend on whether the index was consulted: with a preprocessor = lower(doc) index,
hasAnyTokens(doc, ['hello'], 'splitByNonAlpha') returned [1,2] through the index and [2]
with use_skip_indexes = 0, and hasAllTokens and hasPhrase returned [1] against []. That is
the same wrong-results class as ClickHouse#108808, reached through the preprocessor dimension.

Extend the transform guard in tokenizerArgumentMatchesIndex from has_postprocessor to
has_preprocessor || has_postprocessor. This only narrows what the fix admits: a
non-equivalent combination full-scans and no error is raised.

An earlier probe of this dimension used an expression index (INDEX idx lower(col) ...),
which is a different mechanism. There the transform is written by the user in the
predicate, so the index remains usable; the preprocessor option is applied at write time
and is invisible in the predicate, exactly like the postprocessor.

Also pin a direct-read oracle in the regression test. The existing plan assertion runs with
query_plan_direct_read_from_text_index = 0, so it proved granule pruning only, while the
direct-read queries asserted row equality and passed whether or not the optimization fired.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 open blockers)

Two review rounds by a model independent of the one that wrote the code, plus a cold reviewer
pass. Round 1 found a wrong-results blocker; it is fixed. The final round returned no findings.

Round 1 (commit 06839be)

❌ Blocker - a preprocessor = index option was wrongly admitted. With a matching tokenizer
argument the predicate returned different rows depending on whether the index was consulted, on
all three functions:

query (preprocessor = lower(doc) index, matching tokenizer) use_skip_indexes=0 =1
hasAnyTokens(doc, ['hello'], 'splitByNonAlpha') [2] [1,2]
hasAllTokens(doc, ['hello','world'], 'splitByNonAlpha') [] [1]
hasPhrase(doc, 'hello world', 'splitByNonAlpha') [] [1]

Root cause: with either transform the index stores tokens of a transformed value, which a bare
tokenizer over the raw argument never produces, so tokenizer equality does not make the index able
to answer the predicate. The guard now covers preprocessor and postprocessor alike. Fail-closed
only: full scan, no error.

Note an expression index (INDEX idx lower(doc) ...) is a different mechanism and is legitimately
usable, because there the transform is written by the user inside the predicate. Conflating the two
is what let this through the first time.

⚠️ Major - the direct-read half of the change had no oracle. The plan assertion pinned
query_plan_direct_read_from_text_index = 0, so it proved granule pruning only, while the
direct-read-enabled queries asserted row equality, which passes whether or not direct read fires.
That is the branch where the earlier wrong-results issues in this area originated. A plan-column
assertion was added under = 1; it reads 0 on the base binary and 1 with the fix, so both consumers
of the single gate fix are now separately pinned.

Round 2 (commit d0edd7e)

No findings. The independent cold pass separately confirmed: getDescription() is injective across
all nine registered tokenizers (aliases collapse deliberately, parameters still discriminate); the
two traversals that run before the arity gate never read the tokenizer argument, so they are
unaffected; excluding hasToken is correct and in fact unreachable by construction, since a
three-argument hasToken cannot be built at all; and every new test arm fails if the fix is
reverted, with the transform arms reddening on row disagreement rather than only on an error
annotation.

Two documentation nits were raised against the PR text itself and are fixed here: the changelog
entry now states the no-preprocessor/postprocessor condition, and the hasPhrase request
citation now points at the correct comment.

Validation

Both directions on the issue's own reproducer; a 23-arm base-vs-fix ledger with a positive control
(nine arms flip, five controls unchanged, no live arm passes on base); four negative controls, each
proving a guard load-bearing, including one showing the weaker getType() comparison silently drops
a row; no in-tree reference moved outside the two intentionally retitled hasPhrase sections and
the new test; 450 randomized runs.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1adc14c]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR makes the explicit-tokenizer overload of hasAnyTokens, hasAllTokens, and hasPhrase eligible for text-index optimization when the tokenizer string canonicalizes to the index tokenizer. The current head still reintroduces a wrong-results path for hasPhrase: on splitByString(...) indexes with a postprocessor and support_phrase_search = 1, the exact positional read and the fallback/default-expression path no longer agree, so the query result can change with part materialization or text_index_hint_max_selectivity.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:277-281] tokenizerArgumentMatchesIndex now admits explicit-tokenizer hasPhrase for splitByString(...) + postprocessor again, but the fallback/default-expression path still rewrites the haystack and needle by joining postprocessed tokens with spaces (optimizeDirectReadFromTextIndex.cpp:791-823). With support_phrase_search = 1, the exact reader uses the stored phrase_tokens (src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1254-1268, src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp:858-887), while fallback evaluates hasPhrase('a bc d', 'bc d', 'splitByString([\\'()\\'])') and returns 0. Because exact phrase virtual columns fall back on unmaterialized parts and can also switch to fallback on materialized parts when the selectivity heuristic fires (src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp:319-345, src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:910-915), the same query's answer now depends on materialization / text_index_hint_max_selectivity.
    Suggested fix: keep hasPhrase with splitByString(...) + postprocessor gated away from the explicit-tokenizer path, or make the fallback/default-expression rewrite lossless before allowing it.
Tests
  • ⚠️ Add a focused stateless case for hasPhrase(..., 'splitByString(...)') on a postprocessed index with support_phrase_search = 1 that forces both the exact positional read and the fallback path (for example with text_index_hint_max_selectivity or partially materialized parts). The current tests only cover the no-positions variant, so they would not catch the exact-vs-fallback divergence above.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either restore a guard for the explicit-tokenizer hasPhrase + splitByString(...) + postprocessor combination, or make the fallback/default-expression path preserve the same token sequence as the positional index path, and add a regression test that exercises both execution paths.

LLVM Coverage Report

Measured on commit 1adc14c.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 44/47 (93.62%) · 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 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's own reproducer (expression index, icu('ja'), force_data_skipping_indices) gives Code: 277 INDEX_NOT_USED on every run at base 5bd006cd298a3, and 1 with the fix. Not probabilistic.
b Root cause explained? MergeTreeIndexConditionText::traverseAtomNode rejected any non-binary function node (MergeTreeIndexConditionText.cpp:643) before the name check, so a 3-argument call never reached isSupportedFunction (:235-257), which already lists all three functions. The predicate became an unknown atom: no pruning, no direct read.
c Fix matches root cause? Yes. The arity gate itself is made per-function and per-tokenizer; nothing is guarded downstream, no bound is widened, no test tag added.
d Test intent preserved / new tests added? New stateless test 04353_text_index_explicit_tokenizer_argument. 02346_text_index_function_hasPhrase{,_positions} pinned the old full-scan behavior for this exact case; those sections are retitled and regenerated and a mismatching-tokenizer sibling case is added at the same site, so coverage is added rather than traded.
e Both directions demonstrated? Yes. Base binary 46bac98e... vs fix ce7b1b88...: 9 live arms flip, 5 controls unchanged, no live arm passes on base. Full 23-arm base-vs-fix ledger recorded. The preprocessor arm added in review round 1 was verified the same way: it returns divergent rows without the guard and base-identical rows with it.
f Fix is general across code paths? createTextSearchQuery is the single entry point for granule analysis and the direct-read pass, so one gate fix reaches both consumers, and the test now pins each consumer separately (a Granules: 1/2 assertion with direct read off, and a __text_index_idx_hasAnyTokens plan-column assertion with it on; both read 0 on base and 1 with the fix). Legacy MergeTreeIndexBloomFilterText.cpp:380 has its own != 2 gate, but its allowlist (:400-420) contains none of the three functions, so it is out of scope by design. hasToken is excluded because HasTokenImpl::supports_start_pos == false makes a 3-argument hasToken unconstructible.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tokenizer matrix: splitByNonAlpha, alias tokenbf_v1, whitespace variant, ngrams(3) vs ngrams(4), array, chinese (via 04316), icu('ja') (via 02346_text_index_icu_tokenizer). All three functions; non-constant and invalid arguments; 2/3/4-argument arities. The index-transform dimension has three distinct carriers, each with its own test section and each checked against a use_skip_indexes = 0 control: a postprocessor = option and a preprocessor = option, both invisible in the predicate and therefore rejected, and an expression index, where the transform is written by the user in the predicate and the index is legitimately usable. Tokenizer names are case-sensitive on master, so only whitespace normalizes, and the test says so.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry. Queries that worked keep working; some that full-scanned now use the index, which is the requested change. Mismatching combinations keep full-scanning.
i Invariants and contracts preserved? The direct-read pass stays argument-count-preserving (assign, not append), so chassert(new_children.size() == 3) and the array-tokenizer override below it hold for both entry arities. Operand binding from positions 0 and 1 is unchanged, so haystack type-wrapper handling is untouched. The index/row-level agreement invariant is asserted across use_skip_indexes x query_plan_direct_read_from_text_index and by the byte-identical 04316_chinese_tokenizer_text_index and 02346_text_index_icu_tokenizer references.

Validation: 181/182 of the text_index suite, plus every test named in review round 1
(02346_text_index_preprocessor, ..._preprocessor_partially_materialized, ..._postprocessor,
02346_text_index_function_hasPhrase{,_positions,_postprocessor}, 04316_chinese_tokenizer_text_index,
02346_text_index_icu_tokenizer). The single remaining failure needs the stateful hits dataset,
which is absent locally: it fails at its INSERT ... FROM test.hits before any query runs, uses only
2-argument calls, and declares no preprocessor or postprocessor, so it cannot be affected by this
change. No reference file moved except the new test's. 450/450 randomized runs pass on the final
binary, and 300/300 on the previous one.

Four negative controls confirm each guard is load-bearing rather than trivially green: weakening the
comparison to ITokenizer::getType() makes an ngrams(4) needle wrongly prune granules against an
ngrams(3) index and silently drop a row; keeping the old unconditional push_back produces
Code: 42 NUMBER_OF_ARGUMENTS_DOESNT_MATCH ... got 4 arguments on even the simplest 3-argument query;
reverting only the preprocessor half of the transform guard makes the new arm return row 1 whenever
the index is consulted while use_skip_indexes = 0 correctly excludes it, i.e. it reddens on row
disagreement and not merely on the expected-error line; and wrapping the tokenizer comparison in
catch (...) is byte-identical across all 23 arms, i.e. invisible to the suite, which is why it was
rejected on reasoning instead.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @Ergus, could you review this? The arity gate in MergeTreeIndexConditionText::traverseAtomNode sat ahead of the function-name check, so a 3-argument hasAnyTokens/hasAllTokens/hasPhrase never reached isSupportedFunction and always full-scanned; it now admits the 3-argument form when the argument tokenizer canonicalizes to the index tokenizer, and stays a full scan for a mismatch or for an index carrying a preprocessor/postprocessor option, where the stored tokens cannot answer the predicate.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1adc14ce8 with master 549c02d37 (stripped binary size, per-symbol sizes and ThinLTO time; 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 710.08 MiB 707.02 MiB -3.06 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.

Compile time of recompiled translation units

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

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

Job report

@CurtizJ CurtizJ self-assigned this Aug 21, 2026
The direct-read pass rewrites a text-search predicate in two independent places:
processTextIndexFunction injects the index tokenizer definition into the third
argument, and replaceFunctionsToVirtualColumns substitutes the index answer for
the predicate. Both were authorized only by MergeTreeIndexConditionText's arity
gate in traverseAtomNode, three files upstream, and neither site would notice if
that gate stopped rejecting a tokenizer the index cannot answer.

Re-check the property in selectConditions, which is the single point that
authorizes both consumers, reusing tokenizerArgumentMatchesIndex so there is one
comparator rather than two that can diverge. A tokenizer the index cannot answer
now skips the index and leaves the predicate alone, which is the behaviour the
predicate already had before it became eligible for the index at all.

The check is unreachable on the current gate chain, so it was validated against a
binary with the upstream comparison suppressed. On that binary a mismatching
tokenizer reaches the direct read and returns a row the predicate does not match
(needle 'ell' against an ngrams(3) index queried as splitByNonAlpha); with the
check present the same binary skips the index and agrees with the no-index
result. Behaviour on an unmodified binary is unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger: 872d20e

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04510_not_has_function_explain master-side test content, TYPE_MISMATCH on an Array(Map) constant shipped to a replica #115883 (external, open)

The failing assertion is not in this branch. praktika builds the merge commit, so master's
copy of the test runs against this branch's build: the file is 80 lines at this head and at
its base, 403 lines on master, and the cited failure sits at line 209. test_map_null_set
occurs 0 times at this head and 9 times on master. Breadth over 30 days: 24 rows across 20
distinct pull requests plus 3 hits on master itself. The throw is at
src/Functions/FunctionsConversion.cpp:896, untouched by this branch.

Session id: cron:our-pr-ci-monitor:20260822-050000

The two-argument form of hasAnyTokens/hasAllTokens/hasPhrase is rewritten
into the three-argument form by the direct-read pass, which appends the
index tokenizer and then applies the index preprocessor and postprocessor.
The three-argument form written by the user reached the same code, so
refusing an index that carries either transform made the two spellings of
one predicate behave differently for no reason.

The transform-related bail-out is removed, so a user-written tokenizer
argument that denotes the index tokenizer now takes exactly the path the
injected argument takes. Measured parity: with a postprocessor index the
two forms return the same rows in every combination of use_skip_indexes
and query_plan_direct_read_from_text_index. The divergence between an
index-using and a non-index-using query is the one the function
documentation already describes as tolerated for the two-argument form.

The tokenizer-mismatch check is untouched: an argument naming a different
tokenizer still falls back to a full scan, which is what protects against
the wrong results of ClickHouse#108808 and ClickHouse#107186.

acceptsTokenizerArgument is folded into tokenizerArgumentMatchesIndex; it
had no other caller and both call sites always used the two together.

02346_text_index_function_hasPhrase_postprocessor had a cell asserting
that the three-argument form bypasses the index. That is the behaviour
being changed, so it now asserts parity with the two-argument form, and a
mismatching-tokenizer case is added beside it to keep the full-scan
boundary pinned.
The transform sections listed rows from the two-argument and three-argument
forms next to each other, so a reader had to compare them by eye and a
divergence between the two would still have matched the reference as long
as both lists were recorded.

Each pair is now one query that emits a row only when the two forms
disagree, so the expected output is empty. Verified live: against a binary
that keeps the old transform bail-out the assertions print the disagreeing
pairs ([1,4] vs [] and [1,4] vs [1,2,3,4,5]), and against this commit they
print nothing. The plain row listings are kept so a change in which rows
match is still visible.
…tor list

When a text index has a postprocessor, the row-level rewrite hands hasPhrase
its haystack as the postprocessed tokens joined by a space and re-tokenizes
that string with the index tokenizer. A splitByString separator list may not
reproduce the stored token sequence from that string: separators that do not
contain a space merge all tokens into one, and a postprocessor can also turn a
stored token into a configured separator, which drops it and makes
non-consecutive tokens look consecutive. Both lose or invent phrase matches,
and which one applies depends on the postprocessed token values, which are not
known while planning. Before the explicit-tokenizer support in this PR the
three-argument form always full-scanned, so neither was reachable.

The predicate now refuses that combination and the query falls back to a full
scan, which is what a mismatching tokenizer already does. Only hasPhrase is
affected: hasAnyTokens and hasAllTokens receive the postprocessed tokens as an
array matched verbatim with the array tokenizer, and character-sliding
tokenizers keep a phrase a substring of the joined haystack. Measured on
splitByString(['()']), splitByString(['-']), splitByString([' ']),
splitByString([' ', 'x']), splitByNonAlpha, ngrams(3), asciiCJK and icu: only
the splitByString cases diverged from a full scan.

Reported by an automated review of this PR.
A postprocessed hasPhrase rejoins the index tokens with a space and re-splits them, so a
token containing a token separator cannot be represented and the rewrite refuses it. The
two-argument form on master already refuses such a phrase; before the tokenizer-argument
check the three-argument form answered it from the index instead, so the two forms
disagreed on the same predicate.

An automated reviewer asked for the opposite change - fall back to a full scan for every
tokenizer whose postprocessed tokens cannot round-trip. That is not decidable while
planning: with tokenizer = splitByNonAlpha and postprocessor = concat(doc, ' z') the same
refusal appears, and isTokenSeparator implements splitByNonAlpha's own rules, so the
condition depends on the postprocessed token values rather than on the tokenizer. Falling
back also drops the postprocessor from the predicate, which returns no rows where the
two-argument form returns one, trading a shared loud error for a silent disagreement.

Pin the parity instead, so a later widening cannot reintroduce the divergence unnoticed.
The refusal happens while the predicate is rewritten, so it does not depend on whether the
index is then read directly. Assert it for both values of the setting, and record that the
same phrase simply does not match when the index is not used at all, so the assertion
cannot be satisfied by the query failing for an unrelated reason.
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.
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (the branch was 5092 commits behind and conflicting). One conflict, in selectConditions in optimizeDirectReadFromTextIndex.cpp, where #113154 replaced the None-mode branch condition. I resolved it as a union: the canAnswerFunctionNode check keeps its place ahead of the branch, and the new is_index_analyzed binding and widened condition are taken unchanged.

#113154 also applies the index tokenizer, preprocessor and postprocessor to the row-level evaluation, not only to the index read, so two expectations in 04353_text_index_explicit_tokenizer_argument no longer described the behaviour:

  • The stop-word case. hasAnyTokens for a term the postprocessor maps to the empty string used to return rows when the index was not read, and now returns nothing in every combination, which is what the two-argument form returns too. Measured on the merge and on a pre-Text index: inject tokenizer properly to supported functions outside WHERE/PREWHERE #113154 master: before, the two-argument form returned no rows at use_skip_indexes = 1 and rows 1 and 4 at use_skip_indexes = 0; after, both forms return nothing under either setting. The parity this test pins still holds, and it is no longer pinned on a value where the index and the scan disagreed with each other. I added a search for a term the postprocessor keeps next to it, so an empty result there cannot be read as a table that matches nothing.
  • The separator-spanning hasPhrase case used use_skip_indexes = 0 to show the phrase does not occur literally. The postprocessor applies on that path now as well, so that query raises the same BAD_ARGUMENTS as the four assertions above it and no longer witnesses anything. It uses position instead, which reaches neither the index nor the postprocessor.

All 190 text_index stateless tests ran against the merge: 184 pass, and the 6 failures are environmental here (three test clusters and an access-control profile my config lacks, the absent test.hits dataset, and one test that reads its own LOG_DEBUG lines from system.text_log, which passes once the server logs at debug).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5aa7935

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / STID 0250-3e49, Not-ready Set is passed as the second argument for function 'globalIn' trunk defect, not caused by this PR #112968 (external, open)

CI is fully finished at this head: 175 unique check runs, 0 incomplete, one parent workflow run
(33077779475), and Config Workflow, Style check and Finish Workflow all success. The praktika
report has 177 nodes, 0 DROPPED. CIDB returns 306k+ rows at this commit, of which exactly the failure
above is ownable, so the classification is a measurement and not an empty read.

The owner is resolved from the stack frames rather than from the STID, because the Not-ready Set
bucket pools several distinct defects. This abort runs
FunctionIn::executeImpl (src/Functions/in.cpp:128) <- VirtualColumnUtils::filterBlockWithExpression
<- VirtualColumnUtils::getFilterByPathAndFileIndexes <- StorageObjectStorageSource::createFileIterator
<- ReadFromObjectStorageStep::createIterator, i.e. the object-storage _path / _file prune shape,
which is what #112968 ("Fix Not-ready Set for GLOBAL IN over an object-storage _path / _file filter")
changes: StorageObjectStorageSource.{cpp,h}, StorageObjectStorage.cpp, StorageFile.{cpp,h} and
StorageURL.{cpp,h}. It is open, so it cannot already be present on this branch.

Not caused by this PR: over 30 days that sub-shape measures 58 rows across 47 distinct PRs with 6
true-master hits (a fabricated-phrase control returns 0), against a diff that does not touch the
object-storage read path.

Session id: cron:our-pr-ci-monitor:20260827-190000

@Ergus

Ergus commented Aug 28, 2026

Copy link
Copy Markdown
Member

@CurtizJ and @rschu1ze how are the plans to merge this PR?

The PR #116339 to fix #115999 has a limitation with parallel_replicas that I cannot solve without re-implementing part of these changes and then heavily conflicting with this PR. So I prefer to wait for this to be merged and then work over it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Ergus I do not decide the schedule, but here is the state of this PR, all re-checked just now, so nobody has to dig.

Head 5aa7935f7610517a440afe1cd4313183b57e2600, unchanged since 2026-08-27, master merged in, MERGEABLE. CI has finished on it, nothing queued; finish ledger: #115348 (comment). The only test red is Stress test (arm_msan) with Not-ready Set is passed as the second argument for function 'globalIn', frames in the object-storage _path/_file prune path, i.e. #112968 (open). Not caused by this PR: 58 hits across 47 unrelated PRs and 6 master runs in 30 days, and my diff does not touch that read path. CH Inc sync is the private sync, and the red Mergeable Check follows from those two. can be tested has been on since 2026-08-19.

Every point from @ CurtizJ, including the explicit tokenizer-match safety check, and the six inline comments from @ rschu1ze are implemented and answered, plus three bot rounds. There is no open change request, so this is waiting on review only.

On your dependency: in optimizeDirectReadFromTextIndex.cpp my diff is +12/-3 in three hunks, all inside TextIndexDAGReplacer (a canAnswerFunctionNode guard before the rewrite, the arity bound widened to 3, and the tokenizer argument assigned instead of pushed so the injection is idempotent), and MergeTreeIndexConditionText.h gets one declaration. None of that touches the plan walk or the step crossing where the parallel replicas shape you pinned off lives, so that part should not need any of it re-implemented. Meanwhile I will not push anything to this branch that is not asked for.

@CurtizJ

CurtizJ commented Aug 28, 2026

Copy link
Copy Markdown
Member

Let's merge this PR.

CurtizJ and others added 2 commits August 28, 2026 17:45
The three-argument form no longer refuses a `splitByString` index that
carries a postprocessor, so both spellings of `hasPhrase` take the same
path again.

Co-Authored-By: Claude Opus 5 <[email protected]>
Removing the splitByString carve-out lets the three-argument hasPhrase reach a
postprocessed splitByString index, so the two arms that pinned the refusal no
longer describe the code: one asserted INDEX_NOT_USED, the other recorded the
rows the unrewritten predicate returned.

They now assert what the shared path gives. Each fixture compares the three
argument spelling against the two-argument one at both values of
use_skip_indexes, and force_data_skipping_indices is asserted to succeed rather
than to throw. The .reference file is unchanged.

Measured on this head: the three-argument answers are exactly the answers a
pristine master gives the two-argument spelling, [] for the '()' separator
fixture and [1] for the fixture whose postprocessor emits a separator, at
use_skip_indexes 0 and 1 alike. Restoring the carve-out reddens all five arms:
the four comparisons print a disagreeing row and both force_data_skipping_indices
queries throw INDEX_NOT_USED.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fast test was red on 26f5543f: 04353_text_index_explicit_tokenizer_argument still asserted the refusal that commit removes. Fixed in 1adc14ce, test only, no source change.

Before touching the test I measured what the three-argument form does now, using a pristine master snapshot (438a6180) as the control:

fixture master, 2-arg this head, 2-arg this head, 3-arg 3-arg before 26f5543f
splitByString(['()']) + lower(doc), doc = 'a()bc()d', phrase 'bc()d' [] [] [] [1]
splitByString([' ', 'x']) + lower(doc), doc = 'A X B', phrase 'a b' [1] [1] [1] []

Every cell is the same at use_skip_indexes 0 and 1, so there is no index-versus-scan divergence to report. The two spellings now return the same rows, and those rows are the ones master already gives the two-argument spelling. The carve-out was the thing that made the two spellings disagree (last column). force_data_skipping_indices = 'idx' succeeds on both fixtures now.

The arms that pinned the refusal are retargeted at that property: each fixture compares the three-argument spelling against the two-argument one at both values of use_skip_indexes, and force_data_skipping_indices is asserted to succeed rather than to throw INDEX_NOT_USED. The .reference file is unchanged. Restoring the carve-out reddens all five arms (four print a disagreeing row, both force_data_skipping_indices queries throw 277), so they do not pass by construction.

I did not squash, since that would rewrite your commit.

One property this does not change, in case it matters for the merge: with a postprocessor, hasPhrase searches the stored tokens rejoined with a space, so its answer can differ from the literal text. In the first fixture position(doc, 'bc()d') > 0 returns row 1 where the phrase search returns nothing, and the second fixture matches a phrase that is not literally consecutive. Both hold for the two-argument spelling on plain master.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1adc14ce8ac94e8562042069781a7945374057dc

CI is fully finished on this head: 172 praktika nodes as 150 OK, 19 skipped by digest and 3 FAIL
(the failing leaf, its check, and the PR roll-up). Config Workflow, Style check and
Finish Workflow are all success, and 0 nodes are DROPPED. The one failure has an owner and is
not caused by this PR.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: 'Not-ready Set is passed as the second argument for function 'globalNotIn'' (STID 0250-41a5), Failures: 1/5 trunk logical error, server abort in a build with abort_on_logical_error. A speculative in-place IN-set build takes the destructive path for a source plan that cannot be cloned and then stops without creating the set and without throwing, so FutureSetFromSubquery::build returns a null plan, every caller reads that as nothing left to build, and FunctionIn throws at src/Functions/in.cpp:128 once the main pipeline evaluates the condition. src/Interpreters/PreparedSets.cpp:536-560 names this residual in master itself. 230 CIDB rows over 177 distinct pull requests in 30 days, 22 of them on master, first seen 2026-07-30, most recent 2026-08-29 01:31Z. This diff touches only the text-index skip-index condition and its tests, so it cannot reach that path. #102308 (external, open)

That PR is the remedy for this residual rather than a same-area coincidence: it makes the
subquery plan rebuildable after a failed in-place build and builds into a temporary Set, so a
partial build cannot leak. Tracking issue: #107619.

Session id: cron:our-pr-ci-monitor:20260829-020000

@CurtizJ
CurtizJ added this pull request to the merge queue Aug 29, 2026
Merged via the queue into ClickHouse:master with commit 3cb479d Aug 29, 2026
173 of 175 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 31, 2026
Resolves one conflict in MergeTreeIndexConditionText.cpp, where master's
explicit-tokenizer overload (ClickHouse#115348) and this branch's LIKE ESCAPE fold both
claim the three-argument branch of traverseAtomNode.

Both are kept. The LIKE ESCAPE case is checked first because it is gated on the
function name and returns on every path; tokenizerArgumentMatchesIndex accepts
only hasAnyTokens, hasAllTokens and hasPhrase, so with the order reversed it
would reject like/ilike before the fold ran and the index would stop answering
LIKE ... ESCAPE. Everything else with three arguments still goes through
master's tokenizer check.

Merged master commit: 595bd75
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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

Development

Successfully merging this pull request may close these issues.

Text index is never used when hasAnyTokens/hasAllTokens/hasPhrase are called with an explicit tokenizer argument

6 participants