Skip to content

Add stringzilla tokenizer using StringZilla UTF-8 decoding - #120973

Closed
phulv94 wants to merge 2 commits into
ClickHouse:masterfrom
phulv94:ascii-cjk-v2-stringzilla-tokenizer
Closed

phulv94 wants to merge 2 commits into
ClickHouse:masterfrom
phulv94:ascii-cjk-v2-stringzilla-tokenizer

Conversation

@phulv94

@phulv94 phulv94 commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #111696

Adds the stringzilla tokenizer for text indexes and the tokens family of functions. It splits text into words with the Unicode Text Segmentation (UAX #29) word boundary rules of the StringZilla library, and drops the segments made of whitespace, punctuation and symbols. StringZilla is already vendored and compiled; this PR only links dbms against it.

A note on the issue: asciiCJK does not use ICU. It is a hand-written scanner that emits every non-ASCII codepoint as its own token, using a single lead-byte lookup, and it cannot be made faster with StringZilla (see the benchmarks below). The ICU-based tokenizer is icu(locale), and that is what this tokenizer offers an alternative to: the same UAX #29 standard, 2-5x faster.

Tokens compared to the existing tokenizers:

Input asciiCJK stringzilla icu('en')
café naïve caf é na ï ve café naïve café naïve
한국어 テキスト one token per character 한국어 テキスト 한국어 テキスト
中文,分词 中 文 , 分 词 中 文 分 词 中文 分词 (dictionary)
1,000,000 1 000 000 1,000,000 1,000,000
emoji 😀 👨‍👩‍👧 emoji 😀 👨 ‍ 👩 ‍ 👧 emoji emoji

Chinese ideographs and Hiragana stay single-character tokens, because UAX #29 does not segment them without a dictionary; chinese, japanese and icu remain the choices for that.

Implementation notes:

  • StringZillaTokenizer has the same shape as AsciiCJKTokenizer and is dispatched in forEachToken through detail::forEachTokenImpl. asciiCJK is not touched.
  • nextInString walks the UAX C++ client #29 segments with StringZilla's batching iterator (64 segments per kernel call, as its Python and Java bindings do), kept per thread like the ICU iterator of IcuTokenizer, because the tokenizer object is shared between threads. The segments tile the input, so the separator segments are skipped: those starting with a delimiter per sz_utf8_delimiters after optional underscores. This covers \r\n, whitespace runs, emoji sequences and _id vs __. Fetching one segment per call instead of batching is ~18x slower.
  • LIKE, startsWith, endsWith, match, multiSearchAny and map*Like are supported. UAX C++ client #29 joins words across punctuation (1,000, foo.bar) but never across whitespace, so a token next to a wildcard, or next to the open side of a substring, is used for index lookups only when whitespace separates them. For LIKE '%,000 rows loaded%' only rows is looked up. The shared wordBoundarySubstring* helpers used by asciiCJK only drop tokens touching the edge, which would miss rows for such patterns, so this tokenizer has its own helper.
  • stringLikeToTokens/stringLikeToBloomFilter tokenize each literal of a pattern once, so pattern analysis is linear in the pattern length, and the text between %, _ and \ is copied in runs found with find_first_symbols.

Performance, Apple Silicon (NEON), 100,000 generated rows, median of 7 runs, seconds:

Workload asciiCJK stringzilla icu('en')
tokens, ASCII 0.055 0.093 0.215
tokens, CJK 0.032 0.266 1.167
tokens, mixed 0.057 0.178 1.149
text index build, mixed 0.166 0.329 1.683

stringzilla is 2.3-5.1x faster than icu, which implements the same UAX #29 rules, and slower than asciiCJK, which looks up no Unicode properties at all. x86 with AVX-512 uses different StringZilla kernels and was not measured locally.

Tests:

  • 05218_stringzilla_tokenizer: tokens and tokensForLikePattern edge cases (scripts, emoji, invalid UTF-8, escapes, long inputs).
  • 05219_stringzilla_text_index: search functions return the same rows with and without the index, EXPLAIN granule skipping, and tokenization that is stable across batch boundaries and thread counts.
  • gtest_StringZillaTokenizer: nextInStringLike and stringLikeToTokens return the same tokens.
  • tests/performance/tokenizer_stringzilla.xml.

Changelog category (leave one):

  • New Feature

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

Added the stringzilla tokenizer for text indexes and the tokens family of functions. It splits text into words by the Unicode (UAX #29) word boundary rules, so words in all scripts are kept whole (e.g. café, 한국어, 1,000,000). It implements the same standard as the icu tokenizer and is 2-5x faster.

🤖 Generated with Claude Code


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

@CLAassistant

CLAassistant commented Sep 19, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@phulv94
phulv94 force-pushed the ascii-cjk-v2-stringzilla-tokenizer branch from b142608 to cf5a90a Compare September 19, 2026 05:01
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Please find a better name for it.

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d822bd8]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, sequential) FAIL
AST Fuzzer oracle mismatch: Identity WHERE (NOT(NOT p)) FAIL cidb
Stress test (arm_msan) FAIL
Logical error: GroupingAggregatedTransform pushed bucket A twice (STID: 3994-4c1d) FAIL cidb
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
number_formatting_formats #1 unstable query history
number_formatting_formats #2 unstable query history
number_formatting_formats #5 unstable query history
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
order_by_read_in_order #1 FAIL dashboard

AI Review

Summary

This PR adds a new stringzilla tokenizer for text indexes and the tokens / tokensForLikePattern helpers, wires it into hasPhrase, and adds focused stateless, gtest, and performance coverage. I did not find a correctness bug in the tokenizer or text-index plumbing, but there are still a couple of public-contract issues in the docs/metadata that should be cleaned up before merge.

PR Metadata

Changelog category is correct: this is a New Feature, and a changelog entry is required. The current entry is specific enough overall, but it overstates the tokenizer's behavior by saying it keeps words "in all scripts" whole even though the implementation still tokenizes Chinese ideographs and Hiragana as single characters. A safer replacement would be:

Added the stringzilla tokenizer for text indexes and the tokens family of functions. It applies Unicode (UAX #29) word boundary rules, keeping words whole in scripts such as Latin and Hangul and preserving numbers such as 1,000,000, and it is 2-5x faster than the icu tokenizer for the same standard.

Findings

⚠️ Majors

  • [src/Functions/tokens.cpp:427] tokensForLikePattern still documents itself as supporting the same argument sets as tokens and even gives splitByString / separators as an example, but buildImpl rejects splitByString, splitByRegexp, array, japanese, chinese, and icu via supportsStringLike(). That leaves the public function contract contradictory: the docs tell users to pass argument combinations that now raise BAD_ARGUMENTS.
    Suggested fix: rewrite description_like to list the actual supported tokenizer set and remove examples of tokenizer-specific arguments that can no longer be used there.

💡 Nits

  • [docs/reference/engines/table-engines/mergetree-family/textindexes.mdx:175] The implementation/docs here explicitly say Chinese ideographs and Hiragana remain single-character tokens, so the changelog entry should not promise that stringzilla keeps words "in all scripts" whole.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Align the tokensForLikePattern public docs with the tokenizer set that the function actually accepts.
  2. Tighten the changelog entry wording so it matches the tokenizer behavior that ships.

LLVM Coverage Report

Measured on commit d822bd8.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 214/219 (97.72%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added 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 labels Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d822bd8930b8c6a5b661d170a7117ce8856425eb was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@phulv94 phulv94 changed the title Add asciiCJK_v2 tokenizer based on StringZilla UAX #29 word segmentation Add splitByWordBoundaries tokenizer based on StringZilla UAX #29 word segmentation Sep 19, 2026
Comment thread src/Functions/tokens.cpp Resolved
Comment thread src/Functions/tokens.cpp Resolved
Comment thread src/Functions/tokens.cpp Outdated
/// argument entries only relevant to those tokenizers, are dropped too.
FunctionDocumentation::Arguments arguments_like = arguments;
arguments_like[arg_tokenizer] = {"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `splitByString`, `asciiCJK`, `ngrams`, `sparseGrams`, and `array`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}};
arguments_like[arg_tokenizer] = {"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `asciiCJK`, `splitByWordBoundaries`, `ngrams`, and `sparseGrams`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}};

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.

The tokenizer argument list on this line is now correct, but the public description_like prose below still says tokensForLikePattern supports the same argument sets as tokens and gives splitByString/separators as an example. In the current code buildImpl throws BAD_ARGUMENTS for splitByString, splitByRegexp, array, and japanese, so the function contract is still contradictory. Please align that prose with the actual supported tokenizer set.

@phulv94
phulv94 force-pushed the ascii-cjk-v2-stringzilla-tokenizer branch from a75cba9 to 39e25f5 Compare September 19, 2026 16:52
@phulv94 phulv94 changed the title Add splitByWordBoundaries tokenizer based on StringZilla UAX #29 word segmentation Add asciiCJK_v2 tokenizer using StringZilla UTF-8 decoding Sep 19, 2026
@phulv94
phulv94 marked this pull request as draft September 19, 2026 17:27
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 20, 2026
@rschu1ze rschu1ze self-assigned this Sep 20, 2026
…rd segmentation

Splits text into words with the Unicode Text Segmentation (UAX ClickHouse#29) word boundary rules of the
StringZilla library and drops the segments made of whitespace, punctuation and symbols. Unlike
`asciiCJK`, words of all scripts are kept whole (`café`, `한국어`, `1,000,000`), and it is 2-5x
faster than the `icu` tokenizer, which implements the same standard.

Closes: ClickHouse#111696

Co-Authored-By: Claude Opus 5 <[email protected]>
@phulv94
phulv94 force-pushed the ascii-cjk-v2-stringzilla-tokenizer branch from 39e25f5 to c091edb Compare September 21, 2026 13:42
@phulv94 phulv94 changed the title Add asciiCJK_v2 tokenizer using StringZilla UTF-8 decoding Add stringzilla tokenizer using StringZilla UTF-8 decoding Sep 21, 2026
…zilla-tokenizer

Adapt to master: `stringzilla` joins the tokenizers whose terms never contain a zero
byte in `tokenizerSplitsAtZeroByte`, the replacement of the removed
`zero_padding_tolerated_tokenizers` list.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
With `match_tokens = true`, note that search needles in text search functions are tokenized with the index's own tokenizer, so a plain string needle that does not itself match `regexp` yields no tokens and therefore no results. Needles passed as arrays to text search functions are not tokenized, and are therefore recommended for use with regexp tokenizers.
- `asciiCJK` splits strings into tokens using Unicode word boundary rules (similar to [Unicode Text Segmentation (UAX #29)](https://unicode.org/reports/tr29/)). ASCII alphanumeric characters and underscores form tokens with connectors (ASCII `:` for letters, `.` and `'` for same-type characters). Non-ASCII Unicode characters, including [CJK](https://en.wikipedia.org/wiki/CJK_characters) characters, become single-character tokens.
- `stringzilla` splits strings into words using the full [Unicode Text Segmentation (UAX #29)](https://unicode.org/reports/tr29/) word boundary rules, as implemented by the [StringZilla](https://github.com/ashvardanian/StringZilla) library, and drops the segments made of whitespace, punctuation and symbols (including emoji).
Unlike `asciiCJK`, words in all scripts are kept whole: for example, `café naïve` becomes `['café', 'naïve']` rather than `['caf', 'é', 'na', 'ï', 've']`, `한국어` and `テキスト` are one token each, and `1,000,000` is one token.

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.

The implementation and docs here make it explicit that Chinese ideographs and Hiragana still tokenize to single characters, so the current changelog entry overstates the feature by saying the tokenizer keeps words "in all scripts" whole. Because the changelog is the user-facing upgrade contract, please narrow that wording to match the shipped behavior instead of promising dictionary-style segmentation for scripts that stringzilla still leaves as single-character tokens.

@rschu1ze

Copy link
Copy Markdown
Member

@phulv94 Before we proceed, we need to understand if the stringzilla tokenizers (we'll also need to rename to something more speaking) produces the same output as the icu tokenizer, i.e. if we can recommend it as a drop-in replacement. Could you please take a look?

@phulv94

phulv94 commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

I ran two comparisons against icu.

1. Unicode UAX #29 conformance

Source: contrib/icu/icu4c/source/test/testdata/WordBreakTest.txt (1944 official cases).

Check Result
Every stringzilla token is an exact UAX #29 segment 1944 / 1944
Every icu token is an exact UAX #29 segment 1944 / 1944
Token lists identical 1548 / 1944 (79.6%)

No case shows a different boundary. All 396 differing cases are about keeping vs
dropping a non-word segment: stringzilla keeps a lone combining mark / ZWJ / soft
hyphen, icu keeps Alphabetic symbols such as Ⓜ.

2. Real text

3.55M lines of the ClickHouse docs (304 MB, multilingual):

Script group Lines Differing %
pure ASCII 2,237,559 18 0.0008%
other non-ASCII (Latin-1, Cyrillic, Greek, Arabic, …) 849,241 778 0.09%
Hangul 152,742 40,134 26.3%
Han/Kana 306,280 293,199 95.7%

All 18 ASCII differences are runs of underscores (__), which icu emits as a token
and this tokenizer skips.

Conclusion

  • For space-separated scripts it is a drop-in replacement for icu, and 2-5x faster.
  • For Han/Kana/Thai it is not. ICU adds dictionary segmentation that UAX C++ client #29 alone
    does not define, so tokens become single characters there (same as asciiCJK); those
    users should stay on icu, chinese or japanese.
  • One more difference worth noting: at a Hangul-Latin/digit boundary (2행, AI에게)
    this tokenizer keeps one token, which is what UAX C++ client #29 rules WB5 and WB9 prescribe,
    while icu inserts a break.

On the name

Agreed, stringzilla names the library rather than the behaviour. I'd suggest
splitByWordBoundaries - happy to take another suggestion.

@rschu1ze

Copy link
Copy Markdown
Member

Thanks for checking.

Every stringzilla token is an exact UAX #29 segment 1944 / 1944
Every icu token is an exact UAX #29 segment 1944 / 1944
Token lists identical 1548 / 1944 (79.6%)

I actually don't understand what these statements mean for the question whether Stringzilla is a drop-in replacement for ICU. But maybe the next point is more important:

  1. Real text

pure ASCII 2,237,559 18 0.0008%
other non-ASCII (Latin-1, Cyrillic, Greek, Arabic, …) 849,241 778 0.09%
Hangul 152,742 40,134 26.3%
Han/Kana 306,280 293,199 95.7%

All 18 ASCII differences are runs of underscores (__), which icu emits as a token and this tokenizer skips.

Conclusion
For space-separated scripts it is a drop-in replacement for icu, and 2-5x faster.

The Conclusion looks inconsistent the measurements, there are differences for non-CJK languages.

My hope was that we could use one as drop-in-replacement for the other so we wouldn't need to introduce yet-another tokenizer. Since Stringzilla is heavily under development, its algorithm may change in future. Also, tokenization performance is not a huge performance problem at the moment. So I suggest to close this PR for now and possibly come back to it later.

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-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index: Add a StringZilla-based tokenizer

4 participants