Repository navigation
Use token skip indexes for LowCardinality(String) constants - #110017
alexey-milovidov merged 16 commits into
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260710-151900 |
|
Workflow [PR], commit [e1fb364] Summary: ✅
AI ReviewSummaryThe PR extends Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit e1fb364.
Changed lines: Changed C/C++ lines covered: 47/50 (94.00%) · Uncovered code |
…e_const_name_size LIMIT BY bad-cast, unrelated stress failure)
CI finish ledger — eaaee3aEvery 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.
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]>
|
Addressed in ab1a989. The map-key path ( Regression coverage added to |
Pre-PR validation gate (click to expand)
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-8:20260710-224400 |
CI finish ledger — 50e2ab8CI fully finished (Finish Workflow complete). No PR-caused failure (this PR strips LowCardinality on token-index constants; cannot affect ReplicatedDatabase alter). Every failure owned.
Session id: cron:our-pr-ci-monitor:20260711-030000 |
CI finish ledger — 50e2ab8Every 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
Session id: cron:our-pr-ci-monitor:20260711-040000 |
…-lowcardinality-constant-110010
There was a problem hiding this comment.
@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 | |||
| -- 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; |
| 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) |
There was a problem hiding this comment.
@groeneai Remove GRANULARITY 1 from everywhere in this test.
|
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-8:20260713-083400 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 34/38 (89.47%) · Uncovered code |
CI finish ledger — 3078aacEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The earlier partial fix #111528 (pin Session id: cron:our-pr-ci-monitor:20260729-103000 |
|
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. |
…cardinality-constant-110010
…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]>
|
CI never ran on the previous head: the 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.
Left alone deliberately: a plain Measurements (pristine master vs this branch)
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 |
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.
|
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
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.
I did not unify the two spellings (plain Noticed and not fixed here, pre-existing (measured identical on master and on this branch): |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 23 s compile time in total, 8 of them have a recent master baseline. |
|
@groeneai @CurtizJ @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Confirmed, and part of it belongs to this PR. Details and the full table are in #118690; the short version:
This PR did widen it. A 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 |
`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]>
Closes: #110010
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
text,tokenbf_v1andngrambf_v1skip indexes not being used when the searched constant has typeLowCardinality(String)(e.g.hasToken(s, toLowCardinality('rare'))ors = toLowCardinality('rare')), which caused a silent full scan. Such predicates now prune granules like their plainStringcounterparts, matching the primary key andbloom_filterindex behavior.Description
The token-search index conditions checked the constant's type with
isStringOrFixedString()before stripping wrappers. AConst(LowCardinality(String))needle kept itsLowCardinalitywrapper, failed the gate, produced no index condition, and the query degraded to a full scan. SincehasToken/text-search predicates have no fallback index type, an LC-typed needle guaranteed a full scan.KeyCondition(primary key) and the plainbloom_filterindex already strip the wrapper and prune correctly. This aligns the token indexes with them: stripLowCardinality, thenNullable(only for a non-null value, mirroringRPNBuilderTreeNode::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 shapesLowCardinality(String),LowCardinality(Nullable(String)),Nullable(String), plus derived-LC constants (scalar subquery over an LC column). Regression test asserts pruning is preserved viaEXPLAIN indexes = 1.Only a
Stringneedle is unwrapped. ALowCardinality(FixedString)one stays wrapped and is still declined:FixedStringcarries NUL padding that string equality ignores but a tokenizer does not, so admitting it discarded matching granules. A plainFixedStringneedle keeps its current behavior, which mishandles that padding independently of this change.hasTokenrejects 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. PlainStringandNullable(String)needles keep their current behavior of building the condition and pruning it away, which01781_token_extractor_buffer_overflowpins 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 withLowCardinality, so it stays out of this PR. TheOrNullvariants keep using the index.Workflow [PR]
Sync PR [sync-upstream/pr/110017]