Skip to content

Use token skip indexes for LowCardinality(String) constants - #110017

Merged
alexey-milovidov merged 16 commits into
ClickHouse:masterfrom
groeneai:fix-token-index-lowcardinality-constant-110010
Sep 7, 2026
Merged

alexey-milovidov merged 16 commits into
ClickHouse:masterfrom
groeneai:fix-token-index-lowcardinality-constant-110010

Conversation

@groeneai

@groeneai groeneai commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110010

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed text, tokenbf_v1 and ngrambf_v1 skip indexes not being used when the searched constant has type LowCardinality(String) (e.g. hasToken(s, toLowCardinality('rare')) or s = toLowCardinality('rare')), which caused a silent full scan. Such predicates now prune granules like their plain String counterparts, matching the primary key and bloom_filter index behavior.

Description

The token-search index conditions checked the constant's type with isStringOrFixedString() before stripping wrappers. A Const(LowCardinality(String)) needle kept its LowCardinality wrapper, failed the gate, produced no index condition, and the query degraded to a full scan. Since hasToken/text-search predicates have no fallback index type, an LC-typed needle guaranteed a full scan.

KeyCondition (primary key) and the plain bloom_filter index already strip the wrapper and prune correctly. This aligns the token indexes with them: strip LowCardinality, then Nullable (only for a non-null value, mirroring RPNBuilderTreeNode::tryGetConstant, so a NULL needle stays rejected), before the string-type gate. The constant Field is already a plain value, so only the type wrapper needs stripping.

Covers all three families (text, tokenbf_v1, ngrambf_v1) and the shapes LowCardinality(String), LowCardinality(Nullable(String)), Nullable(String), plus derived-LC constants (scalar subquery over an LC column). Regression test asserts pruning is preserved via EXPLAIN indexes = 1.

Only a String needle is unwrapped. A LowCardinality(FixedString) one stays wrapped and is still declined: FixedString carries NUL padding that string equality ignores but a tokenizer does not, so admitting it discarded matching granules. A plain FixedString needle keeps its current behavior, which mishandles that padding independently of this change.

hasToken rejects a needle holding a token separator, so this change does not admit such a needle to the index: pruning would discard the granule that owes the exception. Plain String and Nullable(String) needles keep their current behavior of building the condition and pruning it away, which 01781_token_extractor_buffer_overflow pins and which is the only place the needle reaches the token extractor. Making the two spellings agree would change behavior for predicates that have nothing to do with LowCardinality, so it stays out of this PR. The OrNull variants keep using the index.


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

The text, tokenbf_v1 and ngrambf_v1 index conditions checked the searched
constant's type with isStringOrFixedString() before stripping wrappers, so a
Const(LowCardinality(String)) needle (e.g. hasToken(s, toLowCardinality('x'))
or s = toLowCardinality('x')) failed the gate, built no index condition, and
the query silently fell back to a full scan. KeyCondition and the plain
bloom_filter index already strip the wrapper and prune.

Strip LowCardinality, then Nullable (only for a non-null value, mirroring
RPNBuilderTreeNode::tryGetConstant so a NULL needle stays rejected) before the
string-type gate. The constant Field is already a plain value, so only the
type wrapper needs stripping. Covers text/tokenbf_v1/ngrambf_v1 and the
LowCardinality(String), LowCardinality(Nullable(String)), Nullable(String) and
derived-LC shapes.

Closes: ClickHouse#110010

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN indexes=1 SELECT count() FROM t WHERE hasToken(s, toLowCardinality('rare')) reads Granules: 128/128 (full scan) before the fix vs 1/128 after, for text/tokenbf_v1/ngrambf_v1.
b Root cause explained? The token index conditions test the constant type with isStringOrFixedString() before stripping wrappers. RPNBuilderTreeNode::tryGetConstant strips only Nullable, not LowCardinality, so a Const(LowCardinality(String)) needle keeps its LC wrapper, fails the gate, builds no index condition, and the query full-scans.
c Fix matches root cause? Yes. Strip LowCardinality (and non-null Nullable) off the constant type before the string-type gate in both MergeTreeIndexConditionText and MergeTreeConditionBloomFilterText, exactly the wrapper that was making the gate fail.
d Test intent preserved / new tests added? New stateless test 04365_token_index_lowcardinality_constant asserts pruning is PRESERVED (Granules: 1/128) for each family and shape, plus a correctness check. No existing test weakened.
e Demonstrated in both directions? Yes. Test FAILS on pristine master (5 LC assertions return 0) and PASSES with the fix. Build IDs confirmed distinct between pristine and fixed binaries.
f Fix is general, not a narrow patch? Both sibling token-index condition files fixed (text and bloom-filter-text); the arrayElement map-key const gate in the bloom path also stripped. Plain bloom_filter and KeyCondition already handled this.
g Generalizes across inputs / wrappers? Verified: LowCardinality(String), LowCardinality(Nullable(String)), Nullable(String), derived-LC (scalar subquery over LC column), and hasAnyTokens LC array all prune. NULL needle safely rejected (returns 0, no crash).
h Backward compatible? Yes. No format/setting/default change; only enables pruning that was silently disabled. Results were already correct; only reading was unpruned.
i Invariants and contracts preserved? Yes. Only the const type wrapper is stripped for the type gate; the Field value is untouched. NULL-value handling mirrors tryGetConstant so a NULL needle is not passed to safeGet<String>().

Session id: cron:clickhouse-worker-slot-1:20260710-151900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @CurtizJ for review: aligns the text/tokenbf_v1/ngrambf_v1 index conditions with KeyCondition and the bloom_filter index by stripping LowCardinality off the searched constant before the string-type gate, so LC-typed needles prune granules instead of full-scanning.

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e1fb364]

Summary: ✅


AI Review

Summary

The PR extends text, tokenbf_v1, and ngrambf_v1 skip-index analysis to non-null LowCardinality(String) carriers, covers the corresponding map-key paths, and adds the follow-up guards needed to avoid FixedString false negatives and swallowed hasToken exceptions. After checking the current e1fb3641 diff against the full touched implementations, prior review threads, and the available CI reports, I did not find a remaining blocker or major issue to raise on this head.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit e1fb364.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 47/50 (94.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 10, 2026
@CurtizJ CurtizJ self-assigned this Jul 10, 2026
…e_const_name_size LIMIT BY bad-cast, unrelated stress failure)
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — eaaee3a

Every failure below has an owner. This PR (token skip-index LowCardinality constant, MergeTree text/tokenbf/ngrambf index conditions only) did not cause any of them.

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) / Bad cast FunctionNode→ConstantNode (STID 1635-18db), LIMIT ... BY const + optimize_const_name_size=0 trunk fuzzer crash (10+ unrelated PRs + master, unrelated to this diff) #109938 (ours, merged 2026-07-10 15:52Z) — merged master into this branch @ 6c4bf0e to pick it up (build predated the fix)
CH Inc sync — CH Inc sync (private, not actionable)

The stress failure ran at 18:56Z on a build that predated #109938's 15:52Z merge, so it did not contain the fix. Merged master; CI re-runs with the fix present.

The map-element key path (traverseMapElementKeyNode) gated the constant
key with isStringOrFixedString on the raw type, so a LowCardinality key
(attrs[toLowCardinality('k')] = 'v' / IN (...)) failed the gate and fell
back to a full scan instead of using the mapKeys(...) text index hint.
Mirror the compared-value fix: strip LowCardinality then Nullable
(non-null only) before the string-type gate.

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

Copy link
Copy Markdown
Collaborator Author

Addressed in ab1a989. The map-key path (traverseMapElementKeyNode) now strips LowCardinality then Nullable (non-null only) off the constant key before the isStringOrFixedString gate, matching the compared-value path. attrs[toLowCardinality('k')] = 'v' and attrs[toLowCardinality('k')] IN (...) now prune via the mapKeys(...) text index instead of full-scanning.

Regression coverage added to 04365_token_index_lowcardinality_constant. Since the analyzer folds attrs[key] into a mapKeys subcolumn before it reaches this branch, the test sets optimize_functions_to_subcolumns = 0 so the arrayElement map-key path is exercised directly. Verified fails-without-fix (LC map-key reads 128/128) and passes-with-fix (1/128), same single granule as the plain-String key.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. attrs[toLowCardinality('entity')] = 'v' on a mapKeys(attrs) text index with optimize_functions_to_subcolumns = 0 reads 128/128 granules (full scan) on HEAD; the plain-String key reads 1/128.
b Root cause explained? traverseMapElementKeyNode gated the constant map key with isStringOrFixedString(const_key_argument->result_type) on the RAW type. isStringOrFixedString does not strip LowCardinality/Nullable, so a LowCardinality(String) key failed the gate, no index condition was built, and the query degraded to a full scan. Same defect the compared-value path had.
c Fix matches root cause? Yes. Strip LowCardinality then Nullable (non-null only, mirroring RPNBuilderTreeNode::tryGetConstant and the compared-value fix) before the string-type gate; a NULL key stays rejected.
d Test intent preserved / new tests added? New map-key section in 04365_token_index_lowcardinality_constant; sets optimize_functions_to_subcolumns = 0 to exercise the arrayElement branch directly. Asserts pruning preserved via EXPLAIN indexes = 1 (String / LC = / LC IN) plus a correctness check. Existing assertions unchanged.
e Demonstrated in both directions? Yes. Fails-without-fix: LC = and LC IN map-key cases read 128/128 (test diff at the two map-key lines). Passes-with-fix: all prune to 1/128, reference byte-exact. Verified against pristine (buildId 0C8602F0) vs fixed (buildId 85559A17) binaries.
f Fix general, not a narrow patch? Yes. This completes the sibling coverage: the compared-value path was fixed in the prior commit; this fixes the map-element key path, the second and last string-type gate in this file that took a raw type. Same strip-then-gate pattern.
g Generalizes across inputs / wrappers? Covers String, LowCardinality(String) for both = and IN. Nullable is stripped only for a non-null key; NULL keys stay rejected (a NULL map key cannot match).
h Backward compatible? Yes. No setting/format/default change; strictly enables index pruning for predicates that previously full-scanned but returned identical results.
i Invariants preserved? Yes. getDataAt(0) already resolves the concrete value through the LowCardinality/Nullable/Const column (LC via dictionary), so key_const_value is unchanged; only the type gate was too strict. The mapKeys-hint contract is unchanged.

Session id: cron:clickhouse-worker-slot-1:20260710-213700

…xt index

The mapKeys(...) arrayElement path in MergeTreeConditionBloomFilterText gated
the constant key with isStringOrFixedString after removeLowCardinality only.
tryGetConstant strips just an outer Nullable, so a
LowCardinality(Nullable(String)) key (attrs[CAST('k','LowCardinality(Nullable(String))')] = 'v')
survived as Nullable(String), failed the gate and degraded to a full scan
instead of using the mapKeys(...) tokenbf_v1 / ngrambf_v1 hint. Mirror the
text-index map-key fix: strip LowCardinality then Nullable (non-null only)
before the string-type gate; a NULL key stays rejected.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. attrs[CAST('entity','LowCardinality(Nullable(String))')] = 'v' on a mapKeys(attrs) tokenbf_v1/ngrambf_v1 index reads 128/128 granules (full scan) on the pristine binary, every run.
b Root cause explained? tryGetConstant strips only an outer Nullable. The bloom-filter map-key gate then did removeLowCardinality(const_type) only, so a LowCardinality(Nullable(String)) key became Nullable(String), isStringOrFixedString returned false, the branch bailed, and no index condition was built -> full scan.
c Fix matches root cause? Yes. Strip LowCardinality then Nullable (non-null only) before the string-type gate, mirroring the compared-value path and the text map-key fix.
d Test intent preserved / new tests added? New assertions extend 04365_token_index_lowcardinality_constant with mapKeys(...) tokenbf_v1/ngrambf_v1 indexes asserting pruning is PRESERVED via EXPLAIN indexes = 1 (Granules 1/128) across String / LC / LC(Nullable) keys + correctness. No existing assertion weakened.
e Demonstrated in both directions? Yes. Pristine (buildId 85559A17): LC(Nullable) map-key cases read 128/128, test diff mismatches. Fixed (buildId C8E4DBDE): all prune 1/128, full test byte-exact against .reference.
f Fix is general, not a narrow patch? Yes. Audited both token-index condition files: value-side (MergeTreeIndexConditionText.cpp:840, MergeTreeIndexBloomFilterText.cpp:467), text map-key (MergeTreeIndexConditionText.cpp:1363), and now bloom-filter map-key (:514) all strip LowCardinality->Nullable consistently. No remaining sibling gates the raw type of a constant key.
g Fix generalizes across inputs / wrappers? Verified the key wrapper matrix: String, LowCardinality(String), LowCardinality(Nullable(String)) all take the fixed path and prune; NULL key stays rejected. IN map-key is a separate pre-existing limitation (plain-String IN is also not pruned by the bloom mapKeys branch), documented and out of scope.
h Backward compatible? Yes. Optimization-only: previously-scanned granules are now pruned; results unchanged. No setting/format/default change.
i Invariants and contracts preserved? Yes. getDataAt(0) already resolves the concrete value through LC/Nullable/Const, so const_value is unchanged; only the type gate widens. NULL-safety preserved (NULL key still rejected).

Session id: cron:clickhouse-worker-slot-8:20260710-224400

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 50e2ab8

CI fully finished (Finish Workflow complete). No PR-caused failure (this PR strips LowCardinality on token-index constants; cannot affect ReplicatedDatabase alter). Every failure owned.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter chronic flaky (48 PRs/9 master, 30d) #110030 (ours, open)
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260711-030000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 50e2ab8

Every failure below has an owner: a fixing PR (ours 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_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (15+ unrelated PRs + 9 on master in 30d; not in this PR's diff — token skip-index only) #110030 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)
PR (aggregator) reflects the above #110030 (ours, open)

Session id: cron:our-pr-ci-monitor:20260711-040000

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 Rename this test to 02346_text_index_bug110010.sql.

@@ -0,0 +1,105 @@
-- Token-search skip indexes (text, tokenbf_v1, ngrambf_v1) must prune granules when the

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 Remove the comment on l. 1-6

-- while a plain-String needle pruned to a single granule. Each assertion below checks that
-- the LowCardinality variant reads the SAME single granule as the plain-String variant.

SET enable_analyzer = 1;

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 Try to remove the setting.

DROP TABLE IF EXISTS t_tokenbf;
DROP TABLE IF EXISTS t_ngrambf;

CREATE TABLE t_text (id UInt64, s String, INDEX idx s TYPE text(tokenizer = splitByNonAlpha) GRANULARITY 1)

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 Remove GRANULARITY 1 from everywhere in this test.

@rschu1ze

Copy link
Copy Markdown
Member

Oh, I missed that @CurtizJ is assigned already. Sorry then, please ignore my comments.

…ality needles

The LowCardinality unwrapping added earlier makes LC(Nullable(String)) map-value
comparisons reachable, but the absent-key guards in the arrayElement and map
subcolumn branches compared value_field against value_type->getDefault(). For a
LC(Nullable(String)) needle that default is NULL, while arrayElement returns the
plain String default ('') for a missing key, so the guard failed to fire and a
granule-skipping bloom condition was built. Rows where the key is absent (matching
via the map default) were then wrongly skipped: a false negative.

Compare against the already-computed unwrapped_value_type default instead.

Regression: absent-key lookup with an empty LC(Nullable(String)) needle on a
mapKeys(...) tokenbf_v1 index must return all rows.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM t WHERE attrs['missing'] = CAST('', 'LowCardinality(Nullable(String))') on a mapKeys(...) tokenbf_v1 index returns 0 (should be 1024) every run on the baseline binary.
b Root cause explained? The earlier LC-unwrapping made LowCardinality(Nullable(String)) map-value comparisons reachable. The absent-key guards (arrayElement branch + map.key_* subcolumn branch) compared value_field == value_type->getDefault() on the RAW type, whose default is NULL. arrayElement(Map(String,String), missing_key) returns the plain-String default '', so '' != NULL → guard did not fire → a granule-skipping bloom condition was built → granules where the key is absent (all rows match via the map default) were wrongly skipped: false negative.
c Fix matches root cause? Yes. Both guards now compare against unwrapped_value_type->getDefault() (the already-computed strip-LC-then-Nullable type). For the LC(Nullable(String)) needle that unwrapped type is String, default '', which correctly matches the map default → guard fires → no skipping condition built.
d Test intent preserved / new tests added? Yes. Added an absent-key correctness case to 04365_token_index_lowcardinality_constant asserting all 1024 rows are returned. Existing pruning assertions unchanged.
e Both directions demonstrated? Yes. Baseline (fix reverted, Build ID d6fd40f6) returns 0 rows / full test diff mismatches at the absent-key line; fixed (Build ID d350283b) returns 1024 / full test byte-exact against .reference.
f Fix is general across code paths? Yes. Both raw-default guard sites in MergeTreeConditionBloomFilterText::traverseTreeEquals (arrayElement branch L494, map subcolumn branch L542) are fixed; grep confirms no remaining value_type->getDefault(). The text sibling (traverseMapElementValueNode) already checks the concrete Field value (safeGet<String>().empty()) so it is wrapper-agnostic and needs no change.
g Fix generalizes across inputs? Yes. unwrapped_value_type is derived by stripping LowCardinality then (non-null) Nullable, so the guard is correct for plain String, LowCardinality(String), Nullable(String), and LowCardinality(Nullable(String)) empty needles — all resolve to the String default ''. A NULL needle stays rejected (Nullable not stripped when null).
h Backward compatible? Yes. No setting, format, or on-disk change; pure query-planning correctness fix (removes a wrong granule-skip). No SettingsChangesHistory impact.
i Invariants and contracts preserved? Yes. The absent-key guard's contract ("do not build a skipping condition when the needle equals the map's arrayElement default") is now upheld across all needle wrappers. getDataAt(0) still resolves the concrete value through LC/Nullable/Const, so the built bloom value is unchanged for present-key predicates.

Session id: cron:clickhouse-worker-slot-8:20260713-083400

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 34/38 (89.47%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3078aac

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server, each with a different query id, so the long-running holder query competes against itself for the single max_concurrent_queries slot and is rejected instead of holding it #112385 (ours, open)

The earlier partial fix #111528 (pin max_threads = 1 on the holder query) is present on this
head and does not cover the parallel-replicas route, so #112385 disables parallel replicas for
this test outright.

Session id: cron:our-pr-ci-monitor:20260729-103000

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

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

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@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 4, 2026
groeneai and others added 6 commits September 5, 2026 08:35
…dex test

Master answers a bare count() over a text-search predicate directly from the text
index posting lists (ReadFromTextIndexCount, setting
query_plan_optimize_count_from_text_index, enabled by default). No ReadFromMergeTree
node is left in the plan, so the "Granules: 1/128" assertions had nothing to read and
the three text-index cases reported 0. The plain-String control failed identically,
which places the change in master rather than in this fix; results stayed correct
(both needles return 1,500).

Disabling that optimization for the test restores the oracle. Checked both directions:
with the fix the file is byte-exact against the reference, and with the fix
reverse-applied exactly the ten LowCardinality assertions redden while every
plain-String control still passes, so the assertions discriminate the
LowCardinality property itself. query_plan_direct_read_from_text_index and
query_plan_text_index_add_hint are randomized by clickhouse-test, so the oracle was
confirmed over all four combinations and over 50 runs with both randomized.

Co-Authored-By: Claude Opus 5 <[email protected]>
The absent-key assertion ran with optimize_functions_to_subcolumns disabled, so it only
reached the arrayElement guard. The map-subcolumn branch has a second, separate default
comparison, and reverting that one alone left the whole test file green: a regression
there was invisible.

With subcolumn folding enabled the analyzer rewrites attrs['missing'] to a map.key_*
reference and the second guard is what decides. Reverting it makes the new assertion
return 0 rows instead of 1024 (the skip index prunes every granule, Granules: 0/128),
so the arm reddens on exactly the code it covers while the existing arrayElement
assertion stays green.

Co-Authored-By: Claude Opus 5 <[email protected]>
…dition

Stripping LowCardinality admitted FixedString needles into token analysis, and that loses
rows. A FixedString constant carries NUL padding: string equality ignores it, so
`s = toLowCardinality(toFixedString('rareword', 12))` is true for the stored value
`rareword`, but the tokenizer does not, so the condition searches for padded tokens the
indexed value never produced and the matching granule is skipped. Measured against the
same tree without this commit: ngrambf_v1 and text(ngrams(3)) equality returned 0 rows
instead of 1, and the map absent-key lookup with an empty LowCardinality(FixedString)
needle returned 0 instead of 1024 through both the arrayElement and the map-subcolumn
guard. Before the LowCardinality unwrapping those shapes failed the type gate, so they
were correct.

Unwrapping now applies only when the stripped type is String, which leaves a wrapped
FixedString to be declined as before. Declining costs pruning, not correctness. A plain
FixedString needle keeps its existing behaviour: it already reached this path and already
mishandles padding, which is a separate defect and not widened here.

The map-key gates are left alone on purpose: the wrapper is folded away before them, so
that shape measures identically with and without this change.

Co-Authored-By: Claude Opus 5 <[email protected]>
…lter text index

`hasToken` and `hasTokenCaseInsensitive` reject a needle containing a token separator, and a
scan reports that as BAD_ARGUMENTS. The bloom-filter condition tokenized the needle anyway, so
the granule that owed the exception was pruned and the query returned an empty result instead.
MergeTreeIndexConditionText already declines these needles for this exact reason; this mirrors
that guard in the sibling. The `OrNull` variants yield NULL rather than an error, so they keep
using the index.

Admitting LowCardinality needles had widened the hole: measured on a tokenbf_v1 index,
`hasToken(s, toLowCardinality('bad needle'))` raised before that change and returned 0 after,
while the plain-String spelling returned 0 both before and after. The guard covers the needle,
not the wrapper, so both spellings raise again, matching an unindexed table.

Also assert pruning for a non-null LowCardinality(Nullable(String)) value needle: the existing
bloom-filter assertions put the wrapper on the map key, which a different gate decides.

Co-Authored-By: Claude Opus 5 <[email protected]>
…euse

The separator check read `const_value`, which the arrayElement and map-subcolumn branches
replace with the map key before the `hasToken` branch runs, so on those paths it could
inspect a key rather than the needle. It now reads `value_field`.

No behaviour change that I could construct: on a mapValues index neither branch overwrites
`const_value`, and with a mapKeys index the `hasToken` branch is not reached, so both
spellings raise identically in every shape I measured. This makes the expression correct
where it was accidentally right, and no test accompanies it because I could not write one
that fails without it.

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

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI never ran on the previous head: the Config Workflow job on 2026-08-01 timed out retrying a CI-database query and praktika dropped the whole matrix, leaving 173 skipped jobs and no test results. Merging master both re-triggers the workflow and picks up #113052, which removed that query.

Validating the refreshed branch against five weeks of trunk found three problems that CI had never had a chance to catch, so this push is more than a rebase. The approval above predates them.

  1. LowCardinality(FixedString) needles were being unwrapped into the index condition. FixedString carries NUL padding that string equality ignores but a tokenizer does not, so matching granules were discarded. Master was accidentally correct here, because the wrapper failed the type gate. Only String is unwrapped now.
  2. hasToken with a separator-bearing needle lost its BAD_ARGUMENTS error on a tokenbf_v1 index: the needle was tokenized and the granule that owed the exception was pruned. MergeTreeIndexConditionText already declines those needles; the bloom-filter sibling now does too, which also restores the error for the plain String spelling.
  3. The Granules: 1/128 assertions had gone stale, because master now answers a bare count() over a text-search predicate from the posting lists (ReadFromTextIndexCount) and leaves no ReadFromMergeTree node to read. The test pins that optimization off and gained arms for the map-subcolumn absent-key guard and for a non-null LowCardinality(Nullable(String)) value needle, neither of which was covered.

Left alone deliberately: a plain FixedString needle mishandles the same padding, but that reproduces on master unchanged by this PR and belongs with the FixedString padding work, not here.

Measurements (pristine master vs this branch)
query master before this push now
s = toLowCardinality(toFixedString('rareword',12)), ngrambf_v1 1 0 1
same, text(tokenizer = ngrams(3)) 1 0 1
attrs['missing'] = CAST('','LowCardinality(FixedString(3))') 1024 0 1024
hasToken(s, toLowCardinality('bad needle')), tokenbf_v1 raises 0 rows raises
hasToken(s, 'bad needle'), tokenbf_v1 0 rows 0 rows raises
plain FixedString needle (out of scope) 0 0 0

Each change was checked in both directions: the test is byte-exact with it and reddens exactly the intended assertions without it. Reverting only the map-subcolumn guard reddens only that arm; removing the LowCardinality(FixedString) restriction reddens only the four new arms. The test also passed 50 consecutive runs with query_plan_direct_read_from_text_index and query_plan_text_index_add_hint randomized per run.

5400178 declined the tokenbf_v1 / ngrambf_v1 index for any separator-bearing
`hasToken` needle, so that the scan raises BAD_ARGUMENTS instead of the index
pruning the granule that owes the exception. That bail-out was too broad.
Master declines only the wrapped spelling, whose LowCardinality wrapper fails
the string-type gate; a plain `String` needle keeps building the condition and
prunes the granule away.

So the broad form changed three needle shapes this PR has no business changing
(measured, pristine master -> 5400178):

  hasToken(s, 'abcabcabcabcabcabcabcab\0')             0 -> BAD_ARGUMENTS
  hasToken(s, 'bad needle')                            0 -> BAD_ARGUMENTS
  hasToken(s, CAST('bad needle', 'Nullable(String)'))  0 -> BAD_ARGUMENTS

The first of those is 01781_token_extractor_buffer_overflow, which turned Fast
test red. Its expectation is not stale: the needle reaches the token extractor
only while the index condition is built (`EXPLAIN indexes = 1` shows the skip
index applied on master and absent at 5400178), so declining the index removes
the very call the test exists to exercise. Re-pointing it at the exception
would leave a token-extractor test that never reaches the token extractor.

Scope the bail-out to a needle that arrived wrapped, which is exactly what the
unwrapping above newly admits. Plain `String` and `Nullable(String)` needles
again behave as on master, and the LowCardinality spellings still reach the
scan and raise, so no exception that this PR made reachable is swallowed.

The remaining asymmetry, plain `String` pruning while LowCardinality raises, is
master's and predates this PR; the `text` index resolves it the other way, for
both spellings. Unifying tokenbf_v1 with it is a user-visible change to 2021
behaviour and belongs in its own PR.
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Narrowed the separator-needle bail-out from the previous commit. It was keyed on the needle alone, so it also fired for spellings master already handles, which turned Fast test red on 01781_token_extractor_buffer_overflow.

tokenbf_v1 over 'yyy,uuu', measured on pristine master / previous head / now:

needle master prev now
hasToken(s, 'abcabcabcabcabcabcabcab\0') 0 BAD_ARGUMENTS 0
hasToken(s, 'bad needle') 0 BAD_ARGUMENTS 0
hasToken(s, CAST('bad needle', 'Nullable(String)')) 0 BAD_ARGUMENTS 0
hasToken(s, toLowCardinality('bad needle')) BAD_ARGUMENTS BAD_ARGUMENTS BAD_ARGUMENTS

The bail-out now applies only to a needle that arrived wrapped, which is exactly what the unwrapping newly admits: identical to master for every spelling above, and the exception this PR makes reachable is still not swallowed.

01781's expectation is not stale. EXPLAIN indexes = 1 shows the skip index applied for that needle on master and absent on the previous head, so the needle reaches the token extractor only while the index condition is built. Expecting the error there instead would leave a token-extractor test that never reaches the token extractor.

I did not unify the two spellings (plain String prunes, LowCardinality raises). That asymmetry is master's and predates this PR, the text index resolves it the other way for both, and changing tokenbf_v1 to match is user-visible for predicates that have nothing to do with LowCardinality.

Noticed and not fixed here, pre-existing (measured identical on master and on this branch): multiSearchAny(attrs['missing'], ['a']) with a mapKeys(...) tokenbf_v1 index raises Code: 170 BAD_GET, while the same query without the index returns 0.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e1fb36414 with master 29dbd618d (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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit 051c925 Sep 7, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @CurtizJ @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, and part of it belongs to this PR. Details and the full table are in #118690; the short version:

NOT hasToken / NOT hasAllTokens / NOT hasAnyTokens over a Nullable(String) or LowCardinality(Nullable(String)) column with a text index already returned the NULL rows before this PR, for a plain String needle. Exact direct read replaces the whole predicate with a UInt8 virtual column, and the cast back to Nullable(UInt8) restores the type but not the null mask, so a NULL row reads as 0 and NOT 0 keeps it.

This PR did widen it. A toLowCardinality('...') needle was not index eligible before, so it never reached that replacement and returned the correct rows; unwrapping the needle made it eligible, and it inherited the same missing null mask. Measured on three binaries with distinct Build IDs (current master, master with this PR's source reverted, master plus the fix), the LC-needle spelling goes from [3] to [2,3], while every plain-needle spelling is identical with and without this PR. EXPLAIN indexes = 1 agrees: no skip-index block for that needle before, one after.

The root cause is tracked as #106922 and the fix is #113332, which I measured to correct all of it, including the two spellings this PR widened and NOT hasPhrase on an index built with support_phrase_search = 1. So the failure has an owner and I am not opening a competing fix.

vanchaklar pushed a commit to vanchaklar/ClickHouse that referenced this pull request Oct 1, 2026
`RPNBuilderTreeNode::tryGetConstant` now returns the type of the value
the constant holds: `LowCardinality` is removed, and `Nullable` is
removed when the value is not NULL. A `Field` is the plain value, so
every consumer of `tryGetConstant` (`KeyCondition`, the text index, the
bloom filter indexes, the selectivity estimator) sees `String` for
`toLowCardinality('x')` and `CAST('x', 'LowCardinality(Nullable(String))')`.
The per-consumer stripping added by ClickHouse#110017
in `MergeTreeIndexConditionText` and `MergeTreeConditionBloomFilterText`
is removed, together with the special case that made a `LowCardinality`
`hasToken` needle with a separator behave differently from a `String` one.

`MergeTreeIndexConditionText::traverseMapElementKeyNode` accepts a
predicate result of `Nullable(UInt8)` or `LowCardinality(UInt8)`, which a
`Nullable` map key produces; NULL reads as false, as in WHERE. The
constant key is read through `tryGetConstant` instead of unwrapping the
column by hand. This supersedes ClickHouse#110031.

The absent-key guards in `MergeTreeConditionBloomFilterText` compare the
constant with its `FixedString` padding stripped. `FixedString` reports
'' as its default while the constant holds N zero bytes, so
`m['missing'] = CAST('', 'FixedString(N)')` used the `mapKeys` index and
returned no rows instead of all rows.

`RPNBuilderTreeNode` holds a const reference to the tree context, so a
node can be built from a const function node.

Closes: ClickHouse#110018

Co-Authored-By: Claude Fable 5.1 <[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-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

7 participants