Skip to content

Rewrite arrayExists over tokens() to hasTokenLike/hasTokenMatch so it can use a text index - #122071

Draft
valerypetrov wants to merge 77 commits into
ClickHouse:masterfrom
valerypetrov:text-index-array-exists-tokens
Draft

valerypetrov wants to merge 77 commits into
ClickHouse:masterfrom
valerypetrov:text-index-array-exists-tokens

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Related: #121831 (this PR is based on it and needs it merged first)

Why

A token search can be written as arrayExists(x -> startsWith(x, 'charg'), tokens(message)), or with endsWith, position(x, 'nnec') > 0, LIKE or match in the lambda. Each row is then tokenized, and the text index on message is not used, because index analysis does not look into the lambda. This branch carries hasTokenLike and hasTokenMatch from an earlier version of #121831. They compute the same predicates and are answered from the index dictionary.

What

RewriteArrayExistsToHasPass also rewrites arrayExists(x -> f(x, c), tokens(s[, tokenizer])) when the lambda has one argument and its body is one of:

lambda body rewritten to
startsWith(x, c) hasTokenLike(s, escaped(c) || '%', t)
endsWith(x, c) hasTokenLike(s, '%' || escaped(c), t)
position(x, c) > 0 hasTokenLike(s, '%' || escaped(c) || '%', t)
like(x, p) hasTokenLike(s, p, t)
match(x, re) hasTokenMatch(s, re, t)
  • c, p and re are constant strings.
  • escaped escapes %, _ and \.
  • t is the tokenizer of tokens(), or splitByNonAlpha if tokens() has none.

The rewrite is controlled by the new setting optimize_rewrite_array_exists_over_tokens, which is off by default.

Design decisions

  • startsWith becomes hasTokenLike, not hasTokenPrefix. When the index on s has a lower or upper preprocessor, hasTokenPrefix applies it to the input and the prefix, even with use_skip_indexes = 0. Then hasTokenPrefix(s, 'Ab') also matches ABC, but arrayExists(x -> startsWith(x, 'Ab'), tokens(s)) does not. hasTokenLike never applies a preprocessor or a postprocessor. Without a preprocessor the index runs the same search for both: hasTokenPrefix(s, c) is compiled to the LIKE pattern escaped(c) || '%', and that pattern seeks to the token range of the prefix. The pass therefore does not need to read index definitions. It could not see them for a Distributed table anyway.
  • The tokenizer is always passed. Without it, the functions would take the tokenizer of the index on s. With it, the index is used only if its tokenizer is the same. Otherwise the function runs on the rows with the tokenizer of tokens(). For tokens(s, 'T') the same string T is passed on, so both call the tokenizer factory with the same definition. Tokenizer parameters in separate arguments, as in tokens(s, 'ngrams', 3), are not rewritten.
  • s must be String or FixedString. With Nullable or LowCardinality input the functions return Nullable(UInt8) or LowCardinality(UInt8), while arrayExists returns UInt8.
  • A separate setting, off by default. The rewritten query is what a Distributed table or parallel replicas send to other servers, and hasTokenLike/hasTokenMatch are new in 26.11. A server older than 26.11 would reject the query with UNKNOWN_FUNCTION during a rolling upgrade. The setting is recorded under 26.11 in the settings history. The has() rewrite keeps optimize_rewrite_array_exists_to_has.
  • Invalid patterns. An invalid LIKE pattern or regexp now raises its error even when no row has a token. Before, arrayExists did not evaluate the lambda in that case.
  • tokens(lower(s)). It is served by an index defined on the expression lower(s). An index on s with preprocessor = lower(s) is not used for it.
  • Shared helper. escapeForLikePattern moves from MergeTreeIndexConditionText.cpp to Common/likePatternToRegexp so the pass can use it.

Local timing

3M log rows as in the performance test text_index_array_exists_tokens, in two versions: with a unique request number in every message (3,000,011 distinct tokens) and without it (1,011 distinct tokens). max_threads = 4, query condition cache off, Apple M4, median of 20 runs; a second round was within 2 ms. Each pair returns the same count. "Before" is the query as written, on a build of #121831. "After" is the call this pass produces, written out by hand, on the same build.

query 3M tokens: before → after, ms 1K tokens: before → after, ms
startsWith(t, 'charg'), index on message 69 → 1 (69x) 55 → 1 (55x)
endsWith(t, 'rged'), index on message 69 → 39 (1.8x) 57 → 1 (57x)
position(t, 'harg') > 0, index on message 59 → 39 (1.5x) 49 → 1 (49x)
like(t, 'ch%ed'), index on message 99 → 63 (1.6x) 86 → 1 (86x)
match(t, '^charg(ed|ing)$'), index on message 58 → 39 (1.5x) 48 → 1 (48x)
startsWith, tokens(lower(message)), index on lower(message) 68 → 1 (68x) 55 → 1 (55x)
like, tokens(lower(message)), index on lower(message) 100 → 63 (1.6x) 86 → 1 (86x)
match, tokens(lower(message)), index on lower(message) 57 → 40 (1.4x) 48 → 1 (48x)
position(lower(message), 'charg') > 0 AND the startsWith form 15 → 11 (1.4x) 10 → 8 (1.2x)
startsWith(t, '1'), too many matching tokens, the index gives up 83 → 80 (1.0x) 70 → 65 (1.1x)
startsWith, table without a text index 67 → 37 (1.8x) 54 → 27 (2.0x)
match, table without a text index 57 → 41 (1.4x) 47 → 31 (1.5x)
like in the SELECT list 99 → 75 (1.3x) 98 → 62 (1.6x)

CI's performance test text_index_array_exists_tokens measures the startsWith(t, '1') query slower with the rewrite: 88 → 120 ms on arm_release and 87 → 135 ms on amd_release. Locally it is not slower (CI build of b54d47e, median of 11 runs: 137 ms with the rewrite, 164 ms without; startsWith(t, 'charg'): 8 ms with, 191 ms without). So the rewrite is off by default.

Only a prefix seeks in the dictionary; the other patterns scan all of it. With 3M distinct tokens that scan takes about 39-63 ms, so those queries gain what the function saves over tokenizing each row into an array, the same saving the rows without an index get. With 1K distinct tokens every shape is answered from the dictionary.

Testing

  • 05255_array_exists_tokens_to_has_token_functions covers each lambda shape:
    • the same rows with the rewrite on and off, with use_skip_indexes = 0, and on a table without the index, plus NOT and the SELECT list;
    • the rewritten query tree, granule pruning and direct read;
    • the shapes that are not rewritten, including Nullable and LowCardinality input;
    • an index with a lower preprocessor, an index on lower(msg), LIKE metacharacters in the needle, and FixedString input;
    • the rewrite being off by default.
  • A new performance test, text_index_array_exists_tokens.xml, with the queries of the table above and the four non-prefix shapes on the 1K-token data; each query enables the setting.
  • Each arrayExists form was compared with a hand-written hasTokenLike or hasTokenMatch equivalent:
    • 1650 queries over 1500 random rows under 5 tokenizers. The rows contain %, _, \, ], NUL, newlines, invalid UTF-8 and multi-byte characters.
    • 784 queries, and their negations, on tables with 7 text index definitions: lower preprocessor, lower postprocessor, array, ngrams, sparseGrams, splitByString and splitByNonAlpha.
    • No row differs.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Queries such as arrayExists(x -> startsWith(x, 'err'), tokens(s)) are rewritten to hasTokenLike or hasTokenMatch, so they can use a text index on s. This covers startsWith, endsWith, position, LIKE and match in the lambda, and is controlled by the setting optimize_rewrite_array_exists_over_tokens.

🤖 Generated with Claude Code


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

valerypetrov and others added 18 commits September 23, 2026 11:48
They check whether any token of the input starts with a prefix, matches a
`LIKE` pattern or matches a regular expression. The text index finds the
matching dictionary tokens and reads their posting lists; since the pattern
is applied per token, the result is exact and eligible for direct read.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Stateless tests for the semantics without an index and for the text index
path (pruning, direct read, tokenizer mismatch, fallback on too many
postings, `Nullable` and `Array(String)` columns, preprocessor), and a
performance test against the `arrayExists(tokens(...))` formulation.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The dictionary scan of a pattern (`LIKE`, `ILIKE`, `startsWith`, `endsWith`,
`hasTokenPrefix`, `hasTokenLike`, `hasTokenMatch`) is abandoned when the pattern
matches more tokens than this, and the predicate is evaluated on the column.
`text_index_like_max_postings_to_read` counts only large postings, so a pattern
matching a million rare tokens collected all of them and was 50 times slower than
the column scan. The default 20000 is the measured break-even on 10 million rows.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…enLike` and `hasTokenMatch`

As for `hasAnyTokens`, the functions without the tokenizer argument use the
tokenizer of the text index. `hasTokenPrefix` applies the `lower` or `upper`
preprocessor of the index to the input and the prefix. A pattern cannot be
preprocessed, so `hasTokenLike` and `hasTokenMatch` do not use an index with a
preprocessor.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… `hasTokenMatch`

Move the `lowerUTF8` preprocessor case into its own `no-fasttest` test,
because the Fast test build has no ICU and fails with `UNKNOWN_FUNCTION`.

Link the new functions and the `text_index_like_max_matched_tokens` setting to
their reference pages without anchors: the anchors only appear once the
reference docs are regenerated, so the internal links check rejected them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…h` depend only on the index definition

The functions were rewritten with the index tokenizer and preprocessor only if
the index could serve them, so e.g. `use_text_index_like_evaluation_by_dictionary_scan = 0`,
an empty needle, or an index with a preprocessor made `hasTokenPrefix` on an
`array` index fall back to `splitByNonAlpha` and return other rows.

Now the index condition always returns a query for them when the column has the
index, one without patterns if the index cannot be used, which only carries the
rewrite. The `lower`/`upper` preprocessor of `hasTokenPrefix` is applied whenever
the index is defined, not only when the index is used. The functions no longer
take the tokenizer from an index that is analyzed for another function (e.g.
`mapKeys(m)` for `m['key']`), and do not use the index for map elements or JSON
paths. Add the functions to the support matrix in the documentation.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…okenMatch`

Check that the results do not depend on settings on `array`, `lower`, `lowerUTF8`
and `Nullable` indexes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
One conflict, in SettingsChangesHistory.cpp: master and this branch each added
a row at the top of the 26.10 block. Both are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h` with a running offset

Same `current_offset` loop as `hasAnyAllTokens`, instead of relying on the zeroed
element before the offsets for the first row. The new cases evaluate full array
columns, not constants, whose first row matches, for String, Nullable(String) and
FixedString elements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The text index condition escapes a needle into a LIKE pattern for
startsWith, endsWith and hasTokenPrefix. The arrayExists rewrite over
tokens() needs the same escaping in an analyzer pass, so the helper
moves next to likePatternToRegexp instead of being copied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Queries written as arrayExists(x -> startsWith(x, 'charg'), tokens(s))
tokenize every row and cannot use a text index on s. The same predicate
is hasTokenLike(s, 'charg%', 'splitByNonAlpha'), which the index answers
from its dictionary. RewriteArrayExistsToHasPass now rewrites a
one-argument lambda over tokens(s[, tokenizer]) whose body is
startsWith, endsWith, position(...) > 0, like or match of the lambda
argument and a constant.

startsWith maps to hasTokenLike rather than hasTokenPrefix: when the
index on s has a lower or upper preprocessor, hasTokenPrefix applies it
and turns a case-sensitive prefix search into a case-insensitive one,
while hasTokenLike never applies a preprocessor. The tokenizer is always
passed, so the function does not take it from an index. Nullable and
LowCardinality inputs are skipped, since the function would not return
UInt8 there, as are tokenizer parameters in separate arguments.

The rewrite reuses optimize_rewrite_array_exists_to_has. The existing
tests of the functions now pin it to 0 where arrayExists is the
reference result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two text indexes can serve the same expression although a column may
have only one: an index on `if(s != '', s, 'none')` is matched through
its normalized name `if(notEmpty(s), s, 'none')`, which another index
can have literally. Both conditions were then selected, the tokenizer
and preprocessor rewrite of `hasTokenPrefix`, `hasTokenLike` and
`hasTokenMatch` was skipped, and each index still pruned granules with
its own tokenizer, so the result changed with `use_skip_indexes` and
direct read.

Now every text index analyzed for such a function must give it the same
tokenizer and the same applied preprocessor (only `lower` or `upper`,
and only for `hasTokenPrefix`). If they agree, the index with the first
name serves the function, so the rewrite always happens and the choice
does not depend on hash order. If they disagree, the function throws
BAD_ARGUMENTS in the rewrite pass, which covers the filter and the
SELECT list whether or not an index is used. An explicit tokenizer
argument leaves only the indexes with that tokenizer. The selection for
other text-search functions is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rewritten query is what a Distributed table or parallel replicas send
to other servers, and hasTokenLike and hasTokenMatch are new in 26.10, so
a server older than that rejects it with UNKNOWN_FUNCTION during a rolling
upgrade. Under optimize_rewrite_array_exists_to_has, whose default does not
change in 26.10, `compatibility` could not turn the rewrite off.

The new setting optimize_rewrite_array_exists_over_tokens has a 26.10
history entry, so `compatibility` 26.9 or older disables the rewrite. The
has() rewrite keeps its own setting. 05255 checks both the default and the
compatibility case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ardinality

EXPLAIN actions = 1 prints the filter as `Filter column: arrayExists(...)`
and never as `FUNCTION arrayExists(`, so the second column of the direct
read check was 0 with and without the rewrite. Match `arrayExists(`
instead, which is 1 on the arrayExists form and 0 on the rewritten one.

Also check that LowCardinality input is not rewritten, since hasTokenLike
would return LowCardinality(UInt8) there while arrayExists returns UInt8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…f test

Adds startsWith, like and match over the index on the column, a substring
prefilter next to the token predicate, a prefix that matches too many
dictionary tokens for the index, a table without a text index, and the
SELECT list, so the comparison also shows the cases where the rewritten
function is evaluated on every row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With about 1000 distinct tokens instead of 3 million, the patterns that are not
a prefix are answered from the dictionary quickly too, so the comparison shows
both ends of the dictionary scan cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 24, 2026
valerypetrov and others added 11 commits September 24, 2026 14:41
Text index tests live under 02346: the test without an index follows
`02346_function_hasPhrase`, the one with an index follows
`02346_text_index_function_hasAnyAllTokens`. The `log_comment` values
lose the old number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`hasTokenPrefix` applied a `lower` or `upper` preprocessor of the index
to its input and prefix, but only where the text index rewrite pass
reaches: in filters and projections over the table. After `GROUP BY` or
in `ALTER TABLE DELETE` it saw the raw values, so with a `lower` index
`WHERE hasTokenPrefix(msg, 'charg')` matched `Charged` rows while the
same call after `GROUP BY msg` did not.

Now none of the three functions applies a preprocessor, like
`hasTokenLike` and `hasTokenMatch` already did: an index with a
preprocessor or a postprocessor is not used by them, and they see the
raw values. What remains shape dependent is the default tokenizer taken
from the index, as for `hasAnyTokens`; the comments and the function
docs now say where it applies, and that an explicit tokenizer argument
gives the same result everywhere. Several indexes on one expression now
only need the same tokenizer.

The `lowerUTF8` test is dropped: every preprocessor now takes the same
path, and its array-tokenizer case moves into the main test. A new test
pins the default tokenizer after `GROUP BY` and in `ALTER TABLE DELETE`,
and that a `lower` index gives the raw-value result in every shape.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Match

The new cap on matched dictionary tokens also applied to `LIKE`,
`ILIKE`, `startsWith` and `endsWith`, so existing queries whose pattern
matches many tokens could switch from the index to a full column scan
after the upgrade, without opting in. It ignores row width, so on wide
rows that scan can cost more than the dictionary scan it replaces.

Now only the tokens matched by a pattern of `hasTokenPrefix`,
`hasTokenLike` or `hasTokenMatch` are counted, and the pre-existing
functions keep their plan. The scan is shared by all pattern queries on
an index, so once the cap trips, a `LIKE` in the same filter is
evaluated on the column as well, as with
`text_index_like_max_postings_to_read`. The setting description, its
history entry and the `TextIndexDiscardPatternScan` description say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`executeImpl` compiled the `LIKE` pattern or regexp and parsed the
tokenizer description on every call. Both arguments are always
constant, so they are now built once per function object under
`std::call_once`, as `transform` does. `Regexps::get`, the global regexp
cache, no longer exists, and `Regexps::LocalCacheTable` is meant for
non-constant patterns.

The compiled regexp is immutable and shared between threads. Tokenizers
are shared as well unless they are stateful (`sparseGrams`, `japanese`),
which are cloned per call, as in `hasAnyTokens`. A test runs a stateful
tokenizer over many blocks and threads against `arrayExists` over
`tokens`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The links to the functions and to `text_index_like_max_matched_tokens`
get their anchors. The footnote of the three functions becomes ⁵ and
the `keyValuePairs` note ⁶, so the notes are listed in order. The table
row, the footnote and the section say that the functions never apply a
preprocessor, where the tokenizer of the index is used, and that the
matched-token cap applies only to them, not to `LIKE`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The functions give the same result with the index, with
`use_skip_indexes = 0` and without direct read for:
- an index with a postprocessor, which the functions do not use;
- a map element with indexes on `mapKeys(m)` (prunes by the key, the
  function keeps `splitByNonAlpha`) and `mapValues(m)` (not used), and
  the same for a JSON path with `JSONAllPaths` and `JSONAllValues`;
- a `LowCardinality(String)` column, answered by direct read;
- `ngrams`, `sparseGrams`, `splitByString` and `asciiCJK` indexes,
  checked against `arrayExists` over `tokens` with the same tokenizer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n the query plan

Without the tokenizer argument, whether a call gets the index tokenizer depends on
the plan, not only on the query shape: `HAVING hasTokenPrefix(tag, 'prod')` on a
grouping key is pushed down to the table and gets it, and with
`query_plan_filter_push_down = 0` it does not (1 vs 2 groups on an `array` index,
as for `hasAnyTokens`). The docs and the function description now say so, the
"does not depend on settings" claim is scoped to an explicit tokenizer, and the
query shapes test pins HAVING with push-down on and off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When several text indexes agree on the tokenizer, the function was served by the
first of them by name, even an index with a preprocessor or a postprocessor that
only carries the tokenizer, so a plain index on the same expression was skipped
and the query evaluated the function on every surviving row. The first index that
answers the function by a dictionary scan now serves it. The tokenizers agree, so
results do not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The dictionary scan looked up every matching pattern in the set of per-token
patterns, also for LIKE, ILIKE, startsWith and endsWith scans that have none.
The lookup now runs only while a per-token pattern exists and none has matched
the token yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es no behaviour

The cap applies only to hasTokenPrefix, hasTokenLike and hasTokenMatch, which are
new, so the history entry keeps the default for older compatibility versions.
The description no longer quotes a 50x slowdown whose query is unknown: on 10M
rows of 'id' || number, hasTokenPrefix(Body, 'id1') (1111111 matching tokens)
took 973 ms uncapped against 28 ms with use_skip_indexes = 0 (median of 7).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
endsWith(msg, '5') scans the dictionary for 200 tokens ending in 5 (with
text_index_like_min_pattern_length = 1) and keeps its pruning at a cap of 100.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 2 commits November 6, 2026 09:28
typeid_cast matches only the exact type, and every Enum is a DataTypeEnum<T>, never
IDataTypeEnum itself. So the Enum key lookup added for m.key_<name> never ran, and
02346_text_index_function_hasTokenPrefixLikeMatch_enum_map_key still read 0 rows
instead of 64 under the default optimize_functions_to_subcolumns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts: master added `TextIndexAutomatonBudgetPtr automaton_budget_` to the
MergeTreeIndexConditionText constructor next to this branch's
`index_required_columns_`, so both are kept; master's DFA pattern cursors are
kept next to this branch's per-token pattern set in TextIndexAnalyzer; in
ProfileEvents.cpp master's `TextIndexDictionaryDFABuilds` row is kept next to
this branch's wording of `TextIndexDiscardPatternScan`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Their TextSearchQuery was built without the shared automaton budget, so every partition condition
compiled its own DFAs with no total limit. They now pass the budget like LIKE does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
if (condition.getHeader().columns() != 1)
continue;

auto search_query = condition.createTextSearchQuery(canonical_node);

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.

[Blocker] Preserve the index tokenizer when constants in the indexed expression are folded

canonical_node contains folded constants, while MergeTreeIndexConditionText matches against the index's original expression name. If the index contains a constant expression, this lookup finds no candidate and the new functions silently use splitByNonAlpha instead of the index tokenizer. This changes results even when the query uses exactly the expression from the index definition.

Reproduced with the current PR-head Fast test binary:

CREATE TABLE t
(
    id UInt64,
    tag String,
    INDEX idx(concat(tag, toString(1))) TYPE text(tokenizer = array)
) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number, 'env:prod-eu' FROM numbers(64);
SELECT count() FROM t
WHERE hasTokenPrefix(concat(tag, toString(1)), 'env:prod'); -- 0
SELECT count() FROM t
WHERE hasTokenPrefix(concat(tag, toString(1)), 'env:prod', 'array'); -- 64

Declaring the otherwise identical index on concat(tag, '1') makes the first query return 64. hasTokenLike and hasTokenMatch have the same failure, including with use_skip_indexes = 0; typed map-key expressions also hit it. Please normalize the index definition and query through the same expression representation before index/tokenizer matching, and add a regression covering these equivalent definitions. Another key-type-specific string reconstruction would leave the scalar-expression case broken.

Master changed `traverseMapElementValueNode` to take the function node
and check the map value default; keep that signature next to this
branch's `hasIndexForMapElementSubcolumn`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
const auto context = Context::getGlobalContextInstance();
if (auto resolver = FunctionFactory::instance().tryGet(function->name, context); resolver && resolver->isDeterministic())
{
if (auto result = tryEvaluateConstantExpression(ast, context); result && WhichDataType(result->second).isString())

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.

[Blocker] Honor constant-folding eligibility when normalizing index expressions

isDeterministic does not imply that a call can be evaluated as a constant. For example, materialize is deterministic but deliberately disables constant folding. Passing it to tryEvaluateConstantExpression throws BAD_ARGUMENTS (result column not found). Because this normalization runs in the MergeTreeIndexText constructor, it now prevents writes to an otherwise valid table, even with the new rewrite disabled.

Reproduced with the PR-head Fast test binary:

CREATE TABLE t
(
    id UInt64,
    s String,
    INDEX idx(concat(s, materialize('1'))) TYPE text(tokenizer = array)
)
ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number, 'env:prod-eu' FROM numbers(64);
-- BAD_ARGUMENTS while evaluating materialize('1')

CREATE succeeds, but INSERT fails. The identical insertion and subsequent query succeed with the earlier PR binary at cd1606825025b4c1cbef341b5c13b60f5433d0fc. Existing tables with this expression therefore also lose write availability on upgrade; background merges construct the same helper.

Please derive the normalized expression from analyzed actions that honor isSuitableForConstantFolding, preserving calls that cannot be folded, and add a regression covering insertion into this table.

…lded

The index name was normalized by evaluating every call of a deterministic function over literals, and only `String` results were kept. `materialize` is deterministic but not foldable, so an index on `concat(s, materialize('1'))` threw `BAD_ARGUMENTS` on every insert and merge. A numeric constant such as `1 + 1` in `substring(s, 1 + 1)` was not folded, so queries, which name it `substring(s, 2)`, did not find the index and its tokenizer, and `hasTokenPrefix` or `hasAnyTokens` without a tokenizer argument returned other rows than with it.

Now nothing is evaluated: the subexpressions that the index's own actions already folded to constants are replaced with literals, named the same way as `KeyCondition` names the folded constants of a query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 2 commits November 12, 2026 21:57
…text index expression

The per-token pattern functions take the tokenizer of an index on their input, found by name. The
query folds constants inside a lambda body and drops `materialize`, the index name did neither, so
`arrayMap(x -> concat(x, toString(1)), tags)` and `concat(tag, materialize('1'))` missed their index
and used the default tokenizer. The index name now does both.

The row fallback of a direct read cannot rebuild a lambda without captured columns (it becomes
`tuple()`), so these functions threw on an index over `arrayMap(x -> lower(x), tags)`. They no longer
read such an expression directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…xt index expression

The index expression DAG does not fold a constant call such as `arrayFirst(y -> 1, ['1'])`, and
inside a lambda body such a value is only an input captured from outside. The query side folds both
before naming the expression, so the names differed, the index was not found and the per-token
functions picked the default tokenizer instead of the index's. Such a node is now evaluated, with
the lambda's constant captures bound, and named as a literal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

if (node.column && isColumnConst(*node.column) && node.column->getDataType() != TypeIndex::Function)
{
ast = make_intrusive<ASTLiteral>((*node.column)[0]);

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.

[Blocker] Preserve constant types when matching and rebuilding indexed expressions

Folding a constant into an untyped ASTLiteral makes semantically different index expressions share a name. For example, a Date and its UInt16 day number both become 20454, although formatRowNoNewline serializes them differently. hasIndexForColumn then accepts the date index for the numeric expression and prunes matching rows. This also breaks existing LIKE queries with the new rewrite disabled, and disabling direct reads does not help.

Reproduced with the Fast test binary for a55bb4a0c984c7e607eafbcd314df6220b59c487:

SET use_query_condition_cache = 0;
CREATE TABLE t
(
    id UInt64,
    s String,
    INDEX idx(formatRowNoNewline('CSV', s, toDate('2026-01-01')))
        TYPE text(tokenizer = array)
) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number, 'env:prod-eu' FROM numbers(64);

SELECT count() FROM t
WHERE formatRowNoNewline('CSV', s, toUInt16(toDate('2026-01-01')))
    LIKE '%20454%'; -- 0
SELECT count() FROM t
WHERE formatRowNoNewline('CSV', s, toUInt16(toDate('2026-01-01')))
    LIKE '%20454%'
SETTINGS use_skip_indexes = 0; -- 64

There is a second occurrence of the same type erasure in convertNodeToAST (optimizeDirectReadFromTextIndex.cpp:431): a query using the original date expression gets a numeric expression as its exact-read fallback. With 64 rows inserted before adding this index and 64 afterward, hasTokenMatch(formatRowNoNewline('CSV', s, toDate('2026-01-01')), '2026-01-01', 'array') returns 64, versus 128 with indexes disabled. On a fully indexed part, forcing the dictionary-scan fallback changes 64 to 0.

Please preserve constant types in the common expression representation used for index matching and fallback reconstruction, rather than adding another type-specific exclusion. Add regressions for differently typed constants with equal Field values, unmaterialized parts, and dictionary-scan fallback.

valerypetrov and others added 5 commits November 15, 2026 16:22
…ists-tokens

Conflict in optimizeDirectReadFromTextIndex.cpp: master switched selectConditions to
VectorWithMemoryTracking, the branch added choosePerTokenPatternFunctionIndex right above it.
Both are kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…xpression

Naming the index expression evaluated every subexpression that depends only on constants. That ran
functions the query side never folds: `throwIf(materialize(1))` in an unused `if` branch made
every INSERT fail, and `identity(materialize('1'))` was replaced by its value, so the index was not
found by the same expression in a query and its tokenizer was not used. Such a subexpression is now
evaluated only if all its functions are suitable for constant folding, like the query does.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A folded constant was written into the name of the index expression as a bare literal, which keeps
the value but not the type. An index on `formatRowNoNewline('CSV', s, toDate('2026-01-01'))` got
the name of the expression with the `UInt16` day number, was used for it and `LIKE` lost rows.
Only strings, native numbers and arrays of them are named by a literal now; other constants keep
the expression, so such an index is matched like before this branch.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ists-tokens

Conflict in MergeTreeIndexConditionText.h: master added [[nodiscard]] to the const methods, the
branch added isPerTokenPatternFunction and a comment next to them. Both are kept, and the const
methods the branch adds get [[nodiscard]] too, as modernize-use-nodiscard is enabled now.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A Bool constant folded into a numeric literal shares its name with the UInt8 constant of the same value,
although toString of the two differs, so the index on one was used for the other and pruned matching rows.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 19, 2026
valerypetrov and others added 6 commits November 19, 2026 15:50
…thout the text index

`convertNodeToAST` rebuilt a constant as a bare literal, which is parsed back with the type of its
value. Since the name of a text index expression folds numeric constants, an index on
`formatRowNoNewline('CSV', s, toFloat32(0.1))` is now found, and in a part without that index the
exact read evaluated the expression with a `Float64` `0.10000000149011612` and dropped the rows.
Cast a constant to its type when the literal alone would give another one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master is now 26.12, so the settings history check requires the records of
`optimize_rewrite_array_exists_over_tokens` and
`text_index_like_max_matched_tokens` under that version. `hasTokenPrefix`,
`hasTokenLike` and `hasTokenMatch` are introduced in 26.12 as well.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The style check forbids plain std containers in src/Processors/QueryPlan.
The map stays ordered: the first candidate by index name is still the tie-break.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants