Repository navigation
Text index: seek the dictionary to the matching block range for anchored LIKE patterns - #120495
Conversation
…n can match Evaluating LIKE / ILIKE / startsWith / endsWith by dictionary scan (use_text_index_like_evaluation_by_dictionary_scan, on by default) read every dictionary block of the part, whatever the pattern's shape. The dictionary is globally sorted and the header's sparse index already stores each block's first token, so an anchored pattern can only match inside one contiguous block range. This is follow-up item 2 of the list in MergeTreeIndexConditionText.cpp. TextIndexAnalyzer::getPatternTokenKeyRanges reports, per pattern, the half-open range of token keys it can match: [literal, firstStringThatIsGreaterThan- AllStringsWithPrefix(literal)) for a Prefix pattern, the point range [literal, literal] for an Exact one (which requires subject_size == literal_size, so at most one block can hold it), and nothing for Suffix / Substring / General, which decline the narrowing for the whole scan. Prefix and Exact are byte comparisons: the OptimizedRegularExpression constructor demotes a case-insensitive anchored literal to General, because a case-insensitive re2 folds Unicode and a byte comparison cannot reproduce that. Byte order is the order the dictionary is sorted in, so the narrowing is sound in that order, and ILIKE never reaches it. blocksMatchingTokenKeyRanges turns the key ranges into merged block intervals. No block before range_begin can hold a matchable token, since a block is indexed by its smallest token and first(range_begin) <= begin by upperBound; no block at or after range_end can, since all its tokens exceed the range's end key while every matchable token is below it. upperBound's strict comparison keeps a block whose first token equals the end key, which is one extra block and still correct. Intervals rather than a materialized list of block indices: dictionary_block_size is user-settable down to 1, so a wide range over a large dictionary would hold millions of indices. There is no sentinel value either: an unrestricted scan is the single interval [0, size), and an empty vector means no block can match, so a prefix absent from the dictionary now reads nothing instead of falling back to a full scan. text_index_like_max_postings_to_read behaves identically: the budget accumulates only over matched tokens, blocks are still visited in ascending order, and a skipped block provably holds no matching token, so the bypass fires at the same point. The pattern scan also now increments TextIndexReadDictionaryBlocks, which so far only the exact-token scan did. Without it the number of blocks this scan reads is not observable, which is what makes a test of the narrowing timing-based. Reported and prototyped by @snelheidai in ClickHouse#120457. Co-Authored-By: Claude Opus 5 <[email protected]>
…in one pass The dictionary pattern scan ran the compiled matcher once per token of every block it visited. A block's tokens are contiguous in one ColumnString buffer and every compiled pattern carries a mandatory literal that match() tests before re2, so one searcher pass over that buffer already finds every token that can match. TextIndexAnalyzer::matchTokensByLiterals marks the tokens containing some pattern's literal, then runs addTokenToPatterns only on the marked ones. The matcher stays the only decider: a token no pattern's literal occurs in would have been rejected by match() anyway, on each of its three paths - anchored (memcmp at the one possible offset), trivial and general (both refuse a subject the searcher does not find the literal in). Hence the marked set is a superset of the matched set and the result is unchanged. The filter is disabled for the whole scan if any pattern has no literal, in which case the per-token loop is kept. OptimizedRegularExpression::searchRequiredSubstring exposes the pattern's own searcher. Using that searcher rather than a locally built one is what makes the superset property hold: only one of the two searchers is ever constructed, so the folding rule cannot diverge from the one match() applies. This is also why MatchImpl's loop is not reused - its VolnitskyCaseInsensitiveUTF8 falls back to UTF8CaseInsensitiveStringSearcher, which folds differently from the ASCIICaseInsensitiveStringSearcher match() uses, and for the case-sensitive path Volnitsky degenerates to the same CaseSensitiveStringSearcher below 20000 bytes of haystack, which every dictionary block is. ILIKE reaches the filter and is safe. stringLikeToPatterns refuses any needle holding a character reachable by ASCII case folding (U+212A folds onto 'k') before the scan starts, so a token whose bytes only fold to the needle under Unicode rules cannot arrive here. The per-pattern pass follows the required-substring loop of MatchImpl::vectorConstant, including its containment check: tokens are stored back to back and are not zero-terminated, so an occurrence may straddle two of them. Skipping such a hit is exact rather than conservative, because an occurrence contained in the token would have to start earlier than one leaving it. Marks, not a collected candidate list: queries_by_pattern holds one entry per pattern of every search query in the RPN, so several patterns are ordinary, and a union of per-pattern index lists would grow as patterns x tokens and need a sort and a dedup pass. One byte per token of the block is allocated once per scan and emits ascending and unique indices, as deserializeTokenInfos requires. Tests. 05218_text_index_like_dictionary_scan_pruning pins the number of dictionary blocks read for each pattern shape against a hand-sized dictionary of 4 blocks, and compares every scenario against the same query with use_skip_indexes = 0, so over-pruning changes the result and under-pruning changes the counter. A prefix absent below the whole dictionary reads 0 blocks and an infix reads all 4, which are the two-directional sensitivity controls. The gtest asserts the superset property directly, including the ASCII-folded case, which is not observable from SQL on its own. The performance test carries a 500000-token dictionary, since the existing text_index_like.xml fixture has about 20 tokens, i.e. one block, where neither change is visible. Reported and prototyped by @snelheidai in ClickHouse#120457. Co-Authored-By: Claude Opus 5 <[email protected]>
… recalibrate the perf test Three test-level gaps found while reviewing the two preceding commits. A literal occurrence may straddle two adjacent dictionary tokens, because a block's tokens are stored back to back and are not zero-terminated, and the filter must then attribute the hit to no token at all and carry on with the next one. No scenario reached that branch, whose failure mode is a token that should have matched being skipped, i.e. rows missing from a LIKE result. 'aabb', 'ccdd', 'xxbbcc', 'yybb' share one block as the bytes 'aabbccddxxbbccyybb', where 'bbcc' straddles the first two tokens and then ends exactly on the end of 'xxbbcc', so one scenario exercises the straddle and the containment test's boundary at once. A pattern whose every literal run is shorter than the three bytes the regexp analysis requires carries no mandatory literal, so it can match a token anywhere in the dictionary. Both new gates therefore refuse for the whole scan as soon as one pattern is like that, and nothing tested it. The array tokenizer admits 'a%b%c%d' because it counts non-wildcard characters, which gives such a pattern; the scenarios pair it with a literal-bearing prefix as well as running it alone, and assert the full block count against the one block that prefix alone is narrowed to. The performance test's queries all ran far outside the 0.1 to 1 second window the harness requires, the anchored ones at 5 ms and the dense one at 4.6 s, so it could not have measured what it exists to defend. The scan runs once per part, so the table is now 30 parts with merges pinned instead of one, the needle is broader to give the patched side work to do, the dense case moved to its own single-part table, and the hasToken query is gone: the token scan already seeks to one block per part, so no fixture of this shape can lift it above the floor, and five other text index performance tests cover it. Also state on TokenKeyRange that equal bounds mean the single key, since the Exact case relies on it and a lowerBound-style seek would silently break it.
Drop the block-range end-bound comment (the sort-order property is stated one comment above), cut the two contract comments that restated the code below them.
Internal second-model review (2 rounds): 3 major fixed, 1 declined, 4 nitsEach round ran two independent cold passes over this diff, my own read of the resulting code and a
❌ declined: a new ProfileEvent counting matcher calls or candidate tokens. The second pass asked for 💡 nits. Fixed: the exact-point encoding of the token-key range is now stated on the struct (equal |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260916-210900 |
|
Workflow [PR], commit [69de08b] Summary: ✅
AI ReviewSummaryThis PR narrows text-index dictionary scans for anchored Final Verdict✅ No actionable review findings in the current patch. LLVM Coverage ReportMeasured on commit 69de08b.
Changed lines: Changed C/C++ lines covered: 132/135 (97.78%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=12 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
`blocksMatchingTokenKeyRanges` resolved both ends of a token-key range with `upperBound`. For an anchored prefix the end is exclusive, being `firstStringThatIsGreaterThanAllStringsWithPrefix` of the literal, so `upperBound` kept the block whose first token is exactly that bound. The dictionary is sorted, so every token of such a block is at or beyond the bound and none of them can carry the prefix. Measured on a two-block dictionary whose second block starts exactly at `toab`: `LIKE 'toaa%'` read 2 blocks where 1 suffices, per pattern and per part. The rows returned were never affected, because the per-token matcher still decided, so this was an over-read and not a wrong result. Resolve an exclusive end with a new `DictionarySparseIndex::lowerBound`, and keep the `Exact` kind on `upperBound`: its bounds are equal and denote a single key, so a lower-bound lookup would drop the very block that starts with it. The example given in the report, a sparse index `["foo0", "fop0", ...]` queried with `foo%`, does not exhibit this. `fop0` is strictly greater than the bound `fop`, so that block was already excluded; only a block starting exactly at the bound was read needlessly. Found by the automated review on ClickHouse#120495 (comment)
The comment claimed the literal occurs in all 500008 tokens and that every token has a single posting. Both hold for the 500000 `toxxN` tokens but not for the eight words each message shares, which carry 500000 postings apiece. The control's conclusion is unchanged: those eight never contain the literal, so they charge no postings budget, measured as zero discards at the default. This was disclosed as a residual when the PR was opened, because the phase that found it could only change comments in `src/`.
`blocksMatchingTokenKeyRanges` declared `range_end` without an initializer and
assigned it in every branch of the if/else chain below it. This tree enables
clang-tidy's `cppcoreguidelines-init-variables`, so `Build (arm_tidy)` failed:
src/Storages/MergeTree/MergeTreeIndexText.cpp:516:16: error: variable
'range_end' is not initialized [cppcoreguidelines-init-variables]
Initialize it where it is declared, the way the neighbouring `range_begin`
does, using the unbounded value an empty `end` selects, and narrow it only when
`end` is set. All three cases keep their results, so the block ranges the
dictionary scan visits are unchanged.
Verified with clang-tidy-22 and this tree's `.clang-tidy`: the error is
reported before the change and nothing after it. Reverting the exclusive-end
lookup inside the rewritten statement still reddens `05218_at_upper_bound`
(2 blocks read instead of 1), so the pinned block counts remain sensitive to it.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+36.85 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 units304 translation units recompiled, 2770 s compile time in total, 304 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.89 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
ClickBench and TPC-H carry no text index, so the Cloud Performance Report above is silent on the path this PR changes. End-to-end numbers on it, on a large-vocabulary fixture rather than the one-unique-token-per-row shape of the new perf test:
8M rows, 128 parts, The time comes out of the scan, not out of pruning: One correction to my own estimate in #120457, where I extrapolated your The residual, relevant to the |
|
Thanks for running this end to end. I am not folding those percentages into the description. I have not reproduced that fixture, and the figures there are what the committed perf test measures, with the On the residual: this PR narrows what the dictionary scan costs, it does not decide when the scan should run. That question and the per-part bound stay in #120457, and I am not pulling them into this diff. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Good change, thanks!
|
@ahmadov Just FYI^^ (since in your code) |
Compile bounded byte automata from literals and RE2 expressions, reuse common prefix states, and seek past rejected dictionary subtrees. Integrate with the existing `LIKE` dictionary reader and postings budget without changing the index format. Add differential, SQL and performance coverage. Motivation: https://playground.serenedb.com/searchbench Related: ClickHouse#120495 Related: ClickHouse#115617
Related: #120457
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up
LIKE,ILIKE,startsWithandendsWithevaluated by a text index dictionary scan (use_text_index_like_evaluation_by_dictionary_scan): the scan now seeks the sorted dictionary to the block range an anchored pattern can match, and tests a block's tokens for the pattern's mandatory literal in one pass instead of running the matcher on every token.Description
A pattern evaluated by dictionary scan read every dictionary block of the part and called the matcher once per token. Two facts were unused: the dictionary is sorted and the sparse index stores each block's first token, and every compiled pattern carries a mandatory literal
matchtests first.Follow-up item 2 at
MergeTreeIndexConditionText.cpp:1536(item 3 is #116585's). #114613 has the same primitive wired only to JSON paths.Two mechanisms:
Prefix-> the prefix range,Exact-> a point range, anything else declines) becomes merged half-open block intervals.Prefix/Exactare byte comparisons, since the constructor demotes a case-insensitive anchored literal toGeneral, and that is the order the dictionary is sorted in, soILIKEnever narrows. A prefix sorting below the whole dictionary now reads 0 blocks.match's.addTokenToPatternsstays the only decider and the filter yields a superset of what it accepts, so results are unchanged.Measured with the perf test added here (30 parts, 500008 dictionary tokens and 977 blocks each, single-threaded, Release, 25-run medians): infix
LIKE-21.7%,LIKE 'needle%'andstartsWith-58.4% (29310 -> 690 blocks),ILIKE-11.9%, suffixLIKEandendsWith-19.4%. A prefix covering one block per part reaches -95.8%, too fast to ship as an arm. The filter's worst case, a literal in 500000 of 500008 tokens, is +0.8%, inside that arm's spread;hasTokendoes not use this path.The pattern scan now also increments the existing
TextIndexReadDictionaryBlocks, making the blocks it reads observable. No setting, no format change.Reported and prototyped by
@ snelheidaiin #120457.Workflow [PR]
Sync PR [sync-upstream/pr/120495]
Version info
26.10.1.164(included in26.10and later)