Skip to content

Look through lossless conversions of the indexed column and of constants in the text index - #120220

Merged
CurtizJ merged 7 commits into
ClickHouse:masterfrom
CurtizJ:text-index-unwrap-lossless-conversion
Sep 30, 2026
Merged

CurtizJ merged 7 commits into
ClickHouse:masterfrom
CurtizJ:text-index-unwrap-lossless-conversion

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Closes: #110018

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

Skip indexes (text, tokenbf_v1, ngrambf_v1) are now used when the indexed column or the searched constant is wrapped into LowCardinality, Nullable or an equivalent CAST. For example, m['key'] = 'value' on a Map(String, LowCardinality(String)) column and hasToken(s, toLowCardinality('x')) previously scanned all granules.


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

Version info

  • Merged into: 26.10.1.1114-master (included in 26.10 and later)
  • Backported to: 26.9.9.12, 26.8.16.18, 26.7.20.10

CurtizJ and others added 2 commits September 15, 2026 14:11
The analyzer wraps the indexed expression into `_CAST`, `toNullable` or
`toLowCardinality` in several cases: `optimize_functions_to_subcolumns`
rewrites `m['key']` on `Map(K, LowCardinality(V))` into
`_CAST(m.key_<key>, 'V')`, and `join_use_nulls` pushes filters down as
`toNullable(column)`. `MergeTreeIndexConditionText` matched the wrapped
expression by name and declined, so the text index was not used.

Strip such conversions in `traverseFunctionNode` and in the `IN` path
while they cannot change the value or throw: adding or dropping
`LowCardinality` and adding `Nullable`, at any depth of `Array`.
Dropping `Nullable` is not looked through because the cast throws on
NULL. Serializing casts such as `FixedString` to `String` or
`Array(String)` to `String` change the bytes the tokenizer sees, so
`canBeSafelyCast` is deliberately not used here.

Also unwrap a `Nullable` set column in the `IN` path and decline sets
that contain NULL.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`RPNBuilderTreeNode::tryGetConstant` now returns the type of the value
the constant holds: `LowCardinality` is removed, and `Nullable` is
removed when the value is not NULL. A `Field` is the plain value, so
every consumer of `tryGetConstant` (`KeyCondition`, the text index, the
bloom filter indexes, the selectivity estimator) sees `String` for
`toLowCardinality('x')` and `CAST('x', 'LowCardinality(Nullable(String))')`.
The per-consumer stripping added by ClickHouse#110017
in `MergeTreeIndexConditionText` and `MergeTreeConditionBloomFilterText`
is removed, together with the special case that made a `LowCardinality`
`hasToken` needle with a separator behave differently from a `String` one.

`MergeTreeIndexConditionText::traverseMapElementKeyNode` accepts a
predicate result of `Nullable(UInt8)` or `LowCardinality(UInt8)`, which a
`Nullable` map key produces; NULL reads as false, as in WHERE. The
constant key is read through `tryGetConstant` instead of unwrapping the
column by hand. This supersedes ClickHouse#110031.

The absent-key guards in `MergeTreeConditionBloomFilterText` compare the
constant with its `FixedString` padding stripped. `FixedString` reports
'' as its default while the constant holds N zero bytes, so
`m['missing'] = CAST('', 'FixedString(N)')` used the `mapKeys` index and
returned no rows instead of all rows.

`RPNBuilderTreeNode` holds a const reference to the tree context, so a
node can be built from a const function node.

Closes: ClickHouse#110018

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f655800]

Summary: ✅


AI Review

Summary

This PR teaches text-index analysis to look through lossless CAST / toNullable / toLowCardinality wrappers on constants and, for the text index family, on the indexed expression plus the direct-read preprocessor path. The remaining gap is that tokenbf_v1 / ngrambf_v1 still do not unwrap the indexed column, so the implementation does not fully match the current title and Changelog entry.

PR Metadata
  • Changelog category Bug Fix matches the actual change.
  • Changelog entry is required and specific enough, but it overstates the indexed-column part: constant-side normalization is implemented for all three skip-index families, while indexed-column unwrapping is implemented only in MergeTreeIndexConditionText (text).
  • Exact replacement text:
    Skip indexes (text, tokenbf_v1, ngrambf_v1) are now used when the searched constant is wrapped into LowCardinality, Nullable or an equivalent CAST. The text index also looks through equivalent wrappers on the indexed column, for example m['key'] = 'value' on a Map(String, LowCardinality(String)).
Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:621] [dismissed by author -- https://github.com/Look through lossless conversions of the indexed column and of constants in the text index #120220#discussion_r4020120213] The PR still does not look through lossless wrappers on the indexed column for tokenbf_v1 / ngrambf_v1. MergeTreeConditionBloomFilterText still resolves keys from the raw getColumnName() result here and again in the IN path at src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:960, so predicates such as hasToken(CAST(s, 'Nullable(String)'), 'rare') and toNullable(s) IN (...) still miss the index and scan all granules. That violates the current title / Changelog entry contract, which says wrapped indexed columns work for all three text-style skip indexes.
    Suggested fix: apply the same key-side unwrapLosslessConversion handling in MergeTreeConditionBloomFilterText (both scalar and set paths), with a focused tokenbf_v1 / ngrambf_v1 regression test; or narrow the PR title and Changelog entry to the text-only indexed-column fix.
Tests
  • ⚠️ The current suite proves constant-side normalization for tokenbf_v1 / ngrambf_v1 (tests/queries/0_stateless/04365_token_index_lowcardinality_constant.sql) and indexed-column normalization only for text (tests/queries/0_stateless/05217_text_index_map_lowcardinality_subcolumn_cast.sql). If the broader contract is intentional, add a focused tokenbf_v1 / ngrambf_v1 regression for a wrapped haystack (CAST / toNullable) and ideally the IN path too.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • either implement key-side lossless-conversion unwrapping for tokenbf_v1 / ngrambf_v1 and cover it with a focused regression, or
    • narrow the PR title and Changelog entry so they only promise the behavior the current code actually implements.

LLVM Coverage Report

Measured on commit f655800.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.70% +0.10%

Changed lines: Changed C/C++ lines covered: 130/137 (94.89%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 15, 2026
@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 15, 2026
`clickhouse-test` randomizes `query_plan_convert_outer_join_to_inner_join`
to `false` in 5% of the runs. The filter is pushed below the join only
when the NULL-rejecting `WHERE` turns the `LEFT JOIN` into an `INNER`
one; with the conversion disabled the `Filter` step stays above the join,
nothing reaches `ReadFromMergeTree` and no index is consulted, so the
`EXPLAIN indexes` count was 0 instead of 1.

Pin the setting on that query. The case is still the one this change is
about: with the conversion enabled the pushed-down filter arrives as
`hasToken(toNullable(s), 'network')`, so the conversion of the indexed
column is what has to be looked through.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120220&sha=ad41b843541a878cc0821080d3db7cfda2f739dd&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
Related: ClickHouse#120220

Co-Authored-By: Claude Opus 5 <[email protected]>
Ergus
Ergus previously requested changes Sep 23, 2026

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The most important one is the preprocessor result divergence

Comment thread src/Storages/MergeTree/RPNBuilder.cpp Resolved
CurtizJ and others added 2 commits September 23, 2026 12:44
# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexConditionText.cpp
…versions

The text index is analyzed on the expression under lossless conversions of the
haystack, e.g. `s` in `hasToken(toNullable(s), 'Foo')`, and applies its
preprocessor to the needle. The row-level rewrite in `processTextIndexFunction`
matched the wrapped haystack against the preprocessor expression, found no
match and kept the case-sensitive function, so the result depended on
`query_plan_direct_read_from_text_index` and on whether a part had the index
materialized. Unwrap the conversions there too, sharing the definition of a
lossless conversion with the index analysis.

Also add a test for the `bloom_filter` index on `mapKeys` / `mapValues`
compared with `CAST('' AS LowCardinality(Nullable(String)))`: taking the
default of the constant's value type instead of its declared type makes the
index decline, as it must for the default value.

Related: ClickHouse#120220 (comment)
Related: ClickHouse#120220 (comment)
Related: ClickHouse#120220

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
CurtizJ and others added 2 commits September 30, 2026 17:37
…-lossless-conversion

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Addresses review comment ClickHouse#120220 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f65580050 with master dc5b03033 (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.

Compile time of recompiled translation units

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

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

Job report

@CurtizJ
CurtizJ dismissed Ergus’s stale review September 30, 2026 23:10

All review comments are resolved.

@CurtizJ
CurtizJ added this pull request to the merge queue Sep 30, 2026
Merged via the queue into ClickHouse:master with commit cdf3d9d Sep 30, 2026
149 checks passed
@CurtizJ
CurtizJ deleted the text-index-unwrap-lossless-conversion branch September 30, 2026 23:46
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 30, 2026
@CurtizJ CurtizJ added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 1, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 1, 2026
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Oct 1, 2026
The `bloom_filter`, `tokenbf_v1` and `ngrambf_v1` indexes now look through
`CAST`, `_CAST`, `toNullable` and `toLowCardinality` around the indexed
expression when the conversion never changes the value and never throws
(adding or dropping `LowCardinality`, adding `Nullable`, at any depth of
`Array`), the same as the text index does since
ClickHouse#120220. Such wrappers come
from explicit casts, from `join_use_nulls` in pushed-down filters, and from
casts of typed JSON paths, e.g. `has(['a'], json.Name::Nullable(String))`.

`unwrapLosslessConversion` moves from the text index condition to
`RPNBuilder` so that all index conditions share it.

`toLowCardinality` now declares itself monotonic, like `toNullable`, so
`KeyCondition` (primary key, `minmax`) accepts it in the monotonic chain.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 1, 2026
Cherry pick #120220 to 26.7: Look through lossless conversions of the indexed column and of constants in the text index
robot-clickhouse added a commit that referenced this pull request Oct 1, 2026
…dexed column and of constants in the text index
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 1, 2026
Cherry pick #120220 to 26.8: Look through lossless conversions of the indexed column and of constants in the text index
robot-clickhouse added a commit that referenced this pull request Oct 1, 2026
…dexed column and of constants in the text index
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 1, 2026
Cherry pick #120220 to 26.9: Look through lossless conversions of the indexed column and of constants in the text index
robot-clickhouse added a commit that referenced this pull request Oct 1, 2026
…dexed column and of constants in the text index
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 1, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #120220 to 26.8: Look through lossless conversions of the indexed column and of constants in the text index
clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #120220 to 26.9: Look through lossless conversions of the indexed column and of constants in the text index
clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #120220 to 26.7: Look through lossless conversions of the indexed column and of constants in the text index
alexey-milovidov pushed a commit to RinChanNOWWW/ClickHouse that referenced this pull request Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index on mapKeys/mapValues is not used when the map element key is a Nullable constant

5 participants