Repository navigation
Add a Chinese 🇨🇳 tokenizer (jieba) for the tokens function and text indexes - #89945
Conversation
This reverts commit 5259e25.
|
Workflow [PR], commit [a828819] Summary: ✅
AI ReviewSummaryThis PR adds a Findings
Final VerdictNeeds 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
Changed lines: Changed C/C++ lines covered: 122/131 (93.13%) · Uncovered code |
|
This sounds great! How big is it? |
It’s about 8 MiB uncompressed. |
…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]>
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]>
2eacc75 to
f88c00a
Compare
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"}}, |
There was a problem hiding this comment.
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.
|
Hi @amosbird I just merged master because there was a big conflict in the documentations. |
| 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 |
There was a problem hiding this comment.
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?
|
@Ergus It looks like there are still more merge conflicts coming... |
Build profile diff (arm_release)Comparing Binary sizes
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
|
| 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
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a
chinesetokenizer for thetokensfunction andMergeTreetext indexes. It segments Chinese text into words using a dictionary and a Hidden Markov Model (the algorithm follows jieba), withcoarse_grained(default) andfine_grainedgranularities. Continues #80174.Documentation entry for user-facing changes
Implementation notes
contrib/jieba_cppsubmodule with acontrib/jieba_cpp-cmakewrapper 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.hasTokennow bypasses the text index for any non-splitByNonAlphatokenizer (usehasAnyTokens/hasAllTokensfor tokenizer-aware matching). This also fixes a pre-existing case wherehasTokenoverngrams/array/splitByString/asciiCJKindexes could return wrong rows.Version info
26.8.1.1555(included in26.8and later)