Skip to content

Test the ESCAPE route into the ngram LIKE-pattern tokenizer - #118279

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/ngrams-tokenizer-escape-pair-restart
Sep 19, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/ngrams-tokenizer-escape-pair-restart

Conversation

@groeneai

@groeneai groeneai commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117858
Related: #118673

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Not required: tests only.

Description

The tokenizer fix this PR opened with was reworked and merged as #118673 (67ccc416), which closed #117858 and added 05147_ngrambf_like_escaped_backslash_run. The source diff here is empty as a result, so the category is now CI Fix or Improvement and the title no longer claims a fix. What is left is the coverage 05147 does not have.

The ESCAPE route into the tokenizer. LIKE <pattern> ESCAPE '<c>' reaches a skip index as a three-argument like(col, pattern, c) call, and both index conditions that tokenize a pattern fold the escape character into a backslash-escaped pattern first: MergeTreeIndexBloomFilterText.cpp:410 for ngrambf_v1/tokenbf_v1 and MergeTreeIndexConditionText.cpp:713 for text. The fold maps a literal backslash to \\, so a pattern whose user-visible form holds no backslash run can still hand one to the tokenizer. 05147 has no ESCAPE arm; this adds one per call site. The regression test deleted here had covered the text call site only.

Oracle. Each arm asserts the granule count index analysis reached, not only that the indexed result and the use_skip_indexes = 0 result agree: an index whose required token set goes empty is still classified as useful, prunes nothing, and leaves both counts at 1. The fixture also holds xxabcdyy, the positive value without the backslashes, in a granule of its own, and that is what separates the custom-escape rewrite from a looser one that drops them: with the branch of likePatternWithCustomEscapeToLikePattern that emits those backslashes deleted, the arms stay green without that row (Granules: 1/2, both counts 1), and with it six assertions redden (both counts 2 and Granules: 2/3, in each index path).

Also here: three tokensForLikePattern lines in 03403_function_tokens_for_like_pattern, covering the defect at ngrams(2), the single-backslash pattern that was always correct, and the ngrams(1) boundary.


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

Version info

  • Merged into: 26.10.1.240-master (included in 26.10 and later)

groeneai and others added 3 commits September 5, 2026 06:26
An `ngrambf_v1` index, and a `text` index with the `ngrams` tokenizer, silently
drop granules that contain matching rows when the `LIKE` pattern holds two or
more literal backslashes immediately before an unescaped wildcard. Wrong results
at default settings; reproduced on released 26.4.1.1 and on master.

`NgramsTokenizer::nextInStringLike` scans with a local cursor while `pos` holds
the start of the sliding window. On emitting an n-gram the window must move
forward by one code point of the decoded pattern, but it moved forward by one
code point of the raw bytes:

    pos += UTF8::seqLength(static_cast<UInt8>(data[pos]));

`UTF8::seqLength('\\')` is 1, and `pos` is at that moment the byte where the
emitted token's first code point begins, including its leading backslash when
that code point is an escape pair. So for an escape pair the window lands on the
pair's second byte. The next call starts there with `escaped` false, re-pairs the
surrounding backslash run one byte out of phase, and the flipped `escaped` state
makes a genuine trailing `%` be taken by the escaped-literal branch. The emitted
token is then a required n-gram containing `%`, which no matching haystack can
contain, so the required-token AND semantics report that the granule cannot hold
a match and its rows disappear.

Take the restart position from the scan's own cursor instead: record the byte
offset just past the token's first code point at the iteration where the emitted
code-point count goes from zero to one, and restart there. The four decoding
branches are untouched, the advance site classifies nothing, and the two cannot
drift apart if the decoding is ever changed.

The alternative of testing `data[pos]` for a backslash at the return site was
rejected: it re-derives, at a second site, an escape classification the scan
already owns, and it needs a bounds guard for a one-byte over-read that the scan
never risks. Bailing out of index analysis on such patterns was also rejected:
the correct required-token set is perfectly derivable, so bailing out would trade
wrong results for permanently lost pruning, and it would not fix
`tokensForLikePattern`, which has no such guard.

For pattern `%ab\\\\%cd%` with `ngrams(2)` the produced tokens were
`ab`, `b\`, `\\`, `\%`, `cd` and are now `ab`, `b\`, `\\`, `cd`, exactly the
2-grams of the decoded literal runs `ab\\` and `cd`, so pruning stays fully
selective. A single literal backslash never completed a token while `pos` sat on
a backslash, which is why it was already correct and is unchanged.

`NgramsTokenizer::nextInString` carries the identical advance and is correct
there, because the plain-string path has no escape pairs; it is not changed. Of
the other `nextInStringLike` implementations, `SplitByNonAlphaTokenizer` and
`AsciiCJKTokenizer` use their `pos` as a single forward cursor,
`SparseGramsTokenizer` discards any gram containing `%`, `_` or `\`, and the rest
throw `NOT_IMPLEMENTED`, so none of them can hold this defect.

Index data is built by `nextInString` over column values, so only query-side
needle tokenization changes: there is no on-disk change, no index rebuild, no
setting and no serialization version.

A side effect worth naming: for an unknown escape such as `\c` the same
misalignment emitted duplicate tokens, and they are now gone. The tokenizer still
drops the backslash of an unknown escape, which is a separate defect; both index
callers already decline to prune such patterns through
`likePatternHasUnknownBackslashEscape`, so their results stay correct.

Closes: ClickHouse#117858
The end-to-end test asserted only that the indexed query and the same query at
`use_skip_indexes = 0` return the same rows. Both sides also agree when the index
silently stops being applied, so the file had no oracle for index integration or
for selectivity, while the change it guards claims that pruning stays fully
selective.

Add one `Granules` assertion per scenario, in the shape the sibling test
`02346_text_index_like_unknown_backslash_escape` already uses: assert on a
filtered projection of `EXPLAIN indexes = 1` rather than on a full-output diff.
The inner query stays `SELECT groupArray(id)`, matching the row arm above it,
because `SELECT count()` would take the trivial-count path and so would not plan
the read the row arms validate.

The assertions are live rather than future-proofing. Before the tokenizer fix the
required token set carries a fabricated n-gram containing `%`, which no granule
can hold, so all three granules are dropped and the row is lost: each scenario
reads `Granules: 3/3` then `Granules: 0/3`. After the fix the required set is the
four genuine 2-grams, granule 2 lacks `\\` and granule 3 lacks `ab`, so exactly
one survives: `Granules: 3/3` then `Granules: 1/3`. All three arms therefore
differ between the two binaries, and the primary-key line is identical in both,
which is what makes the second line the load-bearing one.

Co-Authored-By: Claude Opus 5 <[email protected]>
The trigger for the fabricated required n-gram is n or more consecutive
literal backslashes before an unescaped wildcard, so at n = 1 a single
literal backslash is enough. MIN_NGRAM_SIZE is 1, which makes ngrams(1)
a supported, user-constructible tokenizer, but every existing case in
this file used n = 2.

The n = 1 case is what pins the ORDER of the two statements the fix
adds, not just another value of n. At n >= 2 the restart position is
recorded in an earlier loop iteration than the iteration that returns
the completed token; at n = 1 both happen in the same iteration. Moving
the assignment below the return block therefore still passes every n = 2
case while making n = 1 return the entry position unchanged.

Reuse the same pattern string as the adjacent n = 2 line, so the "n or
more" rule is readable straight from the reference: one literal
backslash fabricates a required '%' at n = 1 and is harmless at n = 2.

Measured on both binaries: tokensForLikePattern('%ab\\%cd%', 'ngrams', 1)
returns ['a','b','\','%','c','d'] before the fix and ['a','b','\','c','d']
after it, while the tokens() column is byte-identical on both.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Independent cold review plus a second-model gate on this branch, two fix rounds; the final round's
gate returned no findings. Adjudicated findings:

  • ⚠️ Test could not observe whether the index was applied (major, agreed, fixed). The regression
    test compared indexed results only against use_skip_indexes = 0, so it stayed green if the index
    silently stopped being applied. Added one EXPLAIN indexes = 1 granule assertion per scenario, in
    the shape the sibling test for the neighbouring defect already uses; the assertions differ between
    the unpatched and patched binaries, so they also prove pruning stays selective.
  • ⚠️ n = 1 was uncovered and the description understated the trigger (major, agreed, fixed).
    The trigger is n or more literal backslashes before a wildcard, so at the minimum supported
    ngrams(1) a single backslash is enough; every test used n = 2 and the description said "two or
    more". Added one tokensForLikePattern assertion at n = 1, and corrected the description and the
    changelog entry to state the general rule.
  • 💡 Checked whether this changes NOT LIKE pruning on ngrambf_v1, since it reuses the same needle
    tokens: it does not. BoolMask::operator!() is a swap, so after the negation can_be_true is
    unconditionally true and a notLike element can never drop a granule, measured as Granules: 3/3
    on both binaries with a pruning positive control on the same table. No behaviour change, so nothing
    is claimed about it in the description.
  • 💡 One comment wrap nit, not blocking.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b53f3b]

Summary: ✅


AI Review

Summary

This PR is now a tests-only follow-up to the already-merged tokenizer fix: it adds tokensForLikePattern coverage for consecutive backslashes and extends 05147_ngrambf_like_escaped_backslash_run to cover the ESCAPE rewrite into both live ngram tokenizer call sites, with a control row that distinguishes the escaped and loose rewrites. I do not see a remaining correctness or coverage gap in the current diff.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @shankar-iyer, could you review this? NgramsTokenizer::nextInStringLike advanced its sliding window by one raw byte instead of one decoded code point, so a LIKE pattern holding n or more escaped backslashes before a wildcard restarted inside an escape pair and emitted a required n-gram containing %, which no haystack can hold, so text(ngrams(n)) and ngrambf_v1 pruned granules that hold matching rows. The new stateless test follows the shape of the sibling 02346_text_index_like_unknown_backslash_escape.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1793a430c with master 3594fb131 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8396165e8; 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.

Object file sizes

8 object files changed (+48.68 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageFileCluster.cpp.o 346.41 KiB 371.27 KiB +24.86 KiB (+7.18%)
src/CMakeFiles/dbms.dir/Storages/StorageFile.cpp.o 1.08 MiB 1.10 MiB +21.23 KiB (+1.92%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

Comment thread src/Interpreters/ITokenizer.cpp Outdated

size_t code_points = 0;
bool escaped = false;
/// Byte offset just past the token's first code point, which is where the next n-gram starts. A code

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.

@groeneai Future readers of the code will not be able to decipher what you did here. Try a different approach.

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.

Rewritten in 1793a43: both loop locals are gone and the advance now states the rule directly.

if (code_points == n)
{
    /// The next n-gram starts one code point later. `pos` is at the start of this n-gram, whose
    /// first code point can be an escape sequence: the backslash and the character it escapes.
    if (data[pos] == '\\' && pos + 1 < length)
        ++pos;
    pos += UTF8::seqLength(static_cast<UInt8>(data[pos]));
    return true;
}

pos is already the first byte of the current n-gram's first code point, since it enters the function that way and the wildcard branch re-establishes it. So the whole defect is that an escape sequence is a single code point spanning two characters, and the change against master is now just skipping the backslash before the pre-existing UTF8::seqLength step: +4/-0 in src/, down from +10/-1, with no added state.

Equivalent to the previous shape rather than merely meant to be: an exhaustive differential over 823536 (pattern, n) pairs, every pattern of up to six symbols over {a, b, %, _, \, U+00E9, U+4F60} with n in 1..6, finds zero divergence, and the pinned 03403_function_tokens_for_like_pattern reference reproduces byte for byte on the rebuilt binary. 02346_text_index_like_* and the 221-test text_index / ngram / tokens sweep are green.

The description claimed the restart position came from the scan's own cursor, which is no longer what the code does; updated.

groeneai and others added 2 commits September 7, 2026 10:44
The previous shape carried the resume position in two extra loop locals, a
`next_pos` and a `code_points_before` snapshot, so that the byte offset just
past the token's first code point could be captured while scanning. That is
hard to read: nothing in the loop says why the 0 to 1 transition is the
interesting one, and the `code_points_before == 0` half of the guard is
silently load bearing, because a bare `code_points == 1` test also fires on
the iteration that merely opens an escape sequence.

`pos` is already the first byte of the current n-gram's first code point in
the pattern: it enters the function that way, and the wildcard reset branch
re-establishes it. The resume position is therefore just `pos` advanced past
one code point of the pattern, and the only thing the original line got wrong
is that an escape sequence is a single code point spanning two characters. An
advance that skips the escaping backslash says precisely that, needs no loop
state, and leaves the pre-existing `UTF8::seqLength` step in place.

Behaviour is identical to the previous shape. An exhaustive differential over
823536 (pattern, n) pairs, every pattern of up to six symbols over
{a, b, %, _, backslash, U+00E9, U+4F60} with n in 1..6, finds zero divergence
between the two, and the pinned `03403_function_tokens_for_like_pattern`
reference, n = 1 boundary line included, reproduces byte for byte.

No test change: the regression tests added earlier in this PR already pin the
behaviour and still redden on the pre-fix binary.
Ergus
Ergus previously requested changes Sep 14, 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.

This PR is a test only change, not a bug fix


-- Each query is paired with the same query with `use_skip_indexes = 0`: a skip index must never change the result.

SET enable_full_text_index = 1;

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.

This whole test duplicates most from 05147_ngrambf_like_escaped_backslash_run

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.

enable_full_text_index = 1 is already defaulted to 1

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.

Right on both counts, and the duplication has a cause: the source fix this PR opened with was reworked into #118673 and merged, which brought 05147_ngrambf_like_escaped_backslash_run with it, so this file became a second copy of a test that already exists.

Deleted it. What 05147 did not have I folded into 05147 itself in 3c9646f: the custom-ESCAPE arm per index type, with the granule count from index analysis asserted next to the result pair. enable_full_text_index is gone with the file; it defaults to 1 since the text index went GA (Settings.cpp: DECLARE_WITH_ALIAS(Bool, enable_full_text_index, true, ...)), and 05147's own text-index block never set it.


SELECT '-- the same pattern reached through a custom ESCAPE character';

SELECT groupArray(id) FROM tab WHERE msg LIKE '%ab\\\\%cd%' ESCAPE '!';

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 ESCAPE arm covers only one of the two escape-folding call sites right?

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.

Correct. likePatternWithCustomEscapeToLikePattern has four callers, and the two that then tokenize the pattern are MergeTreeIndexBloomFilterText.cpp:410 (ngrambf_v1, tokenbf_v1) and MergeTreeIndexConditionText.cpp:713 (text). This file put its ESCAPE arm in the text-index block only, so the bloom-filter fold was uncovered. The other two callers, FunctionsStringSearch.h:375 and KeyCondition.cpp:4104, do not tokenize, so they cannot carry this defect.

05147 now has an ESCAPE arm in both index blocks (3c9646f). Both fold to the pattern the direct arm already uses and prune identically: Granules: 1/2 each, and the text condition prints the same required set, tokens: ["\\\\", "ab", "b\\", "cd"].

The `NgramsTokenizer::nextInStringLike` fix this branch carried was reworked and
merged as 67ccc41, with the regression test
05147_ngrambf_like_escaped_backslash_run, so the separate test file added here
duplicated it. Delete that file and keep only what 05147 did not have, in 05147.

`LIKE <pattern> ESCAPE '<c>'` arrives at the skip indexes as a three-argument
`like(col, pattern, c)` call, and both index conditions that tokenize a pattern
fold the custom escape character into a backslash-escaped pattern before
tokenizing it: MergeTreeIndexBloomFilterText.cpp for `ngrambf_v1`/`tokenbf_v1`
and MergeTreeIndexConditionText.cpp for `text`. The fold maps a literal
backslash to `\\` (likePatternWithCustomEscapeToLikePattern), so a pattern whose
user-visible form carries no backslash run can still present one to the
tokenizer. The deleted file exercised the fold in the `text` condition only.

Each arm asserts the granule count index analysis reached, not only that the two
results agree: an index whose required token set went empty is still classified
as useful, prunes nothing, and leaves both counts at 1. Both arms reach the
tokenizer with the direct arm's pattern and prune identically, `Granules: 1/2`,
and the text condition prints the same required set,
`tokens: ["\\\\", "ab", "b\\", "cd"]`. The assertion produces no row at all when
the index is not applied, which is what makes it stronger than
`force_data_skipping_indices`; it pins `use_skip_indexes_on_data_read`, which the
test runner randomizes and which moves the filtering past index analysis
(measured: the count reads 2/2 for both index types at 1).

`enable_full_text_index` is not set anywhere: it defaults to 1 now that the text
index is GA.
@groeneai groeneai changed the title Fix rows lost by ngram skip indexes for LIKE patterns with escaped backslashes before a wildcard Test the ESCAPE route into the ngram LIKE-pattern tokenizer Sep 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

You are right, and the cause is on my side. The source fix this PR opened with was reworked and merged as #118673 (67ccc416) on 2026-09-08, which closed #117858 and added 05147_ngrambf_like_escaped_backslash_run; the master merge into this branch the next day took the source change out of the diff, and I did not re-read the metadata afterwards. master...HEAD is four test files.

Corrected in place: title, category (CI Fix or Improvement, no changelog entry), Closes replaced by Related links to the issue and to #118673, description rewritten. The pr-bugfix label is stale for the same reason, and the Bugfix validation jobs cannot pass on a diff with no source change.

What is left is the coverage 05147 does not have, folded into 05147 in 3c9646f: a custom-ESCAPE arm per escape-folding call site, each asserting the granule count index analysis reached rather than only that the indexed and unindexed results agree, plus three tokensForLikePattern lines in 03403_function_tokens_for_like_pattern. Details in your two threads. If you would rather not carry the extra arms at all, say so and I will close this.

@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot added comp-testing Test content only (no production code). and removed comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... labels Sep 14, 2026
The custom-escape arms asserted one positive value, `xxab\\cdyy`, which also matches
`%ab%cd%`, and the second granule held neither `ab` nor `cd`. A rewrite of
`likePatternWithCustomEscapeToLikePattern` that dropped the literal backslashes therefore
left both counts at 1 and the granule count at `1/2`: measured by deleting the branch that
emits them, the arms passed unchanged on both index paths.

`xxabcdyy` is that value without the backslashes, in another granule, so the loose rewrite
now reddens six assertions, both ESCAPE counts and `Granules: 2/3` for `ngrambf_v1` and for
the text index. The patterns that require the backslashes still match one row, while
`%ab%cd%` and `%xxab%` now match two.
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
Merged via the queue into ClickHouse:master with commit b2cc32b Sep 19, 2026
177 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot added comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... and removed comp-testing Test content only (no production code). labels Nov 22, 2026
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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants