Skip to content

Add the regexpMasked tokenizer for text indexes - #131868

Open
CurtizJ wants to merge 6 commits into
ClickHouse:masterfrom
CurtizJ:tokenizer-regex-masked
Open

CurtizJ wants to merge 6 commits into
ClickHouse:masterfrom
CurtizJ:tokenizer-regex-masked

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

A new tokenizer for text indexes on log messages. regexpMasked produces the tokens of a base tokenizer (splitByNonAlpha by default, or splitByString), but every match of a mask, a regular expression for a kind of value, becomes a single token. So 10.0.0.1, 2026-11-05 10:15:30.123+00:00, 97a133f8-4d41-4e4f-b869-db7c48b6da4c, 1.5GB or var/lib/clickhouse/x.bin are indexed and searched as one token each, instead of being split into many short and unselective ones.

INDEX idx message TYPE text(tokenizer = regexpMasked)
INDEX idx message TYPE text(tokenizer = regexpMasked(splitByNonAlpha, masks = ['ip', 'uuid'], custom_masks = ['sess_[0-9a-f]{16}']))

SELECT tokens('took 1.5GB from 10.0.0.1:9000', 'regexpMasked');  -- ['took','1.5GB','from','10.0.0.1','9000']

Semantics

  • Built-in masks, selected by name with masks = [...] (all by default): timestamp (ISO 8601, access log, syslog), ip (IPv4, IPv6), uuid, hex, number, path, url. custom_masks = [...] adds RE2 patterns. All masks are case-insensitive.
  • Masks are tried only at the start of a base token. The longest match wins and is extended to the next separator. Without a match, the base token is emitted.
  • Consequences, each covered by tests: tokens are never adjacent (the text between two tokens is whole separators), the tokens of a piece of text cut at token boundaries do not depend on the surrounding text, and masks = [] gives exactly the base tokenizer's tokens.
  • Custom masks are validated: no anchors or word-boundary assertions, no empty match, at most 64 masks of at most 1024 bytes.
  • The description is canonical (built-in masks in fixed order, custom masks sorted and deduplicated), so equivalent definitions match the index in hasAllTokens(col, needle, '<tokenizer>').

Performance

Single thread, tokens over 372 MB of the log lines from tests/performance/tokenizers.xml (shared machine, about ±10%):

  • splitByNonAlpha: ~650 MB/s
  • regexpMasked(masks = []): ~690 MB/s (delegates to the base tokenizer)
  • regexpMasked with all built-in masks: ~120 MB/s

Building a text index on 500k rows takes about 33% longer than with splitByNonAlpha. New queries are added to tokenizers.xml and text_index_build_tokenizers.xml.

Changelog category (leave one):

  • New Feature

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

Added the regexpMasked tokenizer for text indexes and token search functions. It splits text like splitByNonAlpha or splitByString, but keeps values matched by masks, such as IP addresses, UUIDs, timestamps, numbers, paths and URLs, as single tokens. Built-in masks are selected with masks = [...], and additional masks can be given as regular expressions with custom_masks = [...].

🤖 Generated with Claude Code


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

`regexpMasked(base, masks = [...], custom_masks = [...])` produces the tokens of
a base tokenizer (`splitByNonAlpha` or `splitByString`), with every match of a
mask merged into one token. Built-in masks: `timestamp`, `ip`, `uuid`, `hex`,
`number`, `path`, `url`; custom masks are RE2 patterns. Masks are tried only at
base-token starts, the longest match wins and is extended to the next
separator, so tokens never touch and do not depend on the surrounding text.

- `TokenizerFactory`: tokenizers can be registered with a creator that receives
  the argument ASTs, for nested tokenizers and `name = value` arguments.
- `TokenMasks`: built-in masks (Latin-1, ASCII case folding) with first-byte
  tables, prechecks and exact hand-written matchers for `number`, `path` and
  `url` (which also keep a scan linear); custom masks compiled into one
  longest-match alternation, validated (no anchors, no empty match, limits).
- `RegexpMaskedTokenizer::forEachSpan` reports token offsets and whether a
  token is masked, for reuse by the `Log` type; it needs no padding.
- Supported in `text` indexes, `tokens`, `hasAnyTokens`, `hasAllTokens` and
  `hasPhrase`; documented in `textindexes.mdx`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit fdec62c.

Approve preview

@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fdec62c]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

PR #131868 adds regexpMasked tokenization for text indexes and token search functions, with built-in and custom masks. Reviewed commit fdec62c208632203153e192959742001ae941405, including all prior discussion. Both previously reported quadratic scanning issues are fixed. One benchmark setup issue still needs correction.

Findings

⚠️ Majors

  • tests/performance/text_index_build_tokenizers.xml:13: The new CREATE TABLE statements require regexpMasked on the reference server, where it does not exist. Consequently, perf.py aborts the entire benchmark during setup, losing measurements for both the existing and new cases. The current CI performance report confirms Unknown tokenizer: 'regexpMasked'. Add do_not_check_in_pr="131868" to the feature-dependent setup statements, following tests/performance/README.md.
Final Verdict

⚠️ Request changes — Correct the benchmark setup and rerun the performance comparison so the index-build measurements execute.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... labels Nov 15, 2026
Comment thread src/Interpreters/ITokenizer.cpp Resolved
CurtizJ and others added 2 commits November 15, 2026 21:21
The inherited `stringToTokens` and `stringToBloomFilter` call `nextInString`
once per token, and each call starts a new `forEachSpan` with an empty
`TokenMasks::ScanState`. That lost the failed-match positions which keep the
`path` and `url` matchers linear, so a needle such as `repeat('a.', 100000)`
in `hasAllTokens`, `hasAnyTokens`, `hasPhrase` or a text index condition was
tokenized in quadratic time. Both methods now collect the tokens in one
`forEachSpan` pass. The linear-time gtest and the stateless test cover these
entry points.

Review: ClickHouse#131868 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `re2::Regexp::Walker` leaves `max_visits_` uninitialized until `Walk`, which
  `clang-analyzer-optin.cplusplus.UninitializedObject` reports for the derived
  `FirstBytesWalker` constructor: suppressed with a reason.
- Escaped string literals rewritten as raw string literals.
- The fixed seeds of the test's random generators are intentional
  (deterministic test data): suppressed with a reason.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131868&sha=7802dfe132254ede3971abf4901cd9e40b5bfd27&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29
PR: ClickHouse#131868

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/TokenMasks.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fdec62c20 with master 68d5b2e0a (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

13 object files changed (+544.46 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/TokenMasks.cpp.o new 185.23 KiB +185.23 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasAnyAllTokens.cpp.o 1.06 MiB 1.17 MiB +103.53 KiB (+9.50%)
src/CMakeFiles/dbms.dir/Interpreters/TokenizerFactory.cpp.o 179.68 KiB 240.96 KiB +61.28 KiB (+34.11%)
src/CMakeFiles/dbms.dir/Interpreters/ITokenizer.cpp.o 349.92 KiB 405.11 KiB +55.19 KiB (+15.77%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasPhrase.cpp.o 642.58 KiB 696.73 KiB +54.15 KiB (+8.43%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/tokens.cpp.o 634.79 KiB 671.51 KiB +36.72 KiB (+5.79%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/ngrams.cpp.o 315.22 KiB 348.99 KiB +33.77 KiB (+10.71%)

711 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

25 translation units recompiled, 180 s compile time in total, 24 of them have a recent master baseline.

Job report

CurtizJ and others added 3 commits November 16, 2026 12:48
With a `splitByString` base whose separators are hexadecimal digits, such as
`regexpMasked(splitByString(['a']))` on `repeat('bbbbbbbba', n)`, every base
token started a `[0-9a-f]{8,}` match over the rest of the run, which was then
rejected for lacking a decimal digit, so tokenizing was quadratic. The `hex`
pattern now has an exact hand-written matcher: the match is the whole run of
hexadecimal digits, and a rejected run is recorded in `TokenMasks::ScanState`,
because every later start within it is rejected too. `LinearTime` and the
stateless test cover such a base.

Review: ClickHouse#131868 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…asked

# Conflicts:
#	src/Interpreters/TokenizerFactory.h
Master enabled the `modernize-use-nodiscard` clang-tidy check in 7fbc444.
Mark the `const` member functions added by this PR in `RegexpMaskedTokenizer`,
`SplitByStringTokenizer` and `TokenMasks` accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@CurtizJ
CurtizJ marked this pull request as ready for review November 16, 2026 13:21
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review approves this commit, see the AI Review comment.

<create_query>CREATE TABLE tib_log_non_alpha (s String, INDEX idx s TYPE text(tokenizer = splitByNonAlpha)) ENGINE = MergeTree ORDER BY tuple()</create_query>
<create_query>CREATE TABLE tib_log_by_string (s String, INDEX idx s TYPE text(tokenizer = splitByString([' ', '=', ',', '"']))) ENGINE = MergeTree ORDER BY tuple()</create_query>
<create_query>CREATE TABLE tib_log_by_string_multi (s String, INDEX idx s TYPE text(tokenizer = splitByString([', ', '="', ' ', '=']))) ENGINE = MergeTree ORDER BY tuple()</create_query>
<create_query>CREATE TABLE tib_log_regexp_masked (s String, INDEX idx s TYPE text(tokenizer = regexpMasked)) ENGINE = MergeTree ORDER BY tuple()</create_query>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major] Handle the new tokenizer in reference-server benchmark setup

The reference server does not have regexpMasked, but perf.py runs these new setup statements on both servers. Without a setup opt-out, the first CREATE TABLE raises BAD_ARGUMENTS with Unknown tokenizer: 'regexpMasked', and do_create aborts the entire text_index_build_tokenizers test before any timed queries run, including the existing tokenizer benchmarks. This is already the run error in the current performance report.

Please add do_not_check_in_pr="131868" to the new feature-dependent setup statements, as documented in tests/performance/README.md, and rerun the comparison. The harness will then measure the test on the new server and classify it as backward-incompatible instead of failing during setup.

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 16, 2026 15:21

AI review of a later commit does not approve the PR, see the AI Review comment.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant