Repository navigation
Fix text-search functions on an ALIAS column ignoring the text index preprocessor and tokenizer - #130272
Fix text-search functions on an ALIAS column ignoring the text index preprocessor and tokenizer#130272groeneai wants to merge 10 commits into
Conversation
…transforms
The analyzer planner computes ALIAS columns in a separate `Compute alias
columns` step. When that step is not merged into the step that evaluates a
text-search function (a subquery projection over the ALIAS column at default
settings, or `query_plan_enable_optimizations = 0` /
`query_plan_merge_expressions = 0`), the text index rewrite has to match the
function's haystack, an input of its own step, to the index expression over
the scan columns. It did so by renaming the inputs through a map that recorded
only pure renames, so the ALIAS output (e.g. `ifNull(provider,
'default_name')`) was lost, no index matched, and `hasToken`, `hasAnyTokens`,
`hasAllTokens` and `hasPhrase` ran without the index preprocessor, tokenizer
and postprocessor:
SELECT x, hasToken(x, 'HELLO') FROM (SELECT name AS x FROM tab)
returned 0 for 'Hello World' with `preprocessor = lower(name)`, while
`SELECT hasToken(name, 'HELLO') FROM tab` returned 1.
The pass now composes the DAGs of the steps it walks into one DAG over the
scan columns (`clone(NodeMapping &)` + `mergeInplace`, which keeps node
addresses valid), the way the index analysis composes filters through the
steps below them. The text-search function is matched to an index on its node
in the composed DAG, so it matches exactly when it would in the merged plan,
while the rewrite still binds the transforms to the step's own input by name.
Each step is composed before it is rewritten, so a step above still matches
the planned expression after direct read replaced a predicate inside it. The
rename map and its conflict guard are removed.
Found by the AST fuzzer DQP oracle (setting `query_plan_enable_optimizations`)
on the seed of `02346_text_index_preprocessor`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the applyTextIndexInject parameter note (the member doc covers it) and the analogy to the index analysis; state the composition order as an invariant. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review (4 rounds, final verdict clean)Round 1 (head 6d7c6d7): 1 blocker + 3 major, all AGREEd and fixed by a redesign (compose the walked step DAGs and match on the composed expression):
Round 2 (head 79bd72e):
Round 3 (head 9845b43):
Round 4 (head 1f3042e):
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261109-065600 |
|
cc @ahmadov @Ergus, could you review this and add the |
|
Workflow [PR], commit [acd2a46] Summary: ❌
AI ReviewSummaryThe PR composes expression DAGs across plan steps so text-search functions on Findings❌ Blockers
Tests
Final Verdict❌ Block. Address or explicitly track and scope out the remaining plan-dependent results, and add the focused regression coverage. The fixed planning-resource thread was resolved; the author's dismissed cutoff thread was left unchanged. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units7 translation units recompiled, 18 s compile time in total, 7 of them have a recent master baseline. |
…ns on the composed DAG The text index rewrite composes the steps it walks into one DAG. When steps refer to a value twice, e.g. nested `SELECT if(x = 'a', 'b', x) AS x FROM (...)`, the composed expression shares subexpressions, and the canonicalization in `selectConditions` (`ActionsDAGWithInversionPushDown`) copies a shared subexpression once per reference, so planning time and memory doubled with every step. On a debug build, 18 such steps with `ORDER BY x LIMIT 1` each took 0.41 s on master and 4.8 s / 1.9 GB before this change. Count, in linear time, how many copies of shared subexpressions expanding the composed expression into a tree would make, and skip the function when that is more than for every text index expression: an expression equal to an index expression shares what it shares. This covers expressions over columns, over `rand()` or constants, and both mixed. Such plans cost as much as on master again, and less when the steps are merged and the function is in the SELECT list, which takes the same path and was exponential on master (18 steps: 5.4 s -> 0.41 s). The test gets four nested queries under `max_memory_usage = '500M'`; without this change they fail with MEMORY_LIMIT_EXCEEDED. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e length The guard from 160bbc2 counted shared non-leaf nodes, including ones that index analysis removes, so it skipped valid matches: with an index on `concat(s, lower(s))` and `splitByString([' '])`, `hasAnyTokens(concat(CAST(s, 'String'), lower(CAST(s, 'String'))), 'FOO')` returned 1 in the SELECT list (and through a subquery) instead of 0, unlike the same predicate in WHERE. It also did not look into lambda bodies, where a captured expression is expanded once per reference, so nested `arrayMap(y -> concat(y, x, x), ...)` subqueries still took exponential planning time. Replace it with a memoized lower bound of the length of an argument's name in index analysis: every column and every function except the casts, `materialize` and `not` that the analysis may remove contributes at least one character, and a lambda contributes its body with each captured expression counted once per reference. An argument that matches an index has no more such nodes than the index column name has characters (also for `mapKeys`/`mapValues`, `m['key']` and JSON subcolumns, whose wrappers add more characters to the index name than nodes to the argument), so larger arguments are skipped without expanding them and valid matches are kept. Constants are not counted: needles and tokenizers are compared by value. The test covers repeated casts and `materialize` in the SELECT list, in a subquery and in WHERE, and 26 nested subqueries whose lambda references the captured column twice. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 26 nested subqueries exceeded the stack limit of the TSan build (TOO_DEEP_RECURSION in the planner recursion over the subqueries; TSan allows only 1/20 of the stack). Reference the captured value four times per level instead of twice and nest 14 levels: the name expansion of 160bbc2 grows as 4^14 instead of 2^26, and the subquery nesting stays below the 18 levels of the checks above. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The guard added in a5134e3 skipped matching a text-search function whose composed argument had a name lower bound longer than every index column name. That skips valid matches: `m[key]` matches an index on `mapValues(m)` whatever the key is, so a long computed key made `hasAnyTokens(m[<key>], 'FOO')` skip the index tokenizer and return 1 where master returns 0 (also through a subquery and with `query_plan_enable_optimizations = 0`). Apply the bound where a step is composed instead. In each output of the steps below, a subexpression whose name lower bound is longer than every index column name cannot be a part of an indexed expression, so it is replaced by an opaque input whose name is also longer than every index column name. The rest of the output is kept, so `m[<long key>]` computed below still matches `mapValues(m)` as `m[<opaque>]`. The steps above then never expand a long subexpression, and matching itself is never skipped, so a function that matches on master still matches. Measured (debug): the bot's mapValues repro is base 0 / head 1 / fix 0 in the SELECT list, through a subquery and with optimizations off; `m[<long key>]` computed in a subquery now gets the tokenizer like the same-step form; the earlier CAST, lambda-capture and nested if-chain planning shapes stay equal to base. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - d7f067dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
20 jobs were dropped on this head and never started, among them both release builds, Session id: cron:our-pr-ci-monitor:20261109-203008 |
# Conflicts: # src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
|
🕵 Merged |
d7f067d replaced a subexpression of the steps below by an opaque input when its name lower bound was longer than every index column name, and kept a function only when one of its children was replaced. `m[key]` whose key fits the bound while the whole lookup does not therefore became opaque as a whole, so the step above could no longer match it to an index on `mapValues(m)`: with a five-branch `multiIf` key and the index tokenizer `splitByString([' '])`, `hasAnyTokens(v, 'FOO')` over `v` computed in a subquery, an ALIAS with `query_plan_enable_optimizations = 0`, and the filter form with skip indexes off returned 1 where the same-step form returns 0. A long lookup cannot match by its name, only `mapValues(m)` with any key or `mapKeys(m)` with a constant key, so replace a key that is neither constant nor already an input by an opaque input and keep the lookup. Opaque inputs are now numbered by the input count, as the key inputs are not in the replacement map. Measured (debug, base = master a33e1c1): the bot's repro is base 1 / head 1 / fix 0 through a subquery, an ALIAS at optimizations off and the filter form, equal to the same-step 0; the four- and six-branch keys stay 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (!result) | ||
| result = add_opaque_input(node->result_type); |
There was a problem hiding this comment.
[Blocker] Pruning by expression-name length still removes valid dependency-based index matches. traverseMapElementKeyNode can match an arbitrary predicate over a constant-key lookup to mapKeys(m); the haystack need not occur in the index expression's name. Here the long haystack becomes an opaque input, so the next step loses that match and silently skips the index tokenizer.
Reproduced with the Fast test binary for this exact head (87d1f8373ec1):
CREATE TABLE t
(
m Map(String, String),
v String ALIAS reverse(reverse(reverse(reverse(reverse(reverse(reverse(reverse(reverse(reverse(m['a'])))))))))),
INDEX idx(mapKeys(m)) TYPE text(tokenizer = splitByString([' ']))
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t(m) VALUES (map('a', 'FOO-QUX '));
SELECT hasAnyTokens(v, 'FOO') FROM t;
-- 0
SELECT hasAnyTokens(v, 'FOO') FROM t
SETTINGS query_plan_enable_optimizations = 0;
-- 1Computing v in a subquery with ORDER BY v LIMIT 1 also returns 1; the filter on the alias returns the nonmatching row with optimizations and skip indexes disabled. EXPLAIN PLAN actions = 1 confirms that the direct projection injects splitByString([' ']), while the subquery retains the two-argument function.
The same problem affects traverseJSONSubcolumnKeyNode: with j JSON(a String), an index on JSONAllPaths(j) using the same tokenizer, and j.a = 'FOO-QUX ', eighteen nested reverse calls give 0 in the direct projection and 1 through the subquery.
Please preserve dependency-based matching while bounding expansion in canonicalization/matching, rather than adding another carrier-specific exception to the length heuristic. Add focused regressions for both mapKeys and JSONAllPaths across the step boundary.
There was a problem hiding this comment.
Fixed in b57b697: the opacity cutoff is now a fixed expansion bound (10000) instead of the index name length, and the test covers mapKeys and JSONAllPaths across the step boundary.
There was a problem hiding this comment.
[Blocker] b57b697cd967 raises the cutoff, but the dependency-based match is still lost at src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:207-208. A compact query can cross 10000 through shared references; it does not require a long written expression.
On the exact head binary:
CREATE TABLE t
(
j JSON(a String),
INDEX idx(JSONAllPaths(j)) TYPE text(tokenizer = splitByString([' ']))
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('{"a":"FOO-QUX "}');Generate two queries with:
for separated in (False, True):
q = 'SELECT j.a AS x FROM t'
for _ in range(12):
q = f"SELECT if(x = 'a', 'b', x) AS x FROM ({q})"
if separated:
q += ' ORDER BY x LIMIT 1'
print(f"SELECT hasAnyTokens(x, 'FOO') FROM ({q}) "
"SETTINGS optimize_if_transform_strings_to_enum = 0;")The merged query returns 0; the separated query returns 1. At 10 or 11 layers both return 0. At 12 layers the lower bound reaches 12286, so the output becomes an opaque input and the next step cannot see j.a for traverseJSONSubcolumnKeyNode. The tokenizer is consequently omitted. The existing 18-reverse regression stays below the new cutoff.
Please retain dependency-based matching across the cutoff and cover a shared expression that actually crosses it; increasing the cutoff leaves the original correctness issue present.
There was a problem hiding this comment.
Not changing this: past the bound the steps above see the column as master does, and master returns 1 for the separated form at every depth I measured (8-13), so it is the pre-existing behaviour, not a regression (acd2a46 counts constant bytes, so this shape now crosses the bound at 9 layers). Keeping these matches without a bound needs index analysis to match the shared DAG without expanding it, which is a separate change.
…ngth 87d1f83 replaced a subexpression of the steps below by an opaque input as soon as its name lower bound was longer than every index column name. A match that does not compare names was then lost: a function of `m['a']` for an index on `mapKeys(m)`, or of `j.a` for one on `JSONAllPaths(j)`. With 18 nested `reverse` calls and the index tokenizer `splitByString([' '])`, `hasAnyTokens(v, 'FOO')` over `v` computed in a subquery, an ALIAS with `query_plan_enable_optimizations = 0`, and the filter form with skip indexes off returned 1 where the same-step form returns 0. The bound now only limits expansion: a subexpression becomes opaque when its name lower bound exceeds 10000, or the longest index column name if that is longer. A written expression is far shorter, so only columns referenced several times by the steps above reach it, and planning stays bounded for them. Opaque input names keep the index-derived length, so they still cannot occur in an index name and stay short. Measured (debug, base = master a33e1c1): the bot's `mapKeys` and `JSONAllPaths` repros are base 1 / head 1 / fix 0 through a subquery, an ALIAS at optimizations off and the filter form. EXPLAIN planning time of the nested `if(x = 'a', 'b', x)` (up to 18 layers, with and without plan optimizations) and nested lambda capture shapes equals master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ytes
Index analysis expands the expression it matches into a tree, copying every
constant per reference. The previous bound counted only nodes (constants as
zero) and applied only to the outputs of the steps below, so two shapes still
planned far slower than master:
- shared references to a large literal (`if(x = repeat('a', 100000), 'b', x)`
layered through `ORDER BY x LIMIT 1` subqueries): 10 layers took 3.7 s /
4.0 GB on the previous head vs 0.34 s / 268 MB on master (debug build);
- a step whose own `WITH` chain doubles over a column composed from below
(10 doublings over 11 subquery layers): 60 s / 13.8 GB vs 0.5 s.
The expanded size now counts every node plus the bytes of its constant, and
it bounds the haystack of the matched function itself: parts of the composed
haystack larger than max(10000, twice the size of the step's own expression)
become opaque inputs. The step's own expression is what master expands when it
matches the step alone, so a column renamed below keeps master's matches (new
test line), and planning stays within that of master. All the probes above now
take 0.3-0.5 s.
Past the bound the steps above see the column as master does, which is the
same behaviour as before for the shared-reference chains the composition
cannot expand.
Related: ClickHouse#95944
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #95944
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
hasToken,hasAnyTokens,hasAllTokensandhasPhraseon anALIAScolumn ignoring the preprocessor, tokenizer and postprocessor of the column's text index, returning wrong results, when the function was evaluated in a later plan step than the column, e.g. in theSELECTlist of a query whoseWHEREuses the column, through a subquery, or withquery_plan_enable_optimizations = 0orquery_plan_merge_expressions = 0.Description
On 26.10.2.103, for
name String ALIAS ifNull(provider, 'default_name')withINDEX idx(name) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(name)),SELECT x, hasToken(x, 'HELLO') FROM (SELECT name AS x FROM tab)returns 0 for the row'Hello World', whileSELECT hasToken(name, 'HELLO') FROM tabreturns 1. Withquery_plan_enable_optimizations = 0orquery_plan_merge_expressions = 0,WHERE hasToken(name, 'HELLO')returns no rows. On master, fora String ALIAS if(src = 'foo', 'yes', 'no')with text indexes onsrcand ona(preprocessor = lower(a)),SELECT hasToken(a, 'YES') FROM tab WHERE src = 'foo' AND a != ''returns 0 at default settings. Found by the AST fuzzer DQP oracle: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115168&sha=e2768dd0dcbeb63e53684daf6e231bac211051b9&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29Root cause: when the function is evaluated in a later step than the
Compute alias columnsstep, the text index rewrite (optimizeDirectReadFromTextIndex.cpp) maps its input back to the scan only through pure renames, so the ALIAS expression is lost and no index matches.Change: the rewrite composes the walked steps, each before it is rewritten, into one DAG over the scan columns and matches a text-search function on its node there, so it matches an index exactly when it does in the merged plan.
Validation: new test
02346_text_index_preprocessor_alias_unmerged_steps(ifNull,ifand lambda ALIAS columns; preprocessor, tokenizer and postprocessor; WHERE, SELECT list, subquery; direct read on and off) fails on master and passes with the fix, 50/50 with randomized settings; the other 334 text index and token function stateless tests pass. Parts of the composed haystack that expand beyond max(10000, twice the function's own step) nodes and constant bytes stay opaque, as on master, so nested steps that reference a value twice (also inside a lambda or around a large literal) plan as fast as on master; the test covers these, andmapKeys/JSONAllPathsmatches across a step.Workflow [PR]
Sync PR [sync-upstream/pr/130272]