Skip to content

Strip FixedString padding before extracting text-index search terms - #117314

Merged
ahmadov merged 8 commits into
masterfrom
fix-text-index-fixed-string-padding
Sep 7, 2026
Merged

ahmadov merged 8 commits into
masterfrom
fix-text-index-fixed-string-padding

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117021
Related: #112206
Related: #116407

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

Fix a text or ngrambf_v1 index silently dropping matching rows when the indexed column is
compared for equality against a FixedString value, or searched with hasAny or hasAll over
FixedString needles. Happens at default settings, since use_skip_indexes and
enable_full_text_index are both on.

Description

'hello' = toFixedString('hello', 10) is true - the comparison casts both sides to String, which
drops the constant's trailing zero padding. The index conditions did not: they tokenized the raw
padded bytes, so the search terms contained \0 bytes that never appear in the stored data and every
granule looked unmatched. With index_granularity = 1 every matching row is lost.
MergeTreeIndexBloomFilter.cpp already coerces such a constant for the bloom_filter index
(coerceStringFieldLikeSearchFunction, #112206); the text-index paths never got it. Both
MergeTreeIndexConditionText and MergeTreeIndexBloomFilterText now strip the padding.

Stripping is gated two ways, because it is not sound everywhere.

By function. Only the functions that compare through the String supertype ignore the padding:
equals, notEquals, hasAny and hasAll, plus the prepared-set (IN) path.
has, mapContainsKey, mapContainsValue, startsWith and endsWith compare the raw padded bytes
instead - has(['hello'], toFixedString('hello', 10)) is 0 while
hasAny(['hello'], [toFixedString('hello', 10)]) is 1 - so their terms must keep it. This matters
because text(tokenizer = array) answers has and mapContains* by exact direct read, where the
index result replaces the predicate, so a stripped term would return rows the predicate rejects.
Every remaining supported function rejects a FixedString needle outright with
ILLEGAL_TYPE_OF_ARGUMENT.

By tokenizer, for a FixedString indexed column. Its stored terms keep the padding, so the
unpadded constant may only be searched when the terms of the unpadded value are terms of the padded
one as well. That holds for tokenizers that split on a zero byte (splitByNonAlpha, asciiCJK) and
for those that emit substrings (ngrams, sparseGrams), and not for array, which stores the whole
value as a single term, nor for splitByString, which keeps the padding inside the last one.
ngrambf_v1/tokenbf_v1 allow only ngrams, splitByNonAlpha and sparseGrams, so their condition
strips unconditionally. Only ngrambf_v1 changes behavior: tokenbf_v1 is always splitByNonAlpha,
which already splits on the padding, so the strip is a no-op there and its cases in the test are
regression coverage that the strip does not disturb them.

A String constant against a FixedString indexed column with a tokenizer that keeps the padding
inside a term (s = 'hello' over FixedString(6) with text(tokenizer = array)) is wrong on master
for the same reason, in the other direction. It is left alone here: reconciling it means padding the
constant to the column width, which is only valid for equality-shaped predicates -
startsWith(toFixedString('abcd', 6), 'ab') is true, and a padded needle would make the index prune
the matching granule.

Test 05081_text_index_fixed_string_constant pairs every query with the same query at
use_skip_indexes = 0 (or query_plan_direct_read_from_text_index = 0 where the index answers the
predicate exactly) as the oracle. It covers text with ngrams(3), splitByNonAlpha, array and
sparseGrams(3) over both String and FixedString columns, and ngrambf_v1, in equals and
subquery-IN form; hasAny and hasAll over Array(String) for both index types; the has,
mapContainsKey, mapContainsValue, startsWith and endsWith cases that must keep the padding;
and asserts an unpadded constant still prunes.


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

Version info

  • Merged into: 26.9.1.928-master (included in 26.9 and later)
  • Backported to: 26.8.16.34, 26.7.21.4

`String = FixedString(N)` ignores the constant's trailing zero padding, but the `text` and
`ngrambf_v1` conditions tokenized the raw padded bytes. For an n-gram tokenizer that produces
n-grams containing `\0`, which never occur in the stored data, so every granule was pruned and
matching rows silently disappeared - at default settings, since `use_skip_indexes` and
`enable_full_text_index` are on.

Both the `equals` and the prepared-set (`IN`) paths of both index types now strip the padding the
way the comparison does. Stripping can only remove terms from the search, never add one, so a
`FixedString` indexed column stays sound as well. `MergeTreeIndexBloomFilter.cpp` already does
the same for the `bloom_filter` index (#112206).

`text(tokenizer = splitByNonAlpha)` and `tokenbf_v1` were unaffected - the zero bytes act as
token separators there - and stay covered by the test.

Closes: #117021
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2a9f6e1]

Summary: ✅


AI Review

Summary

This PR strips trailing FixedString padding before extracting search terms for the text and text bloom-filter index conditions, then gates that rewrite to the function families and tokenizers where it stays sound. I reviewed the current diff, the full prior discussion, and the touched MergeTree index code paths; the implementation looks correct in the current head, and the only remaining issue I found is a non-blocking overstatement in the changelog/body around tokenbf_v1.

PR Metadata

Changelog category is correct for the code change.

Changelog entry is required and mostly clear, but it currently names tokenbf_v1 as a wrong-results fix without matching evidence in the diff. The replacement I would use is:

Fixes text and ngrambf_v1 indexes silently dropping matching rows when the indexed column is compared for equality against a FixedString value, or searched with hasAny or hasAll over FixedString needles.

Findings

💡 Nits

  • [tests/queries/0_stateless/05081_text_index_fixed_string_constant.sql:206] The PR metadata says tokenbf_v1 also dropped matching rows, but splitByNonAlpha already tokenizes trailing \0 padding as separators and this test block does not cover a failing pre-patch tokenbf_v1 case. Add the concrete repro or narrow the changelog/body to the paths that actually changed behavior.
Final Verdict

✅ Approve with one non-blocking metadata nit.

LLVM Coverage Report

Measured on commit 2a9f6e1.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 79/83 (95.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2a9f6e1a8 with master 58f74d473 (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

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

Job report

@ahmadov ahmadov self-assigned this Aug 31, 2026
@ahmadov

ahmadov commented Sep 1, 2026

Copy link
Copy Markdown
Member

@groeneai can you address my comments?

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

@ahmadov I have no commits on fix-text-index-fixed-string-padding and my account has triage only on this repo, so I cannot push the code and test changes you asked for here.

What I can add is the measurement behind the thread you marked as a valid concern. Master 38a9ca2 (unpatched, 26.9.1.1), text index, index_granularity = 1, single row 'hello'; oracle is the same query with use_skip_indexes = 0:

indexed column constant tokenizer oracle with index
String toFixedString('hello', 10) ngrams(3) 1 0
FixedString(6) 'hello' array 1 0
FixedString(6) 'hello' splitByString([' ']) 1 0
FixedString(6) toFixedString('hello', 6) array 1 1

Rows 2 and 3 are the same defect in the other direction, and they are wrong on master today: the stored term keeps the padding, the probe does not. A strip cannot reach them, since a String constant has nothing to strip, and it makes row 4's search terms byte-identical to row 2's, so on a fixed-width indexed column stripping drops a granule that matches. The claim in the comment at MergeTreeIndexConditionText.cpp:943 is therefore stronger than what holds: this is not only a loss of pruning.

One rule covers all four rows: take the width from the indexed column, re-pad the constant to that width when the column has one, and decline index analysis when it does not (a String column can hold several distinct values that all compare equal to one padded constant, so no exact term set exists).

The scope is also wider than n-grams. Same setup, String column, toFixedString('hello', 10): ngrams(3), array, splitByString and sparseGrams all return 0 instead of 1; only splitByNonAlpha and asciiCJK are immune. The test here covers ngrams(3) and splitByNonAlpha, so three affected tokenizers are untested.

I have the re-pad version implemented and verified locally for equals and prepared-set IN in MergeTreeIndexConditionText.cpp, and I would follow your test-style asks there (no explicit GRANULARITY, one column per line, no narrative comments). Happy to open it as a follow-up on top of this PR or as a replacement, whichever you prefer. Earlier measurements: #117021 (comment)

The stripping was applied unconditionally, but a `FixedString` indexed column is tokenized with its
padding: `text(tokenizer = array)` stores the whole padded value as a single term, so
`s = toFixedString('abc', 5)` would have searched for `abc` while the index holds `abc\0\0` and the
granule holding the matching row would be pruned. Restrict the stripping to the cases where the
terms of the unpadded value are terms of the padded one as well - the tokenizer splits on a zero
byte (`splitByNonAlpha`) or emits substrings (`ngrams`) - or the indexed column is not a
`FixedString`. `ngrambf_v1` and `tokenbf_v1` only ever use those two tokenizers, so their condition
is unaffected.

Also shorten the comments and take the set elements as a `std::string_view` instead of copying them
into a `String`, as asked in the review.
…test

Adds the `text(tokenizer = array)` cases on both a `String` and a `FixedString` column - the latter
is the one that must keep the padding - and an n-gram index on a `FixedString` column. Every query
is paired with the same query at `use_skip_indexes = 0` as the oracle.

Table definitions follow the style asked for in the review: one column per line and no explicit
`GRANULARITY`, which is redundant because the text index is built for the whole part.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai thank you for the measurements - rows 2 and 3 of your table reproduce here as well, and the claim in the comment at MergeTreeIndexConditionText.cpp:943 was indeed too strong. I dropped it.

What is pushed (dac4983, 0c8c2d2) keeps the strip only where it is provably sound: the tokenizer splits on a zero byte (splitByNonAlpha) or emits substrings (ngrams), or the indexed column is not a FixedString. That removes the regression on row 4 and still fixes every String-column case, array and splitByString included - those are now in the test.

I did not take the re-pad rule here, because it is only valid for equality-shaped predicates. The same constant flows into startsWith/endsWith in this function, and startsWith(toFixedString('abcd', 6), 'ab') is 1 while a needle padded to the column width would make the index search for a prefix term containing \0 and prune the matching granule - the exact failure this pull request is about, in a new place. like, match and hasToken reject a FixedString needle outright, so they are not affected, but startsWith/endsWith are.

So rows 2 and 3 - a String constant against a FixedString indexed column with a tokenizer that keeps the padding inside a term - stay open, as a pre-existing wrong-results bug that is not touched by this change in either direction. A follow-up that re-pads, restricted to equals and the prepared-set path, would be very welcome; please open it on top of master once this merges, and I will review it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: Container memory budget exceeded (/docker) in Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) and 6/6 on commit 30d9f49 — https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117314&sha=30d9f49637b52ac052c4bbb2ca547c31f0b0820d&name_0=PR — and provide a fix in a separate PR. If the fix is already in progress, link it here. It is a runner-level memory budget guard, both jobs reported no failing test, and this pull request only changes a skip-index condition, so it cannot be the cause. The branch has since been merged with master and CI is running again.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Understood. I will open the follow-up on top of master once this merges, restricted to equals and the prepared-set path.

The startsWith/endsWith case is the part I did not have. My draft already stopped at those two predicates, but for a weaker reason; your prefix example is the one that actually holds, since padding preserves equality and not prefixes. I will carry it as a negative test that fails if either predicate ever receives a padded needle, so the scope cannot widen later by accident.

I will also re-measure which cases are still wrong against the merged result rather than against my earlier numbers, so the follow-up covers what is left and nothing more.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Both rows are the runner-level guard and both are already owned.

The tree in that report predates both fixes. The job log's own Merge 30d9f496 into 2b418000 line gives the real base 2b4180007260 (2026-08-31T10:00:05Z), and compare/<fix-merge-commit>...2b4180007260 returns ahead_by=0 against both fix merges, so the base is a strict ancestor of each and carries neither. The start time is misleading here: both jobs started 15:06Z, four hours after #117202 merged, but the base they built is from 10:00Z. At that base integration-tests-entrypoint.sh carries no flock, and both jobs print CI_DIND_INIT_RESERVE=17179869184, the pre-fix 16 GiB value. At your current head both markers are the post-fix form.

Per shard, from the kernel oom-kill:constraint=CONSTRAINT_MEMCG records (all oom_memcg=/docker/<dind>/docker), since the victim identity picks the owner:

shard kills victims owner
5/6 3 gdb x3 #117202, merged
6/6 3 clickhouse x2, gdb x1 gdb: #117202. clickhouse: #117412, merged, plus #117564, open

5/6 is purely the shutdown gdb fan-out, so #117202 closes it. On 6/6 the two clickhouse victims are the container-count half: #117412 sized the nested budget, and the remainder is a container leak I have a PR open for, #117564. test_refreshable_mat_view/test.py:33, test_refreshable_mat_view_replicated/test.py:37 and test_distributed_over_distributed/test.py:44 declare started_cluster with scope="session", so those servers stay resident for the whole job instead of ending with their module. The first two ran on your 6/6 (153 and 61 references in that job log) and neither ran on 5/6, matching the victim split.

The live rates agree. Distinct trees carrying the /docker row since 2026-09-02T00:00:00Z: 1/6 0/500, 2/6 0/500, 3/6 0/497, 4/6 0/498, 5/6 0/498, 6/6 81/499 (16.2%). The whole remaining residual is 6/6, the shard #117564 targets, so the run now going on your merged-with-master head should come back clean on 5/6.

Neither job lost a test: 5/6 finished 949 passed, 26 skipped and 6/6 1189 passed, 23 skipped, zero failed on both, and that guard ERROR is the only failing row CIDB holds for either.

One gap in #117564: a fifth long-lived container in these jobs is a Kafka schema registry, which is not one of those three modules.

@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 4, 2026
alexey-milovidov and others added 3 commits September 5, 2026 16:14
`has`, `mapContainsKey` and `mapContainsValue` compare a `FixedString` constant by its raw padded
bytes - `has(['hello'], toFixedString('hello', 10))` is 0 - and so do `startsWith` and `endsWith`.
The strip ran before the function-specific dispatch, so it rewrote their needles too, and
`text(tokenizer = array)` answers `has` and `mapContains*` by exact direct read, where the index
result replaces the predicate: `optimizeDirectReadFromTextIndex` would have returned rows the
predicate rejects.

Restrict the strip to the functions whose comparison goes through the `String` supertype, which is
what drops the padding. `hasAny` and `hasAll` are among them -
`hasAny(['hello'], [toFixedString('hello', 10)])` is 1, and on master the index returns 0 rows for it
for both `text` and `ngrambf_v1` - so they are fixed rather than excluded. Every remaining supported
function rejects a `FixedString` needle outright with `ILLEGAL_TYPE_OF_ARGUMENT`.

Also add `sparseGrams` to `tokenizerToleratesZeroPadding`: it emits a gram only while consuming the
byte at the gram's right border and hashes nothing past it, so extending a value keeps every gram of
the shorter one and only adds new ones. Without this, `text(tokenizer = sparseGrams(3))` on a
`FixedString` column still tokenized the padded probe and pruned the matching granule. `asciiCJK`
joins the list too; it treats a zero byte as a separator, so there stripping is a no-op.
Add `sparseGrams(3)` over a `FixedString` column, `hasAny`/`hasAll` over `Array(String)` for both
`text(tokenizer = array)` and `ngrambf_v1`, and the `has`, `mapContainsKey`, `mapContainsValue`,
`startsWith` and `endsWith` cases that must keep the padding. Where the index answers the predicate
exactly the oracle adds `query_plan_direct_read_from_text_index = 0`, since `use_skip_indexes = 0`
alone does not disable direct read.

Every one of the new index queries returns the wrong count before this pull request except the
padding-keeping ones, which would start returning rows the predicate rejects if the strip were ever
moved back before the dispatch.
- clean up comments
- adjust test for better verification

@ahmadov ahmadov 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.

LGTM 👍

@ahmadov
ahmadov added this pull request to the merge queue Sep 7, 2026
Merged via the queue into master with commit 2be1edf Sep 7, 2026
174 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
bobrik pushed a commit to bobrik/ClickHouse that referenced this pull request Sep 8, 2026
`DataTypeLowCardinality.h` was included twice, which clang-tidy reports as
`readability-duplicate-include` and fails the `Build (arm_tidy)` job on master.

Caused by: ClickHouse#117314

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JyZgVjwycGoE67Jf1wvve6
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 9, 2026
Conflicts in MergeTreeIndexBloomFilterText.cpp, both regions this branch
touches, against three master changes that landed since the last push:
FixedString padding stripping (ClickHouse#117314), the LIKE unknown-backslash-escape
decline, and FixedString padding stripping for set elements.

Resolution keeps both sides:

* traverseTreeEquals: the constant is first padding-stripped by master's
  rule, then const_source_type tracks the type of whatever value survives,
  so the conversion into the index domain sees the same value the scan
  compares. The LIKE escape decline runs after both, unchanged.

* tryPrepareSetBloomFilter: a set element on a non-string index domain is
  re-encoded, as before; every other element keeps master's path including
  the padding strip. A padded FixedString element on a non-string domain
  fails to convert and declines the atom, which costs pruning and cannot
  lose rows.
alexey-milovidov added a commit to rorylshanks/ClickHouse that referenced this pull request Sep 22, 2026
A `FixedString` needle compares equal to a `String` value both with and
without its trailing zero bytes, and a term-preserving tokenizer
(`array`, or `splitByString` with a separator that does not contain the
zero byte) stores those two spellings as two different terms. ClickHouse#117314
strips the needle's padding before extracting the search terms, which
fixed the plain row (ClickHouse#117021) and moved the loss onto the row whose own
value carries literal zeros: the index looked up a term that granule
never stored and pruned it, so the query returned fewer rows than the
same query with `use_skip_indexes = 0`.

No single lookup covers both spellings, so a needle that really carries
padding now leaves the index unusable for that atom, which is what the
`FixedString`-column case already did. The decision becomes explicit:
strip for a tokenizer that treats the zero byte as a separator, keep the
padding for a `FixedString` column whose terms carry it too, and decline
for the term-preserving-over-`String` combination - and only when the
needle actually has padding to strip, so ordinary needles keep their
pruning. The `IN`-set path, which strips per element, follows the same
rule.
@CurtizJ CurtizJ added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 2, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 2, 2026
robot-ch-test-poll added a commit that referenced this pull request Oct 2, 2026
Cherry pick #117314 to 26.8: Strip `FixedString` padding before extracting text-index search terms
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
Cherry pick #117314 to 26.7: Strip `FixedString` padding before extracting text-index search terms
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #117314 to 26.8: Strip `FixedString` padding before extracting text-index search terms
clickhouse-gh Bot added a commit that referenced this pull request Oct 4, 2026
Backport #117314 to 26.7: Strip `FixedString` padding before extracting text-index search terms
ringerc pushed a commit to ringerc/ClickHouse-patches that referenced this pull request Nov 9, 2026
05076 and 05077 are already taken by open pull requests ClickHouse#118128 and ClickHouse#118003,
and 05081/05082 by ClickHouse#117314/ClickHouse#117318, so a merge of any of them would collide.

Co-Authored-By: Claude Opus 5 <[email protected]>
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 / ngrambf_v1 index over-prunes for a FixedString constant on String columns (silent wrong result; #112206 fix did not cover the text-index path)

6 participants