Skip to content

keyValuePairs tokenizer: basic functionality - #115363

Closed
UnamedRus wants to merge 9 commits into
ClickHouse:masterfrom
UnamedRus:keyvaluepairs-tokenizer-exact
Closed

UnamedRus wants to merge 9 commits into
ClickHouse:masterfrom
UnamedRus:keyvaluepairs-tokenizer-exact

Conversation

@UnamedRus

@UnamedRus UnamedRus commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Extracted from #110757

Another option to consider, use "namespaces" for token dictionary. (as alternative to take one bit from varint encoding)
First byte of token is namespace.
Currently, we will have:
\0 is rest of pairs
\1 is first key-value pair per key of row. (or make it even \x80)

May be in future, some other namespaces can be added
ie value major encoding (for better/more efficient filtering by 'value%' prefixes), ...

Plan is, that this first byte should be compressed/encoded efficiently by dictionary layout.

Changelog category (leave one):

  • New Feature

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

New keyValuePairs tokenizer for the text index: accelerates exact m['key'] = 'value' and m['key'] IN (...) predicates on Map(String, String) columns via granule pruning.


Workflow [PR]
Sync PR [sync-upstream/pr/115363]

UnamedRus and others added 6 commits August 18, 2026 21:19
Introduce a `keyValuePairs` text-index tokenizer for `Map(String, String)` /
`Map(LowCardinality(String), LowCardinality(String))` columns. Each map entry is
stored as one token `key || value || reversed-varint((len(key) << 1) | is_rest)`
(is_rest distinguishes a key's first occurrence from later duplicates), so a
whole (key, value) pair is one dictionary entry.

This first version uses the index for granule pruning of the exact predicates:
  m['key'] = 'value'
  m['key'] IN ('v1', ...)
Both build the exact pair token(s) (first occurrence, is_rest = 0) and prune
granules; the predicate is re-checked on surviving granules (no direct read).
Every other map / text-search function is left untouched by the index and falls
back to a normal scan, so results are unchanged. `preprocessor` / `postprocessor`
options and non-String (incl. FixedString) key/value types are rejected.

Tests:
- 04926: index behavior, token format, exact lookups, IN, default-value,
  LowCardinality, duplicate keys, long keys, special-byte keys, rejected types.
- 04927: every existing map function returns identical results with and without
  the index (no wrong pruning).
- 04928: randomized index-on vs index-off consistency.
Updates the system.tokenizers reference and documents the tokenizer in the text
index reference (docs/reference/.../textindexes.mdx).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Move the first-occurrence/duplicate discriminator out of the token trailer
and into a dedicated leading namespace byte, so the token layout becomes:

    token   = namespace | key | value | trailer
    trailer = reversed-varint(key.size())

namespace 0 = a key's first occurrence in a row, 1 = a later duplicate.
Positional `m['key']` lookups (first-value semantics) match namespace 0;
existence over any occurrence can union namespaces 0 and 1.

This makes the tokens self-describing and forward-compatible: future token
kinds (for example, a distinct namespace for guaranteed-unique-key maps, or
the decode-scan / direct-read work that needs to distinguish occurrences) can
be added without changing the on-disk layout or requiring a per-part encoding
version. Emitting both namespaces now means parts written by this version stay
usable by those later features without a rebuild.

Dropping the `<< 1 | is_rest` packing also frees the single-byte trailer to
cover keys up to 127 bytes (previously 63), so more keys avoid the multi-byte
reversed-varint path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…g future kind

Namespace 0 (a key's first occurrence) already covers the unique-key case, so
that was a poor example of what a future namespace buys. The real motivation is
a value-first token kind laid out as value | key: it sorts tokens by value and
so enables value-prefix/suffix scans, mirroring how namespace 0's key | value
layout enables key-prefix scans.

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

04928 covers single predicates; this covers the RPN combination path the branch
implements - AND / OR / NOT chains and m['key'] IN (...) over the in-scope exact
atoms. Randomized data over a small key/value space (non-vacuous), run index-on
vs index-off; results must match. Also folds the OR-of-equals vs IN(...)
equivalence into the same on/off check.

Out-of-scope families (mapContains*, LIKE/startsWith, direct-read) are omitted:
they are not accelerated yet, so including them would test scan-vs-scan.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The keyValuePairs index build labelled a key's first occurrence in a row
(is_rest = 0) versus later duplicates (is_rest = 1) with a per-row linear scan
over the keys seen so far - O(entries^2) per row. For wide maps that is a real
cost (a micro-benchmark showed ~9 / 72 / 265 ns per entry at 8 / 64 / 256 keys).

Replace it with one hash map, scoped to the addDocumentsFromArray call, mapping
each key to the last row index it appeared in. A key already stamped with the
current row is a within-row duplicate; its first appearance in the row (freshly
inserted, or last stamped in an earlier row) is is_rest = 0. The row-index stamp
lets the map serve every row without a per-row clear - stale entries from earlier
rows auto-invalidate - and map keys are a small, stable vocabulary, so the map
stops growing after warm-up: O(1) per entry, flat ~8 ns regardless of map width
in the same benchmark. Entries are still visited in stored order, so the first
occurrence is the one m['key'] returns and token positions are unchanged.

A versioned direct-mapped 'oracle' table was also prototyped but rejected: it
is marginally faster only for small maps and degrades badly for wide ones
(birthday collisions force a per-row exact recheck), for no robustness gain.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Assign the smaller namespace byte to the rare kind. Duplicate map keys are
extremely uncommon, so giving the duplicate namespace the value 0 makes it sort
first: when a part does contain duplicate-key tokens, they become the
dictionary's minimum token and their presence is detectable from the resident
sparse index (its first boundary token) without reading a dictionary block - a
free "does this part have duplicate keys?" check. If instead the first-occurrence
kind sorted first (the previous 0/1 assignment), the rare duplicate tokens would
land at the end of the dictionary, usually buried inside the last block, and
detecting them would require a block read.

Extract the two values as named constants MAP_KV_NAMESPACE_FIRST / _REST so the
one place that emits the byte reads intelligibly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@tuanpach tuanpach added the can be tested Allows running workflows for external contributors label Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20c82c6]


AI Review

Summary

This PR adds a keyValuePairs tokenizer for text indexes on Map(String, String)-like columns and uses it to prune granules for exact m['key'] = 'value' / m['key'] IN (...) predicates. The main gap I found is in the option contract: the new tokenizer-specific validation rejects some unsupported options, but it still accepts support_phrase_search, which adds positions storage for a feature the query side can never use.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeIndexText.cpp:2223] keyValuePairs still accepts support_phrase_search = 1, but hasPhrase explicitly rejects this tokenizer in MergeTreeIndexConditionText, and a Map index has no alternate positions consumer. That means users can enable the option, pay for .pos streams and larger metadata, and get no behavioral change at all. Reject support_phrase_search for keyValuePairs in the same validator branch that already rejects preprocessor / postprocessor, or implement/document a real positions-based query surface.
Tests

⚠️ Add a validator test that TYPE text(tokenizer = 'keyValuePairs', support_phrase_search = 1) is rejected, so this dead option surface does not regress back in later.

Final Verdict

Needs changes before merge: reject support_phrase_search for keyValuePairs (or add a real positions-based consumer for it).

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3574fd9cf with master 4c1d9c8ad (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ed263e523; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.04 MiB 699.03 MiB -3.00 MiB (-0.43%)

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

15 object files changed (+78.22 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexConditionText.cpp.o 807.39 KiB 839.16 KiB +31.77 KiB (+3.94%)

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

42 translation units recompiled, 337 s compile time in total, 41 of them have a recent master baseline.

Job report

UnamedRus and others added 2 commits August 20, 2026 10:56
The test ran ~323s under `amd_asan_ubsan`, over the 180s per-run limit
("Test runs too long (> 180s)"). Cost is dominated by the number of
generated statements: a 5x6 needle grid emitted 9 statements per cell,
run twice (index on and off), for 540 executions.

Shrink the grid to 3x3 (162 executions, ~30%). The rotations still span
every key `k0`..`k4` and values `v0`..`v4`, and the per-run randomized
data keeps the matched row sets varying across runs, so coverage of the
RPN AND/OR/NOT combine logic is preserved.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115363&sha=3574fd9cf81aac475073be1ba3ec2ba5c74c8d59&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
PR: ClickHouse#115363

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test exceeded the per-run runtime limit on the `amd_asan_ubsan`
flaky check. The many small index-on/index-off query pairs are slow
under ASan+UBSan; the consistency check is architecture-independent, so
skip it there via the `no-asan` tag while it still runs on other builds.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115363&sha=3574fd9cf81aac475073be1ba3ec2ba5c74c8d59&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
PR: ClickHouse#115363

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

if (!which_data_type.isString() && !which_data_type.isFixedString())
/// The `keyValuePairs` tokenizer builds tokens from `(key, value)` pairs, with no String
/// tokenization step for `preprocessor` / `postprocessor` to hook into (a postprocessor would also

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.

support_phrase_search = 1 is still accepted for keyValuePairs, but hasPhrase explicitly refuses every tokenizer except splitByNonAlpha, splitByString, asciiCJK, icu, and ngrams in MergeTreeIndexConditionText. For a Map index there is no other query surface that can consume positions, so this option only writes .pos streams / HasPositions metadata and increases build + storage cost without ever changing query behavior. Since this branch already rejects unsupported preprocessor / postprocessor, support_phrase_search should be rejected here as well (or implemented with an actual positions consumer).

A `Map` text index has no query surface that consumes positions:
`hasPhrase` refuses every tokenizer except `splitByNonAlpha`,
`splitByString`, `asciiCJK`, `icu` and `ngrams`, and the exact
`m['key'] = value` / `IN` atoms this tokenizer accelerates never use
positions. Enabling `support_phrase_search` therefore only writes
`.pos` streams and `HasPositions` metadata, increasing build time and
storage without ever changing query behavior.

The branch already rejects the unsupported `preprocessor` /
`postprocessor` options for `keyValuePairs`; reject
`support_phrase_search` the same way until an actual positions consumer
exists. The check runs after the experimental-feature gate, so it
covers the case where `allow_experimental_text_index_phrase_search` is
enabled.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@rschu1ze

Copy link
Copy Markdown
Member

There is an alternative minimal PR now: #115579 (comment)

@Ergus

Ergus commented Aug 20, 2026

Copy link
Copy Markdown
Member

There is an alternative minimal PR now: #115579 (comment)

The other PR is smaller and the key difference is that this one already covers the IN function and adds many new tests.
On the other hand IIUC this one only uses TextIndexDirectReadMode::None instead of direct read.

I need to review this one, but I have no problem to prefer this over mine if it includes the direct read ;)

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 pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants