Skip to content

Use text index on map element with Nullable constant key - #110031

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-nullable-map-key-110018
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-nullable-map-key-110018

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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

A text index defined on mapKeys(m) / mapValues(m) is now used for m[key] = value when the constant map key is wrapped in Nullable (e.g. m[CAST('key' AS Nullable(String))]), instead of falling back to a full scan.

Description

Closes #110018.

A text index on mapKeys(m) / mapValues(m) was used for WHERE m['key'] = 'value' but not for the semantically equivalent WHERE m[CAST('key' AS Nullable(String))] = 'value'. The Nullable wrapper makes arrayElement return Nullable(String) and the comparison return Nullable(UInt8), and the map-element analysis in the text index condition rejected both types.

Fix: strip the Nullable wrapper in the map-element key/value analysis (MergeTreeIndexConditionText), mirroring what the JSON-subcolumn path already does. This is safe for a non-NULL constant key: arrayElement(m, key) returns the value-type default (empty string) for an absent key, not NULL, so the "predicate is false on the default value" invariant the map-element optimization relies on still holds. A NULL constant key still declines the mapKeys path (it would break the invariant); the value index remains a safe over-approximation there.

Verified with EXPLAIN indexes = 1: both the mapKeys and mapValues indexes now prune granules (2/128) for a Nullable (and LowCardinality(Nullable)) constant key, matching the plain-key behaviour. Regression test: 02346_text_index_bug110018.

A text index on mapKeys(m) / mapValues(m) was used for m['key'] = 'value'
but not for m[CAST('key' AS Nullable(String))] = 'value'. The Nullable
wrapper makes arrayElement return Nullable(String) and the comparison return
Nullable(UInt8), and the map-element analysis rejected both, falling back to
a full scan.

Strip the Nullable wrapper in the map-element key and value analysis. This is
safe for a non-NULL constant key: arrayElement returns the value-type default
(empty string) for an absent key, not NULL, so the pruning invariant holds. A
NULL key still declines the mapKeys path.

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 m[CAST('key5' AS Nullable(String))] = 'value5' shows a full scan (no index) on master; deterministic.
b Root cause explained? The analyzer rewrites the predicate so arrayElement returns Nullable(String) and equals returns Nullable(UInt8). traverseMapElementKeyNode rejected the result type via WhichDataType(result_type).isUInt8() (no removeNullable), and hasIndexForMapElementValue did not see through the _CAST(..., 'Nullable(String)') wrapper, so both map-element index paths declined and the query full-scanned.
c Fix matches root cause? Yes. Strip Nullable on the result-type check and the constant-key type check, and unwrap a Nullable-only CAST in the value path. Directly targets the type-gating that rejected the wrapped types.
d Test intent preserved / new tests added? New regression test 02346_text_index_bug110018 asserts result correctness AND granule pruning (Granules: 2/128 via the SELECT ... FROM (EXPLAIN indexes=1 ...) WHERE explain ILIKE '%...%' form). No existing test weakened.
e Both directions demonstrated? Yes. Baseline binary: no index lines (full scan). Fixed binary: idx_keys 2/128, idx_vals 2/2 — matching the plain-key query.
f Fix is general across code paths? Both map-element paths fixed (mapKeys key path + mapValues value path). The JSON-subcolumn sibling already stripped Nullable; this brings map-element to parity. Not a symptom guard — the type check is corrected at the analysis site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified for Nullable(String), LowCardinality(Nullable(String)), and LowCardinality(String) constant keys (all prune). NULL key correctly declines the mapKeys path and still returns correct (empty) results; missing key returns default (0 rows).
h Backward compatible? (maintainer-approved exception only) N/A — pure query-optimization enablement; no setting default, on-disk/wire format, or new validation changed. Results unchanged; only granule pruning improves.
i Invariants and contracts preserved? Yes. The map-element optimization requires the predicate to be false on the value-type default (empty map). A non-NULL constant key yields the default value for absent keys (not NULL), which the code still evaluates on the empty map before accepting. NULL keys are explicitly rejected in the mapKeys path.

Session id: cron:clickhouse-worker-slot-5:20260710-162000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @ahmadov — could you review? Small fix in the text-index map-element condition analysis (MergeTreeIndexConditionText) to strip the Nullable wrapper so a text index on mapKeys/mapValues is used for m[CAST('key' AS Nullable(String))] = 'value', mirroring the JSON-subcolumn path. Closes #110018.

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [524edc2]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
Logical error: Unexpected return type from A. Expected B. Got C. Action: (STID: 1611-4523) FAIL cidb

AI Review

Summary

This PR extends MergeTreeIndexConditionText so text indexes on mapKeys(m) / mapValues(m) remain usable when the constant map key is wrapped in Nullable or LowCardinality, and it restricts the new CAST unwrap to byte-preserving wrappers so casts like FixedString(N) still fall back safely. I did not find any unresolved correctness, safety, or coverage gaps in the current head.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 32/35 (91.43%) · 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
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai look LowCardinality case and LowCardinality(Nullable) case too.

Extend the map-element key analysis in MergeTreeIndexConditionText to also
strip LowCardinality and LowCardinality(Nullable) wrappers on the constant
key, not just Nullable. Previously m[CAST('key' AS LowCardinality(String))]
and m[CAST('key' AS LowCardinality(Nullable(String)))] failed the mapKeys
type gate (removeNullable does not strip LowCardinality), so the text index
on mapKeys(m) was not used and the query fell back to a full scan. Use
removeLowCardinalityAndNullable at the type gates and recursiveRemoveLowCardinality
on the key column before reading its value.

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

Copy link
Copy Markdown
Collaborator Author

Done in d802e70. The map-element key gates now use `removeLowCardinalityAndNullable` (not just `removeNullable`) and `recursiveRemoveLowCardinality` on the key column, so `m[CAST('key' AS LowCardinality(String))]` and `m[CAST('key' AS LowCardinality(Nullable(String)))]` now use the mapKeys text index.

Note: a constant-folded key (e.g. a literal cast) is rewritten to a map subcolumn reference and already pruned. The gap was only on the non-folded path (arrayElement(map, wrapped_key)), so the test uses materialize() on the key in the EXPLAIN indexes = 1 checks to exercise it; those checks fail without this change and pass with it.

Only see through a CAST on the map element value when it reduces to the same
base type after stripping LowCardinality/Nullable. A byte-changing cast (e.g.
FixedString(N), which pads with trailing zero bytes) would make hasIndexForMapElementValue
search the mapValues text index for a token that differs from the raw String
stored in the index, wrongly pruning a matching granule.

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

Copy link
Copy Markdown
Collaborator Author

Fixed in 0beac82. hasIndexForMapElementValue now only sees through a _CAST/CAST on the map value when the target type reduces to the same base type as its argument after stripping LowCardinality/Nullable, i.e. a nullability/LowCardinality-only wrapper that preserves the indexed bytes. A byte-changing cast such as FixedString(N) (trailing zero padding) no longer reuses the mapValues index.

Confirmed both directions on a debug build:

  • baseline (unwrap every CAST): SELECT count() FROM tab WHERE CAST(m['k'],'FixedString(5)')=toFixedString('ab',5) returns 0 with an array tokenizer (the matching ab granule is wrongly pruned), EXPLAIN shows idx_vals used.
  • with the fix: same query returns the matching row, EXPLAIN shows idx_vals NOT used; the byte-preserving Nullable(String) cast still uses it.

Added a focused regression to 02346_text_index_bug110018 asserting the FixedString-cast value returns the matching row and does not use idx_vals, while the Nullable(String) cast still does.

groeneai and others added 2 commits July 10, 2026 21:41
The idx_vals name appears both in the Prewhere filter column and the index
Name line of EXPLAIN indexes=1 output on current master, so an exact count()
on lines mentioning idx_vals is fragile. Use count() > 0 (is the index used?)
which is what the assertions actually check.

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

clickhouse-gh Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 75.20% 85.80% +10.60%
Functions 89.50% 92.70% +3.20%
Branches 65.70% 77.90% +12.20%

Changed lines: Changed C/C++ lines covered: 32/35 (91.43%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 99ea083

Every failure below has an owner (a fixing PR or a full-effort fix task). Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 04401_distributed_with_fill_const_to_scalar flaky (13 master hits + ~16 unrelated PRs/30d; serialize_query_plan=1 + prefer_localhost_replica=0 hits the unimplemented WITH FILL plan-serialization path — unrelated to this PR's text-index change) #110060 (ours, open)

Prior-SHA-only failures (0beac82), already fixed on 99ea083 by the reference/EXPLAIN-assertion fix: Fast test / 02346_text_index_bug110018, Finish Workflow / Post Hooks.

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

@rschu1ze

rschu1ze commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

@PedroTadim Could you please ping the text index team for Groene fixes in the text index area? The LLM tends to produce sloppy and overly verbose code which we should check before integrating into the codebase. Thanks!

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim Could you please ping the text index team for Groene fixes in the text index area? The LLM tends to produce sloppy and overly verbose code which we should check before integrating into the codebase. Thanks!

Ok, maybe I should flag the text index team first, then let them decide whether to request groeneai?

@rschu1ze

Copy link
Copy Markdown
Member

It's totally fine if you say "fix" at Groene (you don't need to wait). Just make sure that the resulting PR gets some eyes by someone familiar with the code (tagging colleagues is enough). Thanks.

@rschu1ze

Copy link
Copy Markdown
Member

Another Groene PR that adds lots of new code to support a questionable use case. I'll look at it when I find some time (haven't done anything else but reviewing Groene PRs today).

@groeneai Please don't push new commits

@groeneai

Copy link
Copy Markdown
Collaborator Author

@rschu1ze understood, no further commits - it is yours to review when you have time.

Re the automated review re-surfacing on the hasIndexForMapElementValue CAST unwrap: that finding is already addressed on the current head (99ea083), in commit 0beac82. The unwrap is restricted to byte-preserving wrappers only - the two-arg CAST is recursed solely when removeLowCardinalityAndNullable(cast.result_type) equals removeLowCardinalityAndNullable(argument.result_type), so byte-changing casts (e.g. FixedString(N), which pads with trailing zero bytes) do not use the index. A focused regression in 02346_text_index_bug110018 asserts the FixedString(6) value cast returns the matching row and does NOT use idx_vals, while the Nullable cast still does.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 524edc2

CI is fully finished on this head (174 check-runs, 0 incomplete, Config Workflow and
Finish Workflow both success). 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
Stress test (arm_asan_ubsan) / Logical error: Unexpected return type from equals. Expected Nullable(UInt8). Got UInt8 (STID 1611-4523) Not PR-caused: aborts in MergeTreeIndexConditionSet::getPossibleGranules (MergeTreeIndexSet.cpp:485) on a set skip index, not on the text index this PR touches. 13 rows across 13 distinct PRs in 30 days, 1 of them on master #110338 (ours, open)

The Build (arm_release) / Post Hooks CIDB row is not a check failure: the
Build (arm_release) check itself concluded success. The build-profile hook logs
WARNING: LogCluster query failed with code 500 from the reporting sink, which is
infrastructure-side and does not affect the build artifact. It is fleet-wide right now
(963 rows across 315 distinct PRs in the last 3 days).

The other 172 checks are green.

Session id: cron:our-pr-ci-monitor:20260803-220000

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

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

CurtizJ commented Sep 15, 2026

Copy link
Copy Markdown
Member

Superseded by #120220.

@CurtizJ CurtizJ closed this Sep 15, 2026
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 v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index on mapKeys/mapValues is not used when the map element key is a Nullable constant

4 participants