Repository navigation
Test the ESCAPE route into the ngram LIKE-pattern tokenizer - #118279
alexey-milovidov merged 8 commits into
Conversation
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]>
Internal second-model reviewIndependent cold review plus a second-model gate on this branch, two fix rounds; the final round's
|
|
Workflow [PR], commit [8b53f3b] Summary: ✅ AI ReviewSummaryThis PR is now a tests-only follow-up to the already-merged tokenizer fix: it adds Final Verdict✅ Approve. |
|
cc @ahmadov @shankar-iyer, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+48.68 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline. |
|
|
||
| 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 |
There was a problem hiding this comment.
@groeneai Future readers of the code will not be able to decipher what you did here. Try a different approach.
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
This whole test duplicates most from 05147_ngrambf_like_escaped_backslash_run
There was a problem hiding this comment.
enable_full_text_index = 1 is already defaulted to 1
There was a problem hiding this comment.
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 '!'; |
There was a problem hiding this comment.
the ESCAPE arm covers only one of the two escape-folding call sites right?
There was a problem hiding this comment.
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.
|
You are right, and the cause is on my side. The source fix this PR opened with was reworked and merged as #118673 ( Corrected in place: title, category ( 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 |
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.
Related: #117858
Related: #118673
Changelog category (leave one):
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 added05147_ngrambf_like_escaped_backslash_run. The source diff here is empty as a result, so the category is nowCI Fix or Improvementand 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-argumentlike(col, pattern, c)call, and both index conditions that tokenize a pattern fold the escape character into a backslash-escaped pattern first:MergeTreeIndexBloomFilterText.cpp:410forngrambf_v1/tokenbf_v1andMergeTreeIndexConditionText.cpp:713fortext. 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 noESCAPEarm; this adds one per call site. The regression test deleted here had covered thetextcall site only.Oracle. Each arm asserts the granule count index analysis reached, not only that the indexed result and the
use_skip_indexes = 0result 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 holdsxxabcdyy, 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 oflikePatternWithCustomEscapeToLikePatternthat 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 andGranules: 2/3, in each index path).Also here: three
tokensForLikePatternlines in03403_function_tokens_for_like_pattern, covering the defect atngrams(2), the single-backslash pattern that was always correct, and thengrams(1)boundary.Workflow [PR]
Sync PR [sync-upstream/pr/118279]
Version info
26.10.1.240-master(included in26.10and later)