Skip to content

Tokenize each LowCardinality dictionary value once when building a text index - #122409

Merged
ahmadov merged 13 commits into
ClickHouse:masterfrom
groeneai:text-index-low-cardinality-dictionary-tokens
Oct 5, 2026
Merged

ahmadov merged 13 commits into
ClickHouse:masterfrom
groeneai:text-index-low-cardinality-dictionary-tokens

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122234

Changelog category (leave one):

  • Performance Improvement

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

Building a text index over a LowCardinality(String) or Array(LowCardinality(String)) column is faster: each distinct value is tokenized once per batch of rows instead of at every occurrence. MATERIALIZE INDEX over a column with 50 distinct values takes about 33% less time.

Description

The text index build tokenized and hashed every value of a LowCardinality column, 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 for LowCardinality columns and arrays of LowCardinality values 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:

Shape master this PR
LowCardinality, 50 distinct values, 2M rows 104 ms 68.5 ms
LowCardinality, 1000 distinct values of 32 KiB, 40960 rows 5080 ms 2911 ms
String, LowCardinality with ~30k and ~865k distinct values, 2M rows within noise

Peak 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 LowCardinality columns and arrays with the same index over String columns, and searches with a full scan, for INSERT and MATERIALIZE INDEX. An integration test compares searches with a full scan for the japanese tokenizer, which keeps state between calls and stays on the per-row path.

For #117519: the cached path adds its tokens to num_processed_tokens directly, 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

  • Merged into: 26.10.1.1589-master (included in 26.10 and later)

groeneai and others added 3 commits September 26, 2026 05:40
…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ❌ The cache assumes tokenizing a value always gives the same tokens. The japanese tokenizer keeps its parse between calls and returns nothing when the same buffer comes again, so the cache could store an empty token list for a value AGREE, fixed @ 3be8b32 Stateful tokenizers keep the per-row path; the new integration test over LowCardinality fails without it (8192 of 10000 rows found)
2 ⚠️ Re-caching after a map resize kept the stale cached builders in memory AGREE, fixed @ 3be8b32 The cache now holds builders of one buffer size at a time
3 ⚠️ The tests do not show that the cached path runs DISAGREE Mutations of code that only the cached path runs (row, last token, token count, NULL check, resize handling) each fail the new test; if the path is ever disabled, the performance test reports the slowdown

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260926-071000

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [92de8b8]

Summary: ✅


AI Review

Summary

This PR adds a LowCardinality fast path to text-index builds by tokenizing each distinct dictionary value once per batch and replaying its postings into later rows, with explicit fallbacks for stateful tokenizers and postprocessor-driven paths. I did not find any remaining blocker or major issue in the current head: the earlier transient-memory concern is now bounded, the stateful-tokenizer case stays on the per-row path, and the tests now exercise insert, MATERIALIZE INDEX, arrays, merge, threshold behavior, and the postprocessor/drop-filter path.

Final Verdict

✅ No blocking findings.

LLVM Coverage Report

Measured on commit 92de8b8.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 55/56 (98.21%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 26, 2026
@groeneai
groeneai requested review from Ergus and ahmadov September 26, 2026 07:50
@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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
  • StressHouse run: b4cd7808-f802-43e8-85b1-6e380333415e
  • MIRAI run: 45b25d93-f347-4b3d-9a04-93799fb02430
  • PR check IDs:
    • clickbench_2721531_1790855912
    • clickbench_2721537_1790855912
    • clickbench_2721555_1790855912
    • tpch_adapted_1_official_2721573_1790855912
    • tpch_adapted_1_official_2721587_1790855912
    • tpch_adapted_1_official_2721601_1790855912

@rschu1ze

rschu1ze commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

@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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Simplified in f6ce817: the dictionary is now tokenized once with tokenizeToArray, the first occurrence of each value goes through the existing addToken, and later rows append to the posting list builders of its tokens (dropped when the token map grows). I removed the Array(LowCardinality) path, the integration test and most of the stateless test. The PR is now +142 lines, 60 of them in src/ (was +518, 183 in src/). MATERIALIZE INDEX over 50 distinct values: 104.5 ms on master, 69 ms with this version, 68 ms with the previous one.

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

4 object files changed (+19.05 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexText.cpp.o 788.36 KiB 807.41 KiB +19.05 KiB (+2.42%)

716 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

28 translation units recompiled, 280 s compile time in total, 28 of them have a recent master baseline.

Job report

groeneai and others added 2 commits September 28, 2026 15:26
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]>
@ahmadov ahmadov added the hold Skip for auto-updating. label Sep 28, 2026
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.
@ahmadov

ahmadov commented Sep 28, 2026

Copy link
Copy Markdown
Member

@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 Array(LowCardinality(..)).

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, understood about force pushes. I won't push while hold is set.

I checked 630f1fb on a debug build: the skp_idx_* files of a LowCardinality column are byte-identical to those of a plain column in 21 shapes (scalar and Array(LowCardinality(Nullable(String))) with NULL, empty, repeated and token-less elements, token map growth, the ngrams and array tokenizers, FixedString, a preprocessor), after INSERT, merge and MATERIALIZE INDEX. A mutation that drops one cached token changes 150 of those 568 files and fails 05258.

One gap in 05258, measured with a mutation: if a row with an empty array did not advance the row counter, hasAnyTokens on tab_array would return wrong rows with the same count() and the same (token, cardinality) pairs, and the test would still pass, because tab_array has no empty arrays and compares only (token, cardinality). Making every tenth row [] and adding SELECT count(), sum(id) FROM tab_array WHERE hasAnyTokens(lc, ['e3']) with skip indexes on and off catches it. Repeating the tab searches after its MATERIALIZE INDEX would cover the AI review's second point. Its first point is already covered: '' repeats in every tab_array row, and that branch only affects speed.

@ahmadov ahmadov removed the hold Skip for auto-updating. label Sep 28, 2026
@ahmadov

ahmadov commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

Thanks, understood about force pushes. I won't push while hold is set.

I checked 630f1fb on a debug build: the skp_idx_* files of a LowCardinality column are byte-identical to those of a plain column in 21 shapes (scalar and Array(LowCardinality(Nullable(String))) with NULL, empty, repeated and token-less elements, token map growth, the ngrams and array tokenizers, FixedString, a preprocessor), after INSERT, merge and MATERIALIZE INDEX. A mutation that drops one cached token changes 150 of those 568 files and fails 05258.

One gap in 05258, measured with a mutation: if a row with an empty array did not advance the row counter, hasAnyTokens on tab_array would return wrong rows with the same count() and the same (token, cardinality) pairs, and the test would still pass, because tab_array has no empty arrays and compares only (token, cardinality). Making every tenth row [] and adding SELECT count(), sum(id) FROM tab_array WHERE hasAnyTokens(lc, ['e3']) with skip indexes on and off catches it. Repeating the tab searches after its MATERIALIZE INDEX would cover the AI review's second point. Its first point is already covered: '' repeats in every tab_array row, and that branch only affects speed.

@groeneai address that with a new commit

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 630f1fb

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (amd_release, master_head, 2/6) / enum #1, int_parsing #62, int_parsing #32 dashboard confirmed_regression, client_time +28.2%, +22.9% and +16.3%, which the shard's own report also calls slower. All three reproduced after the harness restarted both servers (+28.8%, +23.3%, +15.4%), so the slowdown follows the two binaries, not one server process. The queries run toString over an Enum8 column and over integer columns of hits_100m_single, and none of them builds or reads a text index, which is the only code this head changes a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Performance Comparison (amd_release, master_head, 2/6) / json_key_formatting #3 dashboard confirmed_regression, client_time 0.297 -> 0.342 s (+15.0%). The shard's own report does not call it slower, so the harness never re-ran it after a restart. The query runs formatRow('TSV', id) over a Memory table. On amd it moved by more than 15% in 18 of 550 master-vs-master runs in the last 14 days a fix task is created (its fix direction awaits the performance harness owner's decision; fixing-PR link to follow on this PR)
Performance Comparison (amd_release, master_head, 3/6) / qbit_l2_distance_bfloat16_memory #1 dashboard confirmed_regression, client_time 0.119 -> 0.201 s (+68.4%). The shard's own report calls #0 and #1 slower, and both reproduced after the restart (+100.7%, +61.3%). The query computes L2DistanceTransposed over a QBit(BFloat16) column of a Memory table a fix task is created (the same one as for the first row)
Mergeable Check, PR rollups, red only because of the rows above a fix task is created (the same ones as for the rows above)

146 of 146 check runs completed (110 passed, 34 not selected, 2 red: the two shards above), Finish Workflow is green and CH Inc sync passed. The other slower rows of shard 2/6 (consistent_hashes, other int_parsing queries) do not fail a master_head shard. CIDB has no FAIL or ERROR test row on this head.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 456d584, a plain commit on top of 630f1fb: every tenth tab_array row is now [], hasAnyTokens(lc, ['e3']) on tab_array is compared with a full scan, and the tab searches are repeated after MATERIALIZE INDEX. On a debug build, the empty-array mutation now fails 05258, and a mutation applied only during MATERIALIZE INDEX that shifts the rows after each NULL keeps the same (token, cardinality) pairs but fails the repeated searches. I also updated the PR description for Array(LowCardinality).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 456d584

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 1/6) / countIf #3 dashboard confirmed_regression, client_time 0.0099 -> 0.0117 s (+18.1%). The shard's own report does not call it slower, so the harness never re-ran it after a restart. The query is SELECT countIf(AdvEngineID != 0) FROM hits_sparse over a one-column MergeTree table without a text index, and this PR changes only the text index build. On arm this query moved by more than 15% in 3 of 522 master-vs-master runs in the last 14 days #122782 (external, open), which re-runs such rows after a server restart and fails only on those that reproduce
Mergeable Check, PR rollups, red only because of the row above #122782 (external, open)

146 of 146 check runs completed (111 passed, 34 not selected, 1 red: the shard above), Finish Workflow is green and CH Inc sync passed. The shard's 6 too long note does not fail a master_head shard. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260929-033123

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

LGTM 👍

@ahmadov

ahmadov commented Sep 29, 2026

Copy link
Copy Markdown
Member

@groeneai merge the latest origin/master into the branch.

…inality-dictionary-tokens

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged the latest origin/master in 2ba3353, a plain merge commit on top (no force push). It had no conflicts, and the PR's diff against master is unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2ba3353

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_llvm_coverage, 1/8) / test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds fails on every master run since this test file was restored on 2026-09-29: master now decodes manifest bounds only for the columns a filter uses, so the log line that the assertion at line 337 waits for is no longer written. This PR changes only the text index build #122895 (mine, open)
Performance Comparison (amd_release, master_head, 3/6) / sum_map #1 dashboard confirmed_regression, client_time 0.149 -> 0.177 s (+18.6%), which the shard's own report also calls slower. It reproduced after the harness restarted both servers (confirm_changes: 1 of 7 flagged queries did not reproduce after restart, and this is not that one). The query is SELECT maxMap(key, val) FROM sum_map_100000, which neither builds nor reads a text index, the only code this head changes. On amd the same query was reported slower in 5 other runs of the last 14 days (4 unrelated PRs and 1 master run) a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the rows above #122895 (mine, open), and a fix task is created (the same owners as for the rows above)

149 of 149 check runs completed (111 passed, 34 not selected, 4 red: the two jobs above and their two rollups), Finish Workflow is green and CH Inc sync passed. map_subcolumns_prewhere #0 in shard 3/6 is unstable, which does not fail a master_head shard. CIDB has no other FAIL or ERROR test row on this head.

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))

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 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
    [...]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())

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.

The corresponding check in addToken looks different:

if (postprocessor_drop_filter && !postprocessor_drop_filter->drop_on_match)

Intended?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

Not clear what the comment means

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

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.

8 seems a magic constant. It's not based on a dictionary size, right? Do we really need l. 1860-1863?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

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.

Sure we want to mix in a test for low-cardinality columns in the existing Japanese tokenizer tests?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

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.

We should probably disable the merge for the two tables into which we insert.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

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.

query_plan_direct_read_from_text_index = 0 looks redundant in l. 33, 35, 37

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

groeneai and others added 2 commits September 29, 2026 18:52
… 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;

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.

@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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

Let's simplify this comment.

/// Adds the rows from a column or array of `LowCardinality`, tokenizing each dictionary value once.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 92de8b8.

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]>
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... groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index build tokenizes and hashes every occurrence of a LowCardinality value; tokenizing each dictionary value once cuts MATERIALIZE INDEX 37%

4 participants