Skip to content

Fix text-search functions on an ALIAS column ignoring the text index preprocessor and tokenizer - #130272

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/text-index-alias-unmerged-steps
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/text-index-alias-unmerged-steps

Conversation

@groeneai

@groeneai groeneai commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #95944

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

Fixed hasToken, hasAnyTokens, hasAllTokens and hasPhrase on an ALIAS column 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 the SELECT list of a query whose WHERE uses the column, through a subquery, or with query_plan_enable_optimizations = 0 or query_plan_merge_expressions = 0.

Description

On 26.10.2.103, for name String ALIAS ifNull(provider, 'default_name') with INDEX 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', while SELECT hasToken(name, 'HELLO') FROM tab returns 1. With query_plan_enable_optimizations = 0 or query_plan_merge_expressions = 0, WHERE hasToken(name, 'HELLO') returns no rows. On master, for a String ALIAS if(src = 'foo', 'yes', 'no') with text indexes on src and on a (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%29

Root cause: when the function is evaluated in a later step than the Compute alias columns step, 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, if and 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, and mapKeys / JSONAllPaths matches across a step.


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

groeneai and others added 2 commits November 9, 2026 07:10
…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]>
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author
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):

  • ❌ Lambda-backed ALIAS expressions missed the index transforms in unmerged plans (the name renderer printed a lambda without its body). Fixed for lambdas the merged plan handles.
  • ⚠️ The per-output name rendering was unbounded on nested subqueries. Removed with the rename map.
  • ⚠️ A constant aliased to an indexed column's name could be matched to that index. Removed with the rename map.
  • ⚠️ The new test needs no-parallel-replicas, like the sibling inject-path tests. Added.

Round 2 (head 79bd72e):

  • ⚠️ The test had no lambda ALIAS arm. AGREE: lambda arms added.
  • 💡 Not fixed here (separate defect): a lambda that captures only constants is folded into a constant, so the preprocessor check misses it at any settings, also with no ALIAS and in the merged plan.

Round 3 (head 9845b43):

  • ❌ The filter directly above the scan was composed after its own rewrite, so with direct read on, a text-search function above it on an ALIAS whose expression contains a rewritten predicate missed the index transforms (hasToken(a, 'YES') 0 with direct read on, 1 with it off). AGREE: the filter is now composed before it is rewritten, like every other step; test block added.

Round 4 (head 1f3042e):

  • ⚠️ The direct-read block only compares results, so it would stay green if direct read declined. DISAGREE: the query pins direct read on, and the build with the old compose order fails exactly that line (1 -> 0) under the test runner; with direct read off that build returns 1, so the line runs the direct-read path.
  • 💡 Not fixed here (separate defect): with optimize_if_transform_strings_to_enum = 1 an if over string constants is rewritten to an Enum form that no longer equals the index expression, so the preprocessor is not applied in any plan, on master too. The test clamps that setting to its default.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test fails on every run on master (no randomization needed): 0 instead of 1 for the WHERE, SELECT-list, countIf and subquery arms, and 2 instead of 1 for the tokenizer arm.
b Root cause explained? Yes. ALIAS columns are computed in a separate Compute alias columns step. When it is not merged into the step evaluating the function, the rewrite in optimizeDirectReadFromTextIndex.cpp maps the function's input back to the scan only through pure renames, so the input holding ifNull(provider, 'default_name') is never matched to the text index and no preprocessor, tokenizer or postprocessor is applied.
c Fix matches root cause? Yes. The walked steps are composed into one DAG over the scan columns, as the index analysis does, and the function is matched on its composed node. The fix pins no setting and relaxes no check.
d Test intent preserved / new tests added? New SQL test 02346_text_index_preprocessor_alias_unmerged_steps: preprocessor, tokenizer and postprocessor indexes on ALIAS columns, WHERE, SELECT list, countIf above WHERE, a subquery at default settings, and an ALIAS that wraps a direct-read predicate. The test clamps optimize_if_transform_strings_to_enum to 0: that rewrite changes an if ALIAS expression so it no longer matches the index expression, on master too. No existing test changed.
e Both directions demonstrated? Yes. Master: FAIL with 19 differing lines (1/1 fixed settings, 10/10 randomized). Fix: PASS, 1/1 fixed settings and 50/50 randomized.
f Fix is general across code paths? Yes. Every step the pass walks (Filter, Expression, row-preserving pass-throughs) is composed. The direct-read filter and PREWHERE already see scan columns.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Checked Nullable via ifNull, LowCardinality(String), ALIAS of ALIAS, lambda ALIAS expressions (a constant-only lambda with a preprocessor is a separate, pre-existing miss), an ALIAS Map with a mapValues index, and hasToken, hasAnyTokens, hasAllTokens, hasPhrase.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default change. Results change only where they disagreed with the merged plan of the same query.
i Invariants and contracts preserved? Yes. The step DAGs are only cloned for the composition; the rewrite binds to the step's own inputs, so step headers and output names are unchanged.

Session id: cron:clickhouse-impl-slot-5:20261109-065600

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @Ergus, could you review this and add the can be tested label so CI runs? When a text-search function is evaluated in a later plan step than its ALIAS column (a subquery, or query_plan_enable_optimizations = 0), optimizeDirectReadFromTextIndex lost the ALIAS expression in its rename map and skipped the index preprocessor and tokenizer; it now composes the walked step DAGs and matches the function on its composed node.

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [acd2a46]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR composes expression DAGs across plan steps so text-search functions on ALIAS columns inherit their text index's transforms. Reviewed acd2a460cc2ab064bfa144f08244dd6aea7fbd68, including all discussion and the current implementation. The earlier planning-resource reproductions are fixed, but the expansion cutoff still leaves incorrect, plan-dependent results.

Findings

❌ Blockers

  • src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:1334, also lines 1407–1414: The matching budget can suppress required transforms and change query results. [dismissed by author -- https://github.com/Fix text-search functions on an ALIAS column ignoring the text index preprocessor and tokenizer #130272#discussion_r4575417000] The author deliberately retains master's behavior beyond the cutoff; the correctness concern remains because equivalent merged and separated plans still produce different answers.

    On the exact head binary, twelve nested if(x = 'a', 'b', x) projections over j.a = 'FOO-QUX ', with an index on JSONAllPaths(j) using splitByString([' ']), return 0 from hasAnyTokens(x, 'FOO') when merged and 1 when each subquery has ORDER BY x LIMIT 1. Making the dependency opaque prevents the index tokenizer from being injected.

    The current byte-counting bound also loses exact expression matches without shared-expression expansion. Generate this reproduction:

    items = ",".join(["''"] * 2000)
    print(f"""
    CREATE TABLE t
    (
        src String,
        a String ALIAS arrayStringConcat(arrayPushFront([{items}], src), ' '),
        INDEX idx(a) TYPE text(tokenizer = 'splitByNonAlpha', preprocessor = lower(a))
    ) ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO t(src) VALUES ('Hello World');
    SELECT hasToken(a, 'HELLO') FROM t;
    SELECT hasToken(a, 'HELLO') FROM t SETTINGS query_plan_enable_optimizations = 0;
    SELECT count() FROM t WHERE hasToken(a, 'HELLO')
        SETTINGS query_plan_enable_optimizations = 0, use_skip_indexes = 0;
    """)

    Results are 1, 0, 0; all should be 1. The index expression name has 8,045 characters, but the constant array occupies 16,008 bytes. Consequently, the 10,000 budget replaces the literal with an opaque input and loses the preprocessor. Arrays of 1,240 elements work; 1,250 elements already fail. A subquery projection also returns 0. This mismatch pre-exists on master; it remains an unhandled input of the advertised fix. Preserve index matches while bounding expansion; at minimum, measure indexed expressions and query expressions in the same units. Alternatively, link a tracking issue for the deliberately retained limitation and narrow the claimed fix accordingly. This evidence belongs to the existing cutoff finding, so no duplicate inline thread was created.

Tests
  • ⚠️ Add an exact-index regression around the constant-array cutoff, asserting identical projection and filter results with merged and unmerged plans.
  • ⚠️ The committed resource tests omit the large folded-literal and combined lower-step/own-step expansion cases addressed by the latest fix. Add focused regressions so removing those protections fails a test; local probes of both now pass.
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.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default 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... labels Nov 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 87d1f8373 with master 58726cc5c (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.64 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 12.4 s +8.5 s (+220%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.3 s +5.2 s (+246%)
Compile time of recompiled translation units

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

Job report

…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]>
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d7f067d

Every failure below has an owner: a fixing PR (mine 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
Install packages (amd_release, deb) infra, not from this PR (no ci/ file in the diff): Build (amd_release) and Build (arm_release) never ran on this head, so this job died in its pre-run step with Required artifacts are not found in S3 before any test started. 9 other PRs had jobs end in the same job-level error between 18:14Z and 18:40Z a fix task is created (fixing-PR link to follow on this PR)
Install packages (amd_release, rpm) same cause: died in pre-run, its Build (amd_release) artifact is absent a fix task is created (the same one as above)
Install packages (amd_release, tgz) same cause: died in pre-run, its Build (amd_release) artifact is absent a fix task is created (the same one as above)
Compatibility check (amd_release) same cause: died in pre-run, its Build (amd_release) artifact is absent a fix task is created (the same one as above)
Upgrade check (amd_release) same cause: died in pre-run, its Build (amd_release) artifact is absent a fix task is created (the same one as above)
AST fuzzer (amd_release, oracle) same cause: died in pre-run, its Build (amd_release) artifact is absent a fix task is created (the same one as above)
ClickBench (amd_release) same cause: died in pre-run, its Build (amd_release) artifact is absent a fix task is created (the same one as above)
Install packages (arm_release, deb) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Install packages (arm_release, rpm) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Install packages (arm_release, tgz) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Compatibility check (arm_release) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Stress test (arm_release) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
ClickBench (arm_release) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
SQLLogic test same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
SQLStorm test same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Docs examples same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Performance Comparison (arm_release, master_head, 1/6) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Performance Comparison (arm_release, master_head, 2/6) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Performance Comparison (arm_release, master_head, 3/6) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Performance Comparison (arm_release, master_head, 4/6) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Performance Comparison (arm_release, master_head, 5/6) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Performance Comparison (arm_release, master_head, 6/6) same cause: died in pre-run, its Build (arm_release) artifact is absent a fix task is created (the same one as above)
Docker server image same cause: the release build report is absent, so docker_server.py stops with URLS has not been read from build report a fix task is created (the same one as above)
Docker keeper image same cause: the release build report is absent, so docker_server.py stops with URLS has not been read from build report a fix task is created (the same one as above)
Mergeable Check, PR praktika rollups of the rows above a fix task is created (the same one as above)
Sync - CH Inc sync (private, not actionable by me)

20 jobs were dropped on this head and never started, among them both release builds, Quick functional tests, three amd_debug and arm_binary stateless jobs, five targeted jobs, the amd_asan_ubsan and amd_msan flaky checks and four unit test jobs, so they have no results here. Every other job that ran passed, including the amd_tsan flaky check.

Session id: cron:our-pr-ci-monitor:20261109-203008

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). This update was made automatically.

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]>
Comment on lines +206 to +207
if (!result)
result = add_opaque_input(node->result_type);

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] 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;
-- 1

Computing 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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] 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

groeneai and others added 2 commits November 14, 2026 20:42
…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]>

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... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants