Skip to content

Add a Chinese 🇨🇳 tokenizer (jieba) for the tokens function and text indexes - #89945

Merged
Ergus merged 74 commits into
ClickHouse:masterfrom
amosbird:add-jieba
Aug 17, 2026
Merged

Ergus merged 74 commits into
ClickHouse:masterfrom
amosbird:add-jieba

Conversation

@amosbird

@amosbird amosbird commented Nov 12, 2025 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • New Feature

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

Added a chinese tokenizer for the tokens function and MergeTree text indexes. It segments Chinese text into words using a dictionary and a Hidden Markov Model (the algorithm follows jieba), with coarse_grained (default) and fine_grained granularities. Continues #80174.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Implementation notes

  • The tokenizer is a from-scratch C++ reimplementation following the fxsjy/jieba algorithm (dictionary-based maximum-probability segmentation with an HMM fallback). The embedded dictionary and HMM model are generated from a pinned cppjieba commit (MIT) and verified by SHA-256; regenerator scripts are included.
  • The engine lives in a standalone repository, https://github.com/ClickHouse/jieba_cpp, consumed here as the contrib/jieba_cpp submodule with a contrib/jieba_cpp-cmake wrapper that builds it against ClickHouse's in-tree abseil/darts-clone/zstd. Built by default (ENABLE_CHINESE_TOKENIZER); the dictionary ships in little- and big-endian variants and is #embed-ed per host byte order, so it works on big-endian targets too.
  • hasToken now bypasses the text index for any non-splitByNonAlpha tokenizer (use hasAnyTokens / hasAllTokens for tokenizer-aware matching). This also fixes a pre-existing case where hasToken over ngrams/array/splitByString/asciiCJK indexes could return wrong rows.

Version info

  • Merged into: 26.8.1.1555 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a828819]

Summary: ✅


AI Review

Summary

This PR adds a chinese tokenizer based on jieba for tokens and MergeTree text indexes, wires it through the tokenizer factory, and adds docs/tests around the new surface. The core integration is close, but the current branch still leaves a real contract gap around tokenizer-aware indexed search, and one of the new function-doc updates still overstates supported tokensForLikePattern argument sets.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:643, tests/queries/0_stateless/04316_chinese_tokenizer_text_index.sql:42, src/Functions/hasAnyAllTokens.cpp:447-461, docs/reference/engines/table-engines/mergetree-family/textindexes.mdx:162-163] The PR now documents hasAnyTokens / hasAllTokens as the supported way to query a chinese text index, but users still cannot get both correct chinese semantics and index acceleration from those functions. The explicit 3-argument form never reaches the text-index analyzer because traverseAtomNode rejects text-search functions with more than 2 arguments, so the "correct" hasAllTokens(..., ..., 'chinese') workaround is scan-only. The 2-argument form can use the index, but when execution falls back to the scalar function it still defaults to splitByNonAlpha, so the same query can change result on use_skip_indexes = 0, unmaterialized parts, or any other non-indexed path. Suggested fix: either teach MergeTreeIndexConditionText to accept a matching explicit tokenizer for hasAnyTokens / hasAllTokens, or document everywhere this is recommended that the explicit form is scan-only and the 2-argument form is only tokenizer-aware on the rewritten index path.
  • [src/Functions/tokens.cpp:388] The new tokensForLikePattern documentation is still narrower than the actual contract. tokensForLikePattern rejects every tokenizer whose implementation does not opt into LIKE tokenization via supportsStringLike(), which currently includes at least splitByString, array, chinese, icu, and japanese. The new wording says only chinese and icu are unsupported, so it now advertises argument sets that still throw BAD_ARGUMENTS at runtime. Suggested fix: either list the supported set explicitly (splitByNonAlpha, asciiCJK, ngrams, sparseGrams) or describe support in terms of supportsStringLike() instead of singling out only two unsupported tokenizers.
Final Verdict

Needs changes before merge: the new tokenizer itself is mostly in place, but the current docs/tests still promise tokenizer-aware indexed behavior that the implementation does not provide.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 122/131 (93.13%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR. labels Nov 12, 2025
@alexey-milovidov

Copy link
Copy Markdown
Member

This sounds great! How big is it?

@amosbird

Copy link
Copy Markdown
Collaborator Author

How big is it?

It’s about 8 MiB uncompressed.

alexey-milovidov and others added 5 commits May 9, 2026 17:53
…TokenizerFactory architecture

After master refactored 'ITokenExtractor' into 'ITokenizer' with a 'TokenizerFactory'
(commit db800d0 and surrounding work), the original PR's direct enum-based dispatch
in 'createTokenizer' is no longer applicable. This merge ports the Chinese tokenizer to
the new architecture:

- Renamed jieba singleton 'DB::ChineseTokenizer' to 'DB::JiebaSegmenter' so the polymorphic
  tokenizer class can take the more natural 'ChineseTokenizer' name (matching master's
  '<Name>Tokenizer' convention).
- Added 'ChineseTokenizer' (subclass of 'ITokenizerHelper') to 'ITokenizer.h' / 'ITokenizer.cpp',
  with a dispatch case in 'forEachToken' that calls 'JiebaSegmenter::instance().tokenize'.
- Registered the 'chinese' tokenizer in 'TokenizerFactory' with a 'String' granularity
  argument ('coarse_grained' default, 'fine_grained' optional).
- Extended 'tokens.cpp' to forward 'String' arguments to the factory so
  'tokens(value, 'chinese', 'fine_grained')' works.
- Deleted obsolete 'src/Interpreters/ITokenExtractor.cpp' / '.h' (superseded by master).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Earlier the cache key used (data, length) which would silently return stale
tokens if the caller reused the same buffer. Use 'pos == 0' (the canonical
'fresh iteration' marker used by the helper's loops) to trigger
re-tokenization, and keep 'pos' synthesized in (0, length] so the
loop guard 'cur < length' stays true while tokens remain — the actual
token offsets returned by jieba can overlap and don't form a left-to-right
scan.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…state

'IColumn::getDataAt' returns 'std::string_view' on master (after the
'StringRef.h' removal), so '.toString()' no longer compiles. Construct a
'String' from the view directly. Also drop two now-unused members from
'ChineseTokenizer' that were left behind after switching to the
'pos == 0' iteration-restart marker.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread contrib/jieba/jieba_common.h Resolved
Comment thread contrib/jieba/jieba_dict.cpp Resolved
Comment thread contrib/jieba/jieba_dict.cpp Resolved
alexey-milovidov and others added 2 commits May 9, 2026 23:46
Replace the two ~7.6 MiB embedded raw dictionaries (`dict_le.dat`,
`dict_be.dat`) with a single zstd-compressed `dict_le.dat.zst` (~3.5 MiB),
decompressed at startup into an 8-byte aligned heap buffer. ClickHouse
only targets little-endian platforms, so the big-endian artifact and the
runtime byte-order branch are removed.

This keeps the in-tree footprint under the 5 MiB limit enforced by
`ci/jobs/scripts/check_style/various_checks.sh` while leaving the data
self-contained — no external download at build time.

Also fixes the unaligned reinterpret_cast UB flagged by AI review:
the on-disk header is now read via `memcpy`, and the buffer's natural
alignment lets the weights array (offset 24) and trie (offset 24 +
8 * num_elems) be accessed at their required alignment.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`generate_dict.py` builds dictionary keys by encoding each word as
UTF-16-LE and replacing every 0x00 byte with 0xF0 (darts-clone cannot
handle 0x00 inside keys). The runtime in `decodeUTF8Rune` only
remapped ASCII-range runes (where the high byte is 0x00), so any BMP
codepoint whose low byte is 0x00 — e.g. `U+4E00` (一), `U+5000`,
`U+6700`, `U+8000` — would be encoded as `00 NN` in memory and miss
the trie key `F0 NN`.

Replace the narrow `if (rune <= 0xFF)` remap with a general
"if either byte of the UTF-16-LE encoding is 0x00, set it to 0xF0"
rule, matching exactly what the dictionary generator does. The
common ASCII path is unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@amosbird
amosbird requested a review from a team as a code owner August 3, 2026 11:55
@amosbird
amosbird force-pushed the add-jieba branch 4 times, most recently from 2eacc75 to f88c00a Compare August 4, 2026 02:03
Only the ICU-specific implementation bodies (ICU API calls, anonymous-namespace
helpers, pragma diagnostic) need USE_ICU guards — matching the upstream pattern.
The IcuTokenizer struct, enum value, and method declarations are intentionally
unguarded because ICU is always available in ClickHouse builds (it is not gated
by ENABLE_LIBRARIES).
{"input", "The input column.", {"String", "FixedString", "Nullable(String)", "Nullable(FixedString)", "Array(String)", "Array(FixedString)", "Array(Nullable(String))", "Array(Nullable(FixedString))"}},
{"needles", "Tokens to be searched.", {"String", "Array(String)"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `splitByString`, `asciiCJK`, `icu('<locale>')`, `japanese`, `ngrams`, `sparseGrams`, and `array`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `splitByString`, `asciiCJK`, `chinese`, `icu('<locale>')`, `japanese`, `ngrams`, `sparseGrams`, and `array`. 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.

Adding chinese to the valid tokenizer list here makes a broader behavior gap user-visible in the function docs: the prose above still describes only the preprocessor-driven divergence, but the scalar fallback itself is still splitByNonAlpha unless the caller passes the 3rd argument.

Concretely, FunctionHasAnyAllTokensOverloadResolver::buildImpl defaults to splitByNonAlpha, so on a chinese('fine_grained') text index hasAllTokens(doc, ['大学']) is true when the predicate is answered via the text index, but false for SETTINGS use_skip_indexes = 0 or an unmaterialized part. After advertising chinese here, readers of the function docs will hit the same wrong-result pitfall even if they never read textindexes.md.

Please either make the fallback inherit the index tokenizer, or document this omission-of-the-3rd-argument caveat in both hasAnyTokens and hasAllTokens instead of only warning about preprocessors.

@Ergus

Ergus commented Aug 4, 2026

Copy link
Copy Markdown
Member

Hi @amosbird

I just merged master because there was a big conflict in the documentations.

Comment thread src/Functions/tokens.cpp
arguments after `tokenizer` are interpreted according to the selected
tokenizer (for example, `n` for `ngrams`, `separators` for `splitByString`,
and `min_length` / `max_length` [/ `min_cutoff_length`] for `sparseGrams`).
It supports the same argument sets as the `tokens` function, with some

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 new wording here is still narrower than the actual contract. tokensForLikePattern does not only reject chinese and icu: it rejects every tokenizer whose implementation does not opt into LIKE tokenization via supportsStringLike(). In the current tree that also includes splitByString, array, and japanese, and the existing stateless test already expects BAD_ARGUMENTS for at least splitByString and array (03403_function_tokens_for_like_pattern).

As written, the function docs now tell users that those argument sets are supported when they still throw at runtime. Could we either list the actual supported set (splitByNonAlpha, asciiCJK, ngrams, sparseGrams) or phrase this section in terms of supportsStringLike() without singling out only two unsupported tokenizers?

@amosbird

amosbird commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

@Ergus It looks like there are still more merge conflicts coming...

Comment thread contrib/Jieba-CPP Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a828819ea with master c3b0aa7b2 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.29 MiB 695.07 MiB +2.77 MiB (+0.40%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

11 object files changed (+6.36 MiB total), 5 added.

Object file Master PR Δ
contrib/Jieba-CPP-cmake/CMakeFiles/_jieba.dir/__/Jieba-CPP/src/jieba_dict.cpp.o new 3.76 MiB +3.76 MiB
contrib/Jieba-CPP-cmake/CMakeFiles/_jieba.dir/__/Jieba-CPP/src/jieba_hmm_seg.cpp.o new 2.46 MiB +2.46 MiB
contrib/Jieba-CPP-cmake/CMakeFiles/_jieba.dir/__/Jieba-CPP/src/jieba.cpp.o new 38.81 KiB +38.81 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasAnyAllTokens.cpp.o 870.82 KiB 902.09 KiB +31.27 KiB (+3.59%)
contrib/Jieba-CPP-cmake/CMakeFiles/_jieba.dir/__/Jieba-CPP/src/jieba_mp_seg.cpp.o new 17.15 KiB +17.15 KiB

737 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

26 translation units recompiled, 123 s compile time in total, 20 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +7.0 s (+7%) in total before that adjustment.

Translation units without a recent master baseline:

  • contrib/Jieba-CPP-cmake/__/Jieba-CPP/src/jieba_hmm_seg.cpp: 5.5 s

Job report

@Ergus
Ergus added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 3ba15fa Aug 17, 2026
181 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@rschu1ze rschu1ze changed the title Add a Chinese tokenizer (jieba) for the tokens function and text indexes Add a Chinese 🇨🇳 tokenizer (jieba) for the tokens function and text indexes Aug 17, 2026
LyJacky pushed a commit to LyJacky/ClickHouse that referenced this pull request Sep 28, 2026
When a test outlives its timeout, the `proc.wait` in `run_single_test`
raises `TimeoutExpired` and leaves `returncode` unset, and
`process_result_impl` then kills the test's process group. If the test
finishes in between, its leader has exited but nothing has reaped it yet,
and macOS hides such a process (xnu-12377.1.9): `proc_exit` sets
`P_REF_DEAD` ("will not be visible via proc_find", bsd/kern/kern_exit.c),
so `getpgid` returns ESRCH (bsd/kern/kern_prot.c), and `killpg1` skips
`SZOMB` members of a process group and returns EPERM to a POSIX caller when
it found no other member (bsd/kern/kern_sig.c). Linux still reports the
pgid of such a process and signals a group of them without an error.

So on `Fast test (arm_darwin)` a test that exits at its deadline was
reported as `Test internal error` instead of `Timeout!`, and its group was
not killed: `ProcessLookupError` from `os.getpgid(proc.pid)` in
`process_result_impl` (05055_strict_resize_associated_output, ClickHouse#117779), and
`PermissionError` from `os.killpg(pgid, signal.SIGTSTP)` and from
`os.killpg(pgid, signal.SIGTERM)` in `kill_process_group`
(01674_executable_dictionary_implicit_key and 01474_executable_dictionary,
ClickHouse#89945).

Pass `proc.pid` as the process group id. The test is started with
`start_new_session=True`, so its leader is a session leader whose pgid is
its pid and cannot change, and the pid stays taken until the leader is
reaped. This also lets the kill reach members that outlived an exited
leader.

Let `kill_process_group` ignore EPERM like ESRCH for every signal it
sends, not only for SIGKILL: the runner's children run under its uid, which
XNU always lets it signal, so EPERM there means that no member is left to
signal. The SIGKILL-only handler that already did this for the same macOS
behaviour is folded into the common one.

The new test loads the runner as a module, answers `getpgid` and `killpg`
the way macOS does for such a group, and checks that the test is reported
as a timeout with its group signalled, with and without
`--capture-client-stacktrace`.

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 hold Skip for auto-updating. pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants