Skip to content

Add reusable automaton intersection for text index dictionaries - #121650

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
valerypetrov:feature/text-index-automaton-intersection
Nov 2, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
valerypetrov:feature/text-index-automaton-intersection

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

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 with service can 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.

  • Works for anchored LIKE / ILIKE with wildcards inside ('service%error', 'service____error').
  • Patterns it doesn't handle (e.g. '%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.
  • The automaton part is reusable, so it can later back other matchers (e.g. fuzzy / edit-distance search).
  • No new on-disk format, no new SQL functions.

Builds on #120495.

Result

1M rows, one thread, median of 7-15 runs:

pattern before after
'service%error' 16 ms, 7813 blocks 2 ms, 8 blocks
'service____error' 16 ms, 7813 blocks 1 ms, 8 blocks
'service5%9error' 16 ms, 7813 blocks 1 ms, 2 blocks
'missing%error' 16 ms, 7813 blocks 1 ms, 0 blocks
'service%', '%service%' unchanged unchanged
'unrelated%error' (matches almost every token) ~857 ms ~890 ms (3-6% slower)

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 c4f57f593da locally (macOS arm64, clang, Release).

  • Unit tests TextIndexDictionaryDFA.*: 5/5 pass.
  • New stateless test 05238_text_index_dictionary_dfa and the updated 05218_text_index_like_dictionary_scan_pruning pass (also with randomized settings).
  • 229 existing text_index stateless tests: all pass, except ones that need a setup not available locally (test clusters, test.hits, interserver port, jinja2).
  • Index on vs off gives identical results for 31 hand-written patterns (escapes, UTF-8, ILIKE, NUL/0xFF bytes, NOT LIKE) and 2400 random patterns.

Related: #115617

Automaton: a deterministic finite automaton over bytes (TextIndexDictionaryDFA). Exact tokens and prefixes build it directly. A LIKE pattern 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):

  • Performance Improvement

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 LIKE and ILIKE patterns containing internal wildcards.


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


Generated by Claude Code

Version info

  • Merged into: 26.11.1.1092-master (included in 26.11 and later)

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
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [297118f]

Summary: ✅


AI Review

Summary

Adds reusable byte DFAs to skip unrelated text-index dictionary blocks for anchored LIKE and ILIKE patterns. Reviewed head 297118fc43a06dba1031c3a96ac3651e12769219, including prior discussions and the budget/cache changes. No actionable findings remain; the previous partition-specific budget finding is addressed and its bot-authored thread has been resolved.

Final Verdict

✅ Approve. No changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 22, 2026
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
@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 22, 2026
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]>
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1269 1198 -5.6% <0.0001 This PR only changes how text-index dictionaries are scanned for LIKE patterns, and the ClickBench hits table has no text index, so Q34 never runs the changed code. The -5.6% shift rests on only 5 baseline runs after the baseline was refit.

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
  • StressHouse run: 488502fa-2e06-4161-a74d-5f00d6745dcd
  • MIRAI run: d66671a9-e7b0-4945-9272-cb3083fa4034
  • PR check IDs:
    • clickbench_2458288_1790721516
    • clickbench_2458294_1790721516
    • clickbench_2458300_1790721516
    • tpch_adapted_1_official_2458307_1790721516
    • tpch_adapted_1_official_2458322_1790721516
    • tpch_adapted_1_official_2458358_1790721516

@rschu1ze

Copy link
Copy Markdown
Member

@valerypetrov The PR message explains the "what" but not the "why" not so much. Does the automaton help to reduce dictionary block lookups?

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@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]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Should be ready for review.

@CurtizJ CurtizJ self-assigned this Sep 24, 2026
namespace DB
{

/// A deterministic byte automaton over complete dictionary keys. No index-format or

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

"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.

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.

What does "absent transitions reject" mean?

namespace DB
{

/// A deterministic byte automaton over complete dictionary keys. No index-format or

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.

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;

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.

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

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.

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

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.

"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

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.

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.

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.

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());

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.

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 297118fc4 with master 86396e41a (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.

Object file sizes

12 object files changed (+100.86 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/TextIndexDictionaryDFA.cpp.o new 57.62 KiB +57.62 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexConditionText.cpp.o 948.85 KiB 974.33 KiB +25.48 KiB (+2.69%)

719 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

35 translation units recompiled, 344 s compile time in total, 34 of them have a recent master baseline.

Job report

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Should be ready for review.

@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

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.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@rschu1ze , I believe most of the things has been addressed. Can you check please?

@alexey-milovidov alexey-milovidov 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.

Can the automata get too large?

@alexey-milovidov alexey-milovidov self-assigned this Nov 1, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

or that are too complex to compile

Looks ok.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Can the automata get too large?

Good question. Let me reproduce that on the test stand.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Automaton size check (re: "Can the automata get too large?")

Setup: PR a2a89bce rebased onto master a43327cd, macOS arm64 Release. Compared against the same master without the DFA. 1M-row table from text_index_dictionary_dfa.xml (tokenizer = array, dictionary_block_size = 128), max_threads=1.

Pruning claim reproduces: service%error reads 8 dictionary blocks instead of 7813. missing%error reads 0. Results are identical to baseline in every probe.

A single automaton is bounded, and it falls back cleanly. The 1 MiB cap holds.

pattern DFA built? blocks (base → PR)
service%a + 8×_ yes (~0.7 MB) 7813 → 8
service%a + 10..64×_ no, cap hit 7813 → 7813
service + 1000×_, service + 100×%a fallback / fine no regression

Problem: there is no aggregate bound. The automaton is built per LIKE pattern and kept for the query's lifetime. OR of N patterns of the form service%a________<i>:

N peak mem base → PR time base → PR
10 1.8 MB → 12 MB 100 → 166 ms
100 4.7 MB → 114 MB 178 → 1112 ms
500 17 MB → 591 MB 551 → 5527 ms
  • Memory: about 1.15 MB per pattern, growing linearly.
  • Failure: with max_memory_usage=256M, N=500 runs on baseline but fails on the PR with MEMORY_LIMIT_EXCEEDED (569 MiB).
  • Construction cost: about 7 ms per query for one near-cap pattern (1.3 → 8.4 ms/query on a 20k-row table). It is also paid when the DFA is then discarded as too big (n=12), because RE2 uses the whole budget before giving up.
  • Time scaling: at N=500 the over-cap case costs 560 → 3997 ms with no pruning benefit.

Suggestion: apply a total automaton budget per TextSearchQuery (or per query), and skip building once it is spent. A small cap on the DFA state count would also avoid the ~7 ms wasted before fallback.

Repro: body LIKE 'service%a________<i>' OR'd N times, use_text_index_like_evaluation_by_dictionary_scan=1, optimize_rewrite_like_perfect_affix=0.

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]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Pushed 775f00ec: per-query budget for the dictionary automata.

  • All patterns of one condition share a 4 MiB budget (TextIndexAutomatonBudget). A pattern gets no automaton once it is spent, and uses the regular dictionary scan.
  • A failed or over-cap build is charged the full per-pattern limit, so build time is bounded too.
  • The per-pattern limit goes from 1 MiB to 256 KiB. This makes a failed build about 3× cheaper.
  • New test 05238_text_index_dictionary_dfa_budget (400 ORed patterns under max_memory_usage = 100M). It fails with MEMORY_LIMIT_EXCEEDED (454 MiB) without the fix and passes with it.

Same setup as the previous report (1M tokens, max_threads=1), master / PR before / PR now:

case master before now
500 ORed service%a________<i>: peak mem 17 MB 591 MB 17 MB
same: time 0.55 s 5.8 s 0.57 s
500 ORed service<i>%error: blocks read 776 8 8
service%a________ build cost per query 1.5 ms 9.0 ms 3.4 ms
service%error, service____error 7813 blocks 8 8

Single-pattern pruning is unchanged, and results are identical to the index-off runs. 05238, 05218 and the new test pass. The rest of the text_index stateless suite passes except tests that need part_log, text_log, test clusters, users or test.hits, which my ad-hoc local server doesn't have.

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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 2, 2026
Merged via the queue into ClickHouse:master with commit fd1c83b Nov 2, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
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]>
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... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements 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.

5 participants