Repository navigation
Conversation
…xt index Building a text index over a `LowCardinality(String)` column, or over the elements of an `Array(LowCardinality(String))` column, tokenized every row and hashed and looked up every token, although the values come from a small dictionary. Now `MergeTreeIndexAggregatorText::update` tokenizes a dictionary value at its first occurrence in the call, keeps pointers to the posting list builders of its tokens, and appends later rows directly to them. The builders live in the cells of the token map, which move when the map grows, so each cached value remembers the buffer size it was cached at and is cached again after a resize; a value whose own tokens made the map grow is not cached at all. The map only shrinks in `reset`, which is never called while `update` runs (the INSERT/merge transform flushes a segment after `update`, the part writer takes the granule before it). The cache is used only without a postprocessor drop filter (so no builder is `Filtered`) and when dictionary values repeat, at least 8 documents per dictionary value in the call (a conservative threshold): a value is tokenized at its first occurrence anyway, so without repeats there is nothing to save. Columns with ~30,000 and ~865,000 distinct values stay on the existing code and are unchanged. `addToken` and `addDocument` compile to the same instructions as before (checked on a non-ThinLTO release build). Pointers are taken with a `find` right after the existing `addToken`, rather than through a copy of `addToken` that returns the builder, so the token insertion logic stays in one place. A cache of the packed token keys, with one `find` per repeated token, was also measured: it gives -27% on the shape below, the pointer cache -35%. Measured with a non-ThinLTO release build (paired, 20 repetitions): `MATERIALIZE INDEX` of a text index on a `LowCardinality(String)` column with 50 distinct values over 2M rows 106 ms -> 70 ms (-35%); arrays of 500 LowCardinality values per row -18% for INSERT and MATERIALIZE; String and high-cardinality LowCardinality columns unchanged within the noise; peak memory unchanged. The analysis and the first version of the patch are by snelheidai in ClickHouse#122234. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ached builders The `japanese` tokenizer keeps the buffer it parsed last and re-parses only a new `(data, length)`, so tokenizing the same dictionary value right after itself can return no tokens. The INSERT writer calls `update` once per data granule on the same block, with one tokenizer for the whole index granule, so the first value of a granule could be cached with no tokens and its later rows in that granule were missing from the index. The cache is now used only with a tokenizer that keeps no state between calls, so `japanese` and `sparseGrams` keep the per-row path. Re-caching after the token map grows appended a new token range and never released the old one. Now the cached builders are cleared when the buffer size changes. `add` compares a value's recorded buffer size with the current one before it reads the value's range, and the buffer size only grows, so no value that points into the cleared entries can pass that check; such values are cached again at their next occurrence. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the class comment of LowCardinalityDocumentsAdder to one line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings on the first pass, 0 on the recheck of the fix round), plus my own review.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260926-071000 |
|
Workflow [PR], commit [92de8b8] Summary: ✅
AI ReviewSummaryThis PR adds a Final Verdict✅ No blocking findings. LLVM Coverage ReportMeasured on commit 92de8b8.
Changed lines: Changed C/C++ lines covered: 55/56 (98.21%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@ahmadov Another performance fix, low-priority though. The code looks bloated, we can probably simplify drastically. |
Tokenize the dictionary once with tokenizeToArray and keep a pointer to the posting list builder of each dictionary token, taken at the first occurrence of its value through the existing addToken and dropped for all values when the token map grows. This replaces the per-value token cache with its per-value buffer-size tracking, and drops the path for arrays of LowCardinality values. MATERIALIZE INDEX on a LowCardinality(String) column with 50 distinct values, 2M rows, non-ThinLTO release build, paired medians: 104.5 ms on master, 69 ms with this change, 68 ms with the previous version. The stateless test is reduced to the cases this path can get wrong, and the integration test for the japanese tokenizer is removed: the stateful tokenizer check stays, but the reduced path tokenizes each dictionary value once per call, so that test passes without the check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Simplified in f6ce817: the dictionary is now tokenized once with |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+19.05 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units28 translation units recompiled, 280 s compile time in total, 28 of them have a recent master baseline. |
The LowCardinality path of the text index build tokenized the whole dictionary on every `update` call with `tokenizeToArray`, including values the batch never references (a part's shared dictionary during a merge or mutation, or the whole block dictionary for each granule of an INSERT), and held a copy of all those tokens until the call returned. Now a value is tokenized at its first row in the batch, straight through the existing `addToken`, and only the pointers to its tokens' posting list builders are kept. Release build, non-ThinLTO, paired medians. INSERT of 819200 rows whose dictionary has 999 short values and one ~4 MiB value used by one row: master 81.5 ms / 24.5 MB, previous version 563 ms / 40.9 MB, this change 82 ms / 34.5 MB. MATERIALIZE INDEX with 50 distinct values, 2M rows (n=10): master 106 ms, previous version 70.5 ms, this change 72.5 ms. With 1000 distinct values of 32 KiB, peak memory is the same on all three. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dinality test A dictionary value that yields no tokens (empty, or only separators) got an empty range, which was also how a value not seen yet was marked, so it was tokenized again at every row. Unseen values are now marked with a sentinel. Every other row holding a 64 KiB separator-only value, 40960 rows, release build: INSERT 1461 -> 507 ms (master 1361 ms), MATERIALIZE INDEX 1131 -> 264 ms (master 1107 ms). A value is tokenized again at its first row in every `update`, so with the `japanese` tokenizer the same value can be tokenized twice in a row across two granules, and the second call returns no tokens. The stateful tokenizer check keeps such tokenizers on the per-row path; restore the integration test that fails without it (8192 of 10000 rows found). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add `Array(LowCardinality)` support. Extend the test with arrays, `sparseGrams`, the threshold and a merge, and measure `INSERT` with 100, 500 and 1000 distinct values in the perf test.
|
@groeneai I pushed a commit to simplify the implementation by using another approach. We already have a way to pre insert tokens and build the text index for those (introduced by #111690). We can simplify by using that. So, whenever you have a new commit, do not force push it. Also, added support for |
|
Thanks, understood about force pushes. I won't push while I checked 630f1fb on a debug build: the One gap in 05258, measured with a mutation: if a row with an empty array did not advance the row counter, |
@groeneai address that with a new commit |
CI finish ledger - 630f1fbEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
146 of 146 check runs completed (110 passed, 34 not selected, 2 red: the two shards above), Session id: cron:our-pr-ci-monitor:20260928-213347 |
…in 05258 Repeat the `tab` searches against a full scan after its `MATERIALIZE INDEX`, make every tenth `tab_array` row an empty array, and compare `hasAnyTokens` on `tab_array` with a full scan. Comparing only `(token, cardinality)` misses postings attributed to the wrong row: an empty array that does not advance the row counter keeps the same tokens and cardinalities. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in 456d584, a plain commit on top of 630f1fb: every tenth |
CI finish ledger - 456d584Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
146 of 146 check runs completed (111 passed, 34 not selected, 1 red: the shard above), Session id: cron:our-pr-ci-monitor:20260929-033123 |
|
@groeneai merge the latest origin/master into the branch. |
…inality-dictionary-tokens Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged the latest |
CI finish ledger - 2ba3353Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
149 of 149 check runs completed (111 passed, 34 not selected, 4 red: the two jobs above and their two rollups), Session id: cron:our-pr-ci-monitor:20260929-150228 |
`ranges` in `tryAddLowCardinalityDocuments` has one entry per dictionary value and is freed inside `update`, so `text_index_max_memory_usage_before_flush` never sees it. For arrays of `LowCardinality` the 8-documents-per-value gate counts elements, so a batch of very wide arrays could admit a dictionary of millions of values. Skip the fast path for dictionaries of more than 65536 values, which bounds `ranges` to 1 MiB. Peak memory (debug, tokenizer 'array', INSERT / MATERIALIZE INDEX), master, previous head, this commit: - 1 row x 8M elements, 999001 dictionary values: 490.38 / 488.72 MB, +20.18 MB, same as master - 1 row x 64M elements, 8M dictionary values: 2123.67 / 2239.44 MB, +144.78 MB, same as master A 65536-value dictionary still takes the fast path and a 65537-value one does not (checked with a mutant that corrupts only the fast path). Co-Authored-By: Claude Opus 5.5 <[email protected]>
| addDocumentsFromMap(preprocessed_column, offset, rows_read, context); | ||
| } | ||
| else | ||
| else if (!granule_builder.tryAddLowCardinalityDocuments(*preprocessed_column, nullptr, offset, rows_read, context)) |
There was a problem hiding this comment.
This is kind of inconsistent with above code. Can we rewrite to something like
[...]
else if (isMap(index_column.type) && tokenizer->getType() == ITokenizer::Type::KeyValuePairs)
{
addDocumentsFromMap(preprocessed_column, offset, rows_read, context);
}
else if (isLowCardinality(index_column.type)
addDocumentsFromLowCardinality([...])
else
[...]There was a problem hiding this comment.
Done in 86bf46e: after the Map branch, update now has else if (preprocessed_column->lowCardinality()) calling addDocumentsFromLowCardinality. It checks the preprocessed column rather than index_column.type, because a preprocessor such as CAST(s AS String) turns a LowCardinality column into a String one.
| size_t rows_read, | ||
| const PostingListBuildContext & context) | ||
| { | ||
| const auto * column_low_cardinality = typeid_cast<const ColumnLowCardinality *>(&column); |
There was a problem hiding this comment.
If we check that column is LowCardinality before (see my other comment), then we can rename tryAddLowCardinalityDocuments to addLowCardinalityDocuments and assert_cast in l. 1852
There was a problem hiding this comment.
Done in 86bf46e: it is now addDocumentsFromLowCardinality (the name from your sketch, like addDocumentsFromArray and addDocumentsFromMap), it returns nothing, and it uses assert_cast.
| { | ||
| const auto * column_low_cardinality = typeid_cast<const ColumnLowCardinality *>(&column); | ||
| /// A stateful tokenizer can return no tokens for a value tokenized again right after itself. | ||
| if (!column_low_cardinality || postprocessor_drop_filter || tokenizer->isStateful()) |
There was a problem hiding this comment.
The corresponding check in addToken looks different:
if (postprocessor_drop_filter && !postprocessor_drop_filter->drop_on_match)Intended?
There was a problem hiding this comment.
Intended. The cache stores a builder pointer per token after addToken, and with either filter mode there may be none to store: in keep-set mode addToken inserts nothing for a token outside the set, and in drop mode a dropped token gets a Filtered builder that must not receive postings. So with a drop filter each value is added with addDocument, as in the generic path. Caching anyway makes 05258 fail with std::bad_variant_access.
| const PostingListBuildContext & context) | ||
| { | ||
| const auto * column_low_cardinality = typeid_cast<const ColumnLowCardinality *>(&column); | ||
| /// A stateful tokenizer can return no tokens for a value tokenized again right after itself. |
There was a problem hiding this comment.
Not clear what the comment means
There was a problem hiding this comment.
Rewrote it in 86bf46e. The point is that the tokens of a value can be cached only if tokenizing the value again returns the same tokens. The stateful japanese tokenizer does not guarantee that: it parses again only when it gets a different buffer, so tokenizing the same value right after itself returns no tokens.
|
|
||
| bool MergeTreeIndexTextGranuleBuilder::tryAddLowCardinalityDocuments( | ||
| const IColumn & column, | ||
| const IColumn::Offsets * offsets, |
There was a problem hiding this comment.
Can we make the signature as similar as possible to the equivalent functions addDocumentsFromArray, addDocumentsFromArray, etc.? I.e. remove the offsets parameter. I think it's only used for the case of array inputs. However tryAddLowCardinalityDocuments can typeid_cast the input column to an Array and read by itself.
There was a problem hiding this comment.
Done in 86bf46e: the signature is now the one of addDocumentsFromArray, (ColumnPtr column, size_t start_row, size_t rows_read, const PostingListBuildContext & context), and the function reads the offsets itself when column is an array.
| auto elements_begin = [&](size_t row) { return offsets ? (*offsets)[row - 1] : row; }; | ||
|
|
||
| /// Rarely repeating values gain nothing, while `ranges` costs O(dictionary), and the dictionary is per block. | ||
| static constexpr size_t min_documents_per_value = 8; |
There was a problem hiding this comment.
8 seems a magic constant. It's not based on a dictionary size, right? Do we really need l. 1860-1863?
There was a problem hiding this comment.
It is relative to the dictionary: the cache is used only if the batch has at least 8 rows or array elements per dictionary value (8 is a conservative choice, not a tuned one). It is needed: without it, MATERIALIZE INDEX on a LowCardinality column with ~30k distinct values over 2M rows is 10.6% slower (paired release runs, 95% CI [7.5%, 13.8%]). Values rarely repeat within a block there, so the cache costs a pass over ranges and a lookup per token for nothing. With the check, that case is within noise of master. The 65536 cap next to it was added after your review, for the memory concern in this thread.
| node.query("DROP TABLE jp") | ||
|
|
||
|
|
||
| def test_text_index_low_cardinality(started_cluster): |
There was a problem hiding this comment.
Sure we want to mix in a test for low-cardinality columns in the existing Japanese tokenizer tests?
There was a problem hiding this comment.
It is the only test that fails without the isStateful() condition: with that condition removed, this test reads 8192 of the 10000 rows through the index, while 05258 still passes, because sparseGrams, the other stateful tokenizer, returns the same tokens every time. The MeCab dictionary is set up only in this suite, and a separate module would need its own copy of that setup, so I kept it here.
| </substitution> | ||
| </substitutions> | ||
|
|
||
| <create_query> |
There was a problem hiding this comment.
We should probably disable the merge for the two tables into which we insert.
There was a problem hiding this comment.
Done in 86bf46e: both tables get SYSTEM STOP MERGES in a fill_query.
|
|
||
| SELECT 'Search vs full scan'; | ||
| SELECT count(), sum(id) FROM tab WHERE hasToken(lc, 'w3'); | ||
| SELECT count(), sum(id) FROM tab WHERE hasToken(lc, 'w3') SETTINGS use_skip_indexes = 0, query_plan_direct_read_from_text_index = 0; |
There was a problem hiding this comment.
query_plan_direct_read_from_text_index = 0 looks redundant in l. 33, 35, 37
There was a problem hiding this comment.
Right, use_skip_indexes = 0 already disables the direct read (direct_read_from_text_index = query_plan_direct_read_from_text_index && use_skip_indexes in QueryPlanOptimizationSettings.cpp). Removed in 86bf46e, from all seven queries and from the Japanese test.
… fast path `builders` holds one pointer per token of each value first seen since the token map last grew, and is freed inside `update` like `ranges`, so one long repeated value (for example with `ngrams`) added 8 bytes of untracked memory per token. Stop caching at 1 << 23 pointers (64 MiB): values first seen after that are tokenized at every occurrence, as without the fast path, while the values cached before keep using the cache. The 1000 values of 6500 tokens from the PR description need 6.5M pointers per granule, so that case keeps its speedup. Debug build, INSERT of 16 rows sharing one value of N 'a' characters, ngrams(2), master / previous head / this commit: - N = 4M: 861 / 337 / 351 ms, peak 9.59 MB in all three - N = 12M: 2381 / 897 / 2684 ms, peak 210.04 / 247.06 / 210.04 MB A granule with cached values, a value that fills the cache and values first seen after it gives the same index as a String column; a mutant that keeps caching those later values loses their rows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`update` now picks the LowCardinality path by the column type, like the Map path, and `addDocumentsFromLowCardinality` has the signature of `addDocumentsFromArray`: it takes a LowCardinality column or an array of them, reads the offsets itself and asserts the type. The conditions of the token cache moved into it; when the cache does not apply, it adds each value with `addDocument`, as the generic path does. The check that values repeat at least 8 times per batch stays: without it, MATERIALIZE INDEX of a LowCardinality column with ~30k distinct values over 2M rows is 10.6% slower (paired release runs, 95% CI [7.5%, 13.8%]). Tests: `use_skip_indexes = 0` already disables the direct read from the text index, and the perf test no longer merges the tables it inserts into. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| const IColumnUnique & dictionary = column_low_cardinality.getDictionary(); | ||
| auto elements_begin = [&](size_t row) { return column_array ? column_array->getOffsets()[row - 1] : row; }; | ||
|
|
||
| static constexpr size_t min_documents_per_value = 8; |
There was a problem hiding this comment.
@groeneai can you add comments to explain what these constants do. e.g:
/// Values must repeat for the cache to pay off.
static constexpr size_t min_documents_per_value = 8;
/// Bounds `ranges` to 1 MiB.
static constexpr size_t max_dictionary_size = 65536;
/// Bounds `builders` to 64 MiB for long values.
static constexpr size_t max_cached_tokens = 1 << 23;keep comments short and brief
There was a problem hiding this comment.
Done in 92de8b8, with your wording. I also dropped the "so values must repeat" sentence above use_cache, since the new comment on min_documents_per_value now says it.
| void addDocument(std::string_view document, const PostingListBuildContext & context); | ||
| // Adds a document to the granule. The document is inserted directly as a single token. | ||
| void addToken(std::string_view token, UInt32 token_position, const PostingListBuildContext & context); | ||
| /// Adds the rows of a `LowCardinality` column or of an array of them, tokenizing each dictionary value once if possible. |
There was a problem hiding this comment.
Let's simplify this comment.
/// Adds the rows from a column or array of `LowCardinality`, tokenizing each dictionary value once.
Review feedback: say what each threshold of the dictionary cache is for, and shorten the comment of addDocumentsFromLowCardinality. Comments only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #122234
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Building a text index over a
LowCardinality(String)orArray(LowCardinality(String))column is faster: each distinct value is tokenized once per batch of rows instead of at every occurrence.MATERIALIZE INDEXover a column with 50 distinct values takes about 33% less time.Description
The text index build tokenized and hashed every value of a
LowCardinalitycolumn, although the values come from a small dictionary. Now each dictionary value that a batch uses is tokenized at its first occurrence, and later occurrences append to the posting list builders of its tokens, taken again after the token map grows. This is used forLowCardinalitycolumns and arrays ofLowCardinalityvalues when values repeat (at least 8 rows or array elements per dictionary value) and the dictionary has at most 65536 values, without a postprocessor, and with a tokenizer that keeps no state between calls.MATERIALIZE INDEX, non-ThinLTO release build, medians of paired runs:LowCardinality, 50 distinct values, 2M rowsLowCardinality, 1000 distinct values of 32 KiB, 40960 rowsString,LowCardinalitywith ~30k and ~865k distinct values, 2M rowsPeak memory is unchanged in these shapes. At most 2^23 builder pointers (64 MiB) are cached; values first seen after that are tokenized at every occurrence. Dictionary values that a batch does not use are not tokenized. The test compares the index over
LowCardinalitycolumns and arrays with the same index overStringcolumns, and searches with a full scan, for INSERT andMATERIALIZE INDEX. An integration test compares searches with a full scan for thejapanesetokenizer, which keeps state between calls and stays on the per-row path.For #117519: the cached path adds its tokens to
num_processed_tokensdirectly, so a per-row token count must be updated there too.Analysis and first patch by @ snelheidai in #122234.
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/122409]
Version info
26.10.1.1589-master(included in26.10and later)