Skip to content

Segmentation tokenizer for text index - #104281

Open
scanhex12 wants to merge 3 commits into
ClickHouse:masterfrom
scanhex12:segmentation_tokenizer
Open

scanhex12 wants to merge 3 commits into
ClickHouse:masterfrom
scanhex12:segmentation_tokenizer

Conversation

@scanhex12

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

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

Segmentation tokenizer for text index. This closes #103743

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b2737c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, flaky check) FAIL
MemorySanitizer: use-of-uninitialized-value (STID: 1003-326e) FAIL cidb
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) FAIL
MemorySanitizer: use-of-uninitialized-value (STID: 1003-326e) FAIL cidb
Stress test (amd_msan) FAIL
MemorySanitizer: use-of-uninitialized-value (STID: 1003-358c) FAIL cidb
Stress test (arm_msan) FAIL
MemorySanitizer: use-of-uninitialized-value (STID: 1003-358c) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/feature_docs.py FAIL

AI Review

Summary

This PR adds a new segmentation tokenizer for text index and coverage tests for IPv4/IPv6/MAC/UUID/URI/timestamp inputs. The implementation still has multiple correctness and safety regressions in token extraction and state handling that can produce false-negative pruning or undefined behavior, so it is not ready to merge.

Findings

❌ Blockers

  • [src/Interpreters/ITokenizer.cpp:494] SegmentationTokenizer::buildStateIfNeeded reads data[i] when i == length via isMajorSplitChar(data[i]), which is out-of-bounds and makes tokenization depend on accidental buffer padding.
    Suggested fix: guard with i < length before any data[i] access in the end-of-input branch.
  • [src/Interpreters/ITokenizer.cpp:532] LIKE token extraction can emit boundary-partial minor-segment tokens that are not guaranteed to exist in matching rows (e.g. LIKE '%23.4%' vs row 123.45), causing false-negative text-index pruning.
    Suggested fix: emit only tokens guaranteed for every match (drop boundary-partial segments, or emit no pruning token in ambiguous cases).
  • [src/Interpreters/ITokenizer.cpp:588] substringToTokens ignores is_prefix/is_suffix, so startsWith/endsWith paths can emit unsafe boundary-partial tokens (e.g. startsWith(col, '192.1') emits 192.1 while row 192.168 has tokens 192, 192.168, 168), again causing false-negative pruning.
    Suggested fix: honor prefix/suffix boundary flags and remove unsafe boundary-partial segments before token generation.
  • [src/Interpreters/ITokenizer.h:410] SegmentationTokenizer is stateful (mutable cursor/cache fields), but multi-threaded function execution only clones sparseGrams. Using segmentation with hasAnyTokens/hasAllTokens can race on shared mutable state and produce nondeterministic results.
    Suggested fix: either make tokenizer stateless per call, or extend the existing clone workaround for mutable tokenizers to include Type::Segmentation.

⚠️ Majors

  • [src/Interpreters/TokenizerFactory.cpp:285] segmentation_creator ignores args, so segmentation(...) silently accepts arbitrary parameters instead of rejecting invalid arity, unlike other tokenizers.
    Suggested fix: add assertParamsCount(args.size(), 0, SegmentationTokenizer::getExternalName()).
Tests
  • ⚠️ Add regression coverage for unsafe substring/LIKE boundary cases (e.g. LIKE '%23.4%' on 123.45, startsWith('192.168', '192.1')) to guarantee no false-negative pruning.
  • ⚠️ Add concurrency coverage for hasAnyTokens/hasAllTokens with tokenizer segmentation to prove deterministic results under parallel execution.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Fix the out-of-bounds read in buildStateIfNeeded.
  2. Fix unsafe boundary token generation in nextInStringLike and substringToTokens (respect prefix/suffix semantics and avoid boundary-partial pruning tokens).
  3. Fix mutable-state thread-safety for segmentation in multi-threaded tokenization paths.
  4. Enforce zero-argument validation for segmentation in TokenizerFactory.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 7, 2026
factory.registerTokenizer(AsciiCJKTokenizer::getName(), ITokenizer::Type::AsciiCJK, ascii_cjk_creator);
factory.registerTokenizer("unicodeWord", ITokenizer::Type::AsciiCJK, ascii_cjk_creator);

auto segmentation_creator = [](const FieldVector & /*args*/) -> std::unique_ptr<ITokenizer>

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.

⚠️ This creator ignores arguments entirely. Unlike other tokenizers, segmentation(...) currently accepts any parameter list silently.

That makes typoed settings look valid and changes behavior without an explicit error. Please add assertParamsCount(args.size(), 0, SegmentationTokenizer::getExternalName()) here for consistent validation.

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.

Re-checking current head (76a6efca) this is still live: segmentation_creator still ignores args, so segmentation(...) accepts arbitrary parameters silently while other tokenizers validate arity.

Please add assertParamsCount(args.size(), 0, SegmentationTokenizer::getExternalName()) in this creator.

Comment thread src/Interpreters/ITokenizer.cpp Resolved
@alexbakharew alexbakharew self-assigned this May 13, 2026
Comment thread src/Interpreters/ITokenizer.h Resolved
@scanhex12
scanhex12 force-pushed the segmentation_tokenizer branch from 1d89fb6 to 76a6efc Compare May 18, 2026 16:43
@scanhex12
scanhex12 requested a review from UnamedRus May 18, 2026 16:49
major_part_index.push_back(cur_major_part_index);
}
part_begin = i + 1;
if (isMajorSplitChar(data[i]))

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.

❌ buildStateIfNeeded reads data[i] when i == length.

The outer condition uses i <= length, and inside this block we call isMajorSplitChar(data[i]) unconditionally. At i == length this dereferences one byte past the provided buffer, so tokenization depends on accidental padding/null-termination.

Please guard the increment with if (i < length && isMajorSplitChar(data[i])) (or split the end-of-input path) so the tokenizer never reads past length.

while (pos < length)
{
const char c = data[pos];
if (!escaped && (c == '%' || c == '_'))

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.

❌ This LIKE token extraction can create false negatives for matches that start/end inside a minor segment.

Concrete case:

  • row value: 123.45 (row tokens are 123, 123.45, 45)
  • predicate: LIKE '%23.4%'
  • this code emits token 23.4

23.4 is not present in row tokens, so the text index can prune a granule that actually contains a matching row. For LIKE/substring predicates we must only emit tokens guaranteed to exist in every real match; boundary-partial segments should be dropped (or the pattern should produce no token for pruning).

}


mutable std::vector<size_t> minor_part_starts;

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.

❌ SegmentationTokenizer keeps mutable cursor/cache state (previous_data, current_part_i, current_part_j, and the cached parts vectors), so one instance is not thread-safe.

hasAnyTokens/hasAllTokens currently clone only sparseGrams before multi-threaded execution (src/Functions/hasAnyAllTokens.cpp). With this tokenizer now registered globally, hasAnyTokens(..., 'segmentation') can race on shared mutable state and return nondeterministic results.

Please either make this tokenizer stateless per call, or extend the cloning workaround to include Type::Segmentation.

stringToBloomFilter(data, length, bloom_filter);
}

void SegmentationTokenizer::substringToTokens(const char * data, size_t length, std::vector<String> & tokens, bool /*is_prefix*/, bool /*is_suffix*/) const

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.

❌ substringToTokens ignores is_prefix / is_suffix and always tokenizes the full substring. That can emit boundary-partial tokens that are not guaranteed to exist in matching rows, which leads to false-negative index pruning.

Concrete case:

  • row value: 192.168
  • predicate: startsWith(col, '192.1')
  • this path can emit 192.1, but row tokens are 192, 192.168, 168

Because startsWith uses substringToTokens(..., true, false), trailing boundary-partial segments should be dropped (and similarly leading ones for suffix mode) before generating pruning tokens.

@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 86.55% (103/119) · Uncovered code

Full report · Diff report

@rschu1ze rschu1ze assigned Ergus and unassigned alexbakharew May 19, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Allow me to ask @Ergus (instead of @alexbakharew) for a review as he was working on full-text search for a longer while.

@Ergus

Ergus commented May 19, 2026

Copy link
Copy Markdown
Member

Hi @scanhex12

I just added this PR to my TODO list ;). To start with I would request to add some documentation for this new tokenizer in order to understand better how it works and when it is useful for (the last part I saw in the opened issue, but we need to put it all together)

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 10, 2026
`CoalescingMergeTree` delegates to `SummingSortedAlgorithm` with
`aggregate_all_columns = true`. The dedicated branch for that case in
`defineColumns` (`src/Processors/Merges/Algorithms/SummingSortedAlgorithm.cpp:267`)
wrapped its work in `if (map_name == column.name || !endsWith(map_name, "Map"))`
and then fell through to an unconditional `continue`. For any nested column
whose parent table name ends with `Map` (e.g. `testMap.key`,
`legacy_features_Map.id`), the inner branch was skipped while the `continue`
still fired, so the column was added to neither `columns_to_aggregate` nor
`column_numbers_not_to_aggregate`.

`postprocessChunk` then constructed `res_columns` of size `num_result_columns`
and left those slots `nullptr`. `Chunk::setColumns` -> `Chunk::checkNumRowsIsConsistent`
dereferenced the null `ColumnPtr`, producing a SIGSEGV in release builds, a
`px != 0` assertion in debug builds, and an UBSan `member call on null pointer`
report in `arm_asan_ubsan` (STID 1003-326e on the AST fuzzer for PR ClickHouse#104281 and
PR ClickHouse#104563).

CoalescingMergeTree performs per-column `last_value` coalescing, so nested
`Map` arrays must be coalesced element-wise like any other array column. The
legacy `nestedName.suffix` routing into `discovered_maps` for `sumMap`-by-key
merging is a SummingMergeTree concept that does not apply here, so the
Map-suffix exclusion is dropped from the `aggregate_all_columns = true` branch.
SummingMergeTree code paths are untouched.

Closes ClickHouse#101937
CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/104563/c2e0f0fe3b92d48b5a47fa90555f7d4aca54c553/ast_fuzzer_arm_asan_ubsan/

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@rschu1ze

Copy link
Copy Markdown
Member

@scanhex12 #104281 (comment) ^^

@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, 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.

@Ergus Ergus self-assigned this Jun 18, 2026
@Ergus

Ergus commented Jun 22, 2026

Copy link
Copy Markdown
Member

Hi @scanhex12

Are we continuing with this?

@Ergus Ergus 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.

I am looking into this again and I have a main issue with this as implemented (or intended)

From the original description in the feature request I see that:

192.168.1.106 -> [192, 168, 1, 106, 192.168, 168.1, 1.106, 192.168.1, 168.1.106, 192.168.1.106]

IIUC correctly that is the combination that grows with the number of sub-tokens with a quadratic complexity: N*(N+1)/2

An IPV6 address will produce 36 entries in the dictionary...

In this case the index size increase could affect the overall performance more than just getting some false positive in granules exclusion.

What if we rethink the approach a little bit now that we have the positions experimental feature? With position information we won't need to store all the combinations to get correct full filtering.

The trade off is that positions already increase the index size significantly and is disabled by default.

@rschu1ze WDYT?

@UnamedRus

Copy link
Copy Markdown
Contributor

I don't think that it that much worse, than other already existing tokenizers which we can use in text indexes

SELECT
    ngrams('192.168.1.106', 3),
    ngrams('2001:db8:85a3::8a2e:370:7334', 3) AS ip,
    sparseGrams('2001:db8:85a3::8a2e:370:7334') AS ip2,
    length(ip),
    length(ip2)
FORMAT Vertical

Query id: ee800a00-76ea-4d4c-ac12-1186182e974a

Row 1:
──────
ngrams('192.168.1.106', 3): ['192','92.','2.1','.16','168','68.','8.1','.1.','1.1','.10','106']
ip:                         ['200','001','01:','1:d',':db','db8','b8:','8:8',':85','85a','5a3','a3:','3::','::8',':8a','8a2','a2e','2e:','e:3',':37','370','70:','0:7',':73','733','334']
ip2:                        ['200','001','01:','1:d','01:d',':db','db8',':db8','01:db8','b8:','8:8','b8:8',':85','85a','5a3','85a3',':85a3','b8:85a3','01:db8:85a3','001:db8:85a3','a3:','3::','::8',':8a','8a2',':8a2','::8a2','3::8a2','a3::8a2','001:db8:85a3::8a2','a2e','2e:','a2e:','e:3',':37','370',':370','70:',':370:','0:7',':73','0:73',':370:73','733',':370:733','e:370:733','a2e:370:733','334','a2e:370:7334']
length(ip):                 26
length(ip2):                49


std::vector<String> SegmentationTokenizer::compactTokens(const std::vector<String> & tokens) const
{
std::unordered_set<String> result;

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.

This has changed on master to use the memory tracking API

const size_t n_parts = minor_part_starts.size();

if (current_part_i >= n_parts)
return false;

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.

IIUC comparing with SparseNGrams I think that in this condition you need to reset:

previous_data = nullptr;
previous_len = 0;

Otherwise you could miss some rows because buildStateIfNeeded can early-returns on a cache hit without re-initializing current_part_i

SELECT id FROM tab WHERE ip = '192.168.1.106' ORDER BY id;

SELECT 'prefix segment';
SELECT id FROM tab WHERE ip LIKE '192.168.%' ORDER BY id;

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.

Will this match equivalent text patterns like 192.168?

What about LIKE '%92.16%'

Or other functions like startWith('192.1')?

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.

What about LIKE '%92.16%'

IMO, main goal of it to solve problem of "bad" query/lookup pattern.
When someone write search by IP (192.168.1.43) but in bad way.

ip LIKE '%192.168.1.43%' -- we "at least" get 168.1 as useful token

ip LIKE '%192.168.1.43 %' -- we "at least" get 168.1.43 as token

ip LIKE '% 192.168.1.43%' -- we "at least" get 192.168.1 as token

Which marginally, but better than

SELECT tokensForLikePattern('%192.168.1.43%'), tokensForLikePattern('% 192.168.1.43%'), tokensForLikePattern('%192.168.1.43 %'),

['168','1']	['192','168','1']	['168','1','43']

For IPv6 or ids with more delimeters, advantage of "saved" tokens should be better/bigger

@Ergus

Ergus commented Jul 2, 2026

Copy link
Copy Markdown
Member

I don't think that it that much worse, than other already existing tokenizers which we can use in text indexes

yes, the ngrams is not actually the best example on how to use the text index. Somehow we still support it for some corner cases and legacy, but now really recommended in most of the cases precisely because of the dictionary size grow.

@UnamedRus

UnamedRus commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

not actually the best example on how to use the text index

I don't like alphatokens* ones either (for log style data).

They might work OK for normal text data, but in logs, people tends to have/use those symbols (by which we split) as part of ids (ip, uuid, mac, whatever custom id style they managed to invent).
And indexing those values sliced by alpha tokens is just a waste of space (both disk and "search space" for useless/too small/broad tokens). It can be argued that position information should fix that, but it's almost doubling index size, and imo it's still too much useless information to our relatively simple goal: search by various kind of ids (which actually represent relatively small byte/length size of total log data (which include a lot of text for humans, but irrelevant for our search requirements))

I think, we better be with (may be with better layout) bloom filter style index instead.

@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, 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.

@abashkeev abashkeev added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 4, 2026

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.

segmentation tokenizer, which more suitable for log data search/patterns

6 participants