Repository navigation
Add reusable automaton intersection for text index dictionaries - #121650
alexey-milovidov merged 9 commits into
Conversation
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
|
Workflow [PR], commit [297118f] Summary: ✅
AI ReviewSummaryAdds reusable byte DFAs to skip unrelated text-index dictionary blocks for anchored Final Verdict✅ Approve. No changes requested. |
CI includes RE2 with a regular include path, exposing old-style casts and anonymous-structure warnings in its private headers under `-Weverything`. Extend the existing diagnostic scope around `re2/prog.h`, keeping warnings enabled for the surrounding ClickHouse implementation. Reproduced the eight compiler errors with a non-system RE2 include path; the corrected source passes that check and the ASan/UBSan automaton tests. Related: ClickHouse#121650 CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121650&sha=a16d3568b53e0935fb8d953c444131be42ef5475&name_0=PR&name_1=Fast%20test
The randomized RE2 differential test intentionally uses a fixed seed so failures are reproducible. Add a targeted `NOLINT` for the random-seed security checks, following the existing unit-test convention. Related: ClickHouse#121650 CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121650&sha=c4399bbd21bf304974d4363b3345ee802a875be6&name_0=PR&name_1=Build%20%28arm_tidy%29
`Weverything -Werror` makes re2's own header an error: `longest_match_` is a 1-byte bit-field following a 4-byte one, which trips -Wms-bitfield-padding on clang 21. `Common/re2.h` exists to push exactly those diagnostics around the include, and is what the other fifty users in the tree - three of them gtests - go through. The automaton source already does; only the test included re2 raw. Co-Authored-By: Claude Opus 5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds an automaton that skips parts of a text index's dictionary when matching LIKE patterns. The only change is inside the MergeTree text index code, and neither ClickBench nor TPC-H defines a text index. The one flagged query, ClickBench Q34 (-5.6%), is downgraded to not sure because it cannot reach the changed path. That result also rests on a thin baseline: only 5 runs after the recent master refit, with two of the PR's runs sharing one machine. The PR's own text_index_dictionary_dfa performance test is where to look for its intended effect. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@valerypetrov The PR message explains the "what" but not the "why" not so much. Does the automaton help to reduce dictionary block lookups? |
Makes sense. Simplified PR body and added why it works faster with automaton. |
The wasm64 build failed in `TextIndexDictionaryAutomaton.cpp`: the emscripten sysroot defines `NULL` as `0L`, so the internal RE2 headers trigger `-Wzero-as-null-pointer-constant`. Ignore it the same way `src/Common/re2.h` does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Should be ready for review. |
| namespace DB | ||
| { | ||
|
|
||
| /// A deterministic byte automaton over complete dictionary keys. No index-format or |
There was a problem hiding this comment.
Looks like this class realizes this automaton: https://en.wikipedia.org/wiki/Deterministic_finite_automaton
Please then call it like that (it's not really clear what a "byte automaton" is).
There was a problem hiding this comment.
added to the description more info about it(as well as for the comments in code).
| { | ||
|
|
||
| /// A deterministic byte automaton over complete dictionary keys. No index-format or | ||
| /// tokenizer assumptions: regex, wildcard and edit-distance compilers can supply the |
There was a problem hiding this comment.
"regex, wildcard and edit-distance compilers can supply the same transitions" - what does that mean?
|
|
||
| /// A deterministic byte automaton over complete dictionary keys. No index-format or | ||
| /// tokenizer assumptions: regex, wildcard and edit-distance compilers can supply the | ||
| /// same transitions. State zero is the initial state; absent transitions reject. |
There was a problem hiding this comment.
What does "absent transitions reject" mean?
| namespace DB | ||
| { | ||
|
|
||
| /// A deterministic byte automaton over complete dictionary keys. No index-format or |
There was a problem hiding this comment.
What does "complete dictionary keys" mean? This reads like the automaton is encoding the entire dictionary but that's not the case.
|
|
||
| struct Transition | ||
| { | ||
| uint8_t first; |
There was a problem hiding this comment.
first, last - not really clear what that represents, please document.
| /// search is usually a better candidate filter than seeking a sorted dictionary. | ||
| bool canSkipPrefixes() const; | ||
|
|
||
| enum class Result : uint8_t |
There was a problem hiding this comment.
Let's move this enum class into Cursor?
| public: | ||
| explicit Cursor(const TextIndexDictionaryAutomaton & automaton_) : automaton(automaton_) {} | ||
|
|
||
| /// Match: `key` is accepted. Seek: no accepted key lies in [key, next), |
There was a problem hiding this comment.
"key" and "seek_target" are too generic names. Maybe "needle" and "haystack"? (this terminology is used a lot in the code).
|
|
||
| /// Match: `key` is accepted. Seek: no accepted key lies in [key, next), | ||
| /// and next > key in unsigned byte order. Exhausted: no key >= key matches. | ||
| /// A seek target need only be a prefix of an accepted key: cyclic languages |
There was a problem hiding this comment.
A seek target need only be a prefix of an accepted key: cyclic languages
need not have a lexicographically smallest accepted extension.
Not really clear what this means, please re-phrase or add an example.
| @@ -0,0 +1,65 @@ | |||
| -- Tags: no-parallel-replicas | |||
| -- no-parallel-replicas: the block-read assertion uses the initiator's ProfileEvents. | |||
There was a problem hiding this comment.
Let's start the test with a comment that explains what the test is supposed to check.
|
|
||
| TextIndexDictionaryAutomaton::TextIndexDictionaryAutomaton(std::vector<State> states_) : states(std::move(states_)) | ||
| { | ||
| chassert(!states.empty()); |
There was a problem hiding this comment.
Can you add a comment what this ctor is computing?
EDIT: The functions in this file need many more comments.
… document it Address review: name the class after what it is (a deterministic finite automaton), move `Result` into `Cursor`, rename the `Cursor::next` parameters to `token` / `lower_bound`, document every member and function with examples (a worked `LIKE 'ab%c'` DFA and dictionary walk), and explain what the stateless test checks. The files, the gtest suite and the tests are renamed accordingly. No behaviour change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes12 object files changed (+100.86 KiB total), 1 added.
719 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 units35 translation units recompiled, 344 s compile time in total, 34 of them have a recent master baseline. |
|
Should be ready for review. |
|
Dear @CurtizJ, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
@rschu1ze , I believe most of the things has been addressed. Can you check please? |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Can the automata get too large?
Looks ok. |
Good question. Let me reproduce that on the test stand. |
Automaton size check (re: "Can the automata get too large?")Setup: PR Pruning claim reproduces: A single automaton is bounded, and it falls back cleanly. The 1 MiB cap holds.
Problem: there is no aggregate bound. The automaton is built per
Suggestion: apply a total automaton budget per Repro: |
Each `LIKE` pattern built its own DFA (up to 1 MiB each) with no limit across patterns, so a query with hundreds of `OR`ed patterns kept hundreds of automata (500 patterns: ~590 MiB, 10x slower, `MEMORY_LIMIT_EXCEEDED` under `max_memory_usage = 256M`). A pattern whose DFA exceeded the cap also burned the whole RE2 budget (~7 ms) on every query before falling back. - Share a `TextIndexAutomatonBudget` (4 MiB) between all patterns of one `MergeTreeIndexConditionText`. A failed attempt is charged the full per-pattern limit, so the total build time is bounded too. Patterns without an automaton use the regular dictionary scan, so only speed is affected. - Lower the per-pattern limit from 1 MiB to 256 KiB: ordinary patterns need a few KiB, and a failed build is ~3x cheaper. - Add `TextIndexDictionaryDFA::memoryUsage`. - Add test `05238_text_index_dictionary_dfa_budget`. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
Pushed
Same setup as the previous report (1M tokens,
Single-pattern pruning is unchanged, and results are identical to the index-off runs. |
…x-automaton-intersection
With `use_constant_folding_in_index_analysis`, `ConditionTemplate` creates one `MergeTreeIndexConditionText` per partition. Each had its own automaton budget and recompiled all `LIKE` patterns, so the cost of building the automata (failed attempts included) was paid once per partition: 30 patterns on 32 partitions took 1.2 s instead of 0.17 s. - Own the `TextIndexAutomatonBudget` in `MergeTreeIndexText`, which is created once per query and index, and pass it to every condition it creates. - Cache the built automata in the budget by pattern kind, options and text, so identical patterns are compiled once. Failures are cached too: the budget only shrinks, so a failed pattern would fail again. - Add the profile event `TextIndexDictionaryDFABuilds` (cache hits excluded). - Extend `05238_text_index_dictionary_dfa_budget` with a partitioned table and constant folding: the number of builds must not grow with the partitions (270 builds without sharing, at most 41 with it). Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Master (ClickHouse#121650) builds a dictionary DFA per LIKE pattern and bounds them by a `TextIndexAutomatonBudget` shared by all conditions of the index. Every other pattern query passes it; the phrase word query did not, so its automaton was neither shared nor counted against the per-query limit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The dictionary DFA from ClickHouse#121650, now merged, already restricts the dictionary scan of a case-insensitive pattern with a literal prefix to the blocks that can hold a match: `ILIKE 'java%'` on the issue's 4M-row table reads 1 dictionary block on master, and every dictionary-block count in 05315 is the same with and without the key ranges. So the key ranges only duplicated it. A case-insensitive phrase word starting with `s` or `k` is still not searched: re2 folds U+017F and U+212A onto them, so the regexp has no literal prefix, gets no DFA, and its search reads every dictionary block (measured: 14 of 14 in 05315). Among the other words, the longest one is searched. The test loses the ILIKE prefix and `array` tokenizer cases, which covered only the key ranges; the performance query for an ILIKE prefix goes for the same reason. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Why
A text index keeps a sorted dictionary of all tokens. For a query like
LIKE 'service%error', ClickHouse used to read every dictionary block and check each token against the pattern, even though only tokens starting withservicecan possibly match.On 1M rows that means reading 7813 blocks to find the 8 that matter.
What this PR does
It turns the pattern into a small automaton and walks the sorted dictionary with it. When the automaton says "nothing between here and token X can match", the reader jumps straight to X. Blocks that can't contain a match are never read.
LIKE/ILIKEwith wildcards inside ('service%error','service____error').'%service%'), or that are too complex to compile, keep using the old code path. Results are always re-checked by the existing matcher, so this only changes speed, not answers.Builds on #120495.
Result
1M rows, one thread, median of 7-15 runs:
'service%error''service____error''service5%9error''missing%error''service%','%service%''unrelated%error'(matches almost every token)The last row is the worst case: when nearly every token matches there is nothing to skip, and the extra automaton step costs a little.
Testing
Built
c4f57f593dalocally (macOS arm64, clang, Release).TextIndexDictionaryDFA.*: 5/5 pass.05238_text_index_dictionary_dfaand the updated05218_text_index_like_dictionary_scan_pruningpass (also with randomized settings).text_indexstateless tests: all pass, except ones that need a setup not available locally (test clusters,test.hits, interserver port,jinja2).ILIKE, NUL/0xFFbytes,NOT LIKE) and 2400 random patterns.Related: #115617
Automaton: a deterministic finite automaton over bytes (
TextIndexDictionaryDFA). Exact tokens and prefixes build it directly. ALIKEpattern is translated into a regular expression, and RE2 builds its complete DFA within a memory limit; if it does not fit, the regular dictionary scan is used. When the DFA rejects a dictionary token, it gives the smallest string the next match can start with, and the scan jumps there by binary search instead of reading every token.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Use automaton-guided dictionary seeks to skip unrelated text-index blocks for anchored
LIKEandILIKEpatterns containing internal wildcards.Workflow [PR]
Sync PR [sync-upstream/pr/121650]
Generated by Claude Code
Version info
26.11.1.1092-master(included in26.11and later)