Repository navigation
Use the text index when a tokenizer argument matches the index tokenizer - #115348
Conversation
…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.
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 Round 1 (commit
|
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.
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.
|
Workflow [PR], commit [1adc14c] Summary: ❌
AI ReviewSummaryThis PR makes the explicit-tokenizer overload of Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 1adc14c.
Changed lines: Changed C/C++ lines covered: 44/47 (93.62%) · Uncovered code |
Pre-PR validation gate (click to expand)
Validation: 181/182 of the Four negative controls confirm each guard is load-bearing rather than trivially green: weakening the |
|
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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units31 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 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.
CI finish ledger: 872d20eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The failing assertion is not in this branch. praktika builds the merge commit, so master's 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.
|
Merged master (the branch was 5092 commits behind and conflicting). One conflict, in #113154 also applies the index tokenizer, preprocessor and postprocessor to the row-level evaluation, not only to the index read, so two expectations in
All 190 |
CI finish ledger - 5aa7935Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
CI is fully finished at this head: 175 unique check runs, 0 incomplete, one parent workflow run The owner is resolved from the stack frames rather than from the STID, because the Not caused by this PR: over 30 days that sub-shape measures 58 rows across 47 distinct PRs with 6 Session id: cron:our-pr-ci-monitor:20260827-190000 |
|
@CurtizJ and @rschu1ze how are the plans to merge this PR? The PR #116339 to fix #115999 has a limitation with |
|
@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 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 |
|
Let's merge this PR. |
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]>
|
Before touching the test I measured what the three-argument form does now, using a pristine master snapshot (
Every cell is the same at 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 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, |
CI finish ledger -
|
| 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
3cb479d
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
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
textindex is now used forhasAnyTokens,hasAllTokensandhasPhrasecalled 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::traverseAtomNoderejected any non-binary function node before looking at the function name, so a three-argumenthasAnyTokens/hasAllTokens/hasPhrasenever reachedisSupportedFunction. 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-splitByNonAlphatokenizer 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 notngrams(4)). A different, non-constant or invalid argument still full-scans, without raising an error.An index carrying a
preprocessororpostprocessorbehaves 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:
hasPhraseon apostprocessorindex with asplitByStringtokenizer. The row-level rewrite handshasPhrasethe 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.hasAnyTokensandhasAllTokensare unaffected (tokens matched verbatim as an array), as aresplitByNonAlpha,ngrams,asciiCJKandicu.hasPhraseis 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. In04353that 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]