Skip to content

Fix text and token skip indexes over-pruning IPv6 columns - #113157

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-const-conversion-ipv6
Sep 23, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-const-conversion-ipv6

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

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

Fixed ngrambf_v1, tokenbf_v1 and sparse_grams skip indexes silently dropping matching rows when an IPv6 column is compared with a string literal, as in WHERE ip = '2001:db8::'. The index probe is now built from the constant converted into the indexed column's own type, so it matches the bytes the index stores.

Description

A skip index on an IPv6 column drops the matching row:

CREATE TABLE t (ip IPv6, INDEX idx ip TYPE ngrambf_v1(3, 512, 3, 0))
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('2001:db8::');

SELECT count() FROM t WHERE ip = '2001:db8::';                    -- 0, wrong
SELECT count() FROM t WHERE ip = '2001:db8::'
SETTINGS ignore_data_skipping_indices = 'idx';                    -- 1, correct

No forced index or unusual setting. tokenbf_v1, sparse_grams, LowCardinality(IPv6), the map-key subcolumn form and ip IN (SELECT ...) do the same; ip = toIPv6('2001:db8::') is unaffected.

Root cause. The index tokenizes the column's raw bytes, for IPv6 the 16 bytes 20010DB800..., but MergeTreeConditionBloomFilterText::traverseTreeEquals checked only the constant's type and tokenized its own bytes, the ASCII 2001:db8::. The encodings share nothing, so the filter reported no match and the granule was pruned. The bloom_filter index converts, and is correct here.

Change. Convert the constant into the column's primitive type and re-serialize it through that type's own column, so the probe bytes are the bytes the index stores. It also runs per IN set element, where a subquery set is not type-checked against the index. An unrepresentable constant declines the atom, which full scans and answers correctly; String/FixedString keep the old path. A map element compared with the map value type's default declines too: an absent key reads as that default, which a mapValues index does not hold. Granules are untouched, so existing indexes need no rebuild.

Validation. 04716_text_index_ipv6_string_constant uses the index-ignored query as its oracle and force_data_skipping_indices on positive queries, so a declined atom is an error rather than a silent full scan. 10 of its 18 assertions fail on unpatched master, each mutation-backed; 50 of 50 randomized runs are green; a 383-test skip-index and map suite shows no regressions.

Reported by an automated review comment on #112868.


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

Version info

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

The ngrambf_v1 / tokenbf_v1 / sparse_grams aggregator tokenizes the raw bytes
of the indexed column, which for an IPv6 column are its 16 stored bytes.
MergeTreeConditionBloomFilterText::traverseTreeEquals gated on the CONSTANT's
type only and then tokenized the constant's own bytes, so for

    WHERE ip = '2001:db8::'

the granule held n-grams of 20010DB8000000000000000000000000 while the probe
was built from the ASCII 323030313A6462383A3A. The two encodings share no
prefix, so the bloom filter reported no match and the matching granule was
pruned: 0 rows instead of 1, on a plain SELECT with no forced index and no
unusual setting.

The query is only valid because the comparison function converts separately at
runtime (executeWithConstString). Index analysis had no counterpart; the
sibling bloom_filter index does convert and is correct on the same query.

Convert the constant into the indexed column's primitive type and re-serialize
it through that type's own column, so the probe bytes are the bytes the index
stores. A constant that cannot be represented there declines the atom, which
falls back to a full scan and a correct answer; tryConvertFieldToType is used
so index analysis cannot raise for a constant the comparison would never
evaluate. String and FixedString columns keep the previous code path exactly
via an early return, since there the constant already is the index encoding
and a constant wider than a FixedString must still be able to prune.

Affected carriers, all measured: ngrambf_v1, tokenbf_v1 and sparse_grams on
IPv6, ngrambf_v1 on LowCardinality(IPv6), and the map-key subcolumn form on a
Map(IPv6, ...) with a mapKeys index. Granules are untouched, so existing
indexes stay valid and need no rebuild.
…ndex

tryPrepareSetBloomFilter is a third arm with the shape the previous commit
repaired in traverseTreeEquals: it type-gates on the SET's element types and
then tokenizes their raw bytes, without converting them into the indexed
column's encoding.

The tuple form of IN was already safe by accident. RPNBuilderTreeNode::
tryGetPreparedSet resolves a literal tuple through PreparedSets::findTuple,
which requires equals(set->getTypes(), types) against the index data types, so
a String tuple set against an IPv6 index never matches and the atom declines.
A subquery resolves through findSubquery, which takes no types argument at all,
so a String-typed set clears the gate and builds ASCII probes against the 16
stored bytes:

    SELECT count() FROM t WHERE ip IN (SELECT '2001:db8::')

returned 0 where the oracle returns 1, with Granules: 0/64.
use_index_for_in_with_subqueries defaults to true.

Reuse convertConstantToIndexDomain per set row, and decline the whole atom if
any row cannot be represented in the index domain: a partially converted set
would under-approximate membership and could prune a granule that matches. A
String or FixedString domain keeps the previous code path byte for byte, since
there the set's own bytes already are the index encoding.

Also relabel the inverted notEquals test row. Skip index conditions are built
from an ActionsDAGWithInversionPushDown, whose inverse_relations renames
notEquals to equals under a NOT, so NOT (ip != 'lit') is carried by the equals
arm rather than by the notEquals arm. The row is a real carrier and stays; its
name no longer claims to observe something it cannot.
The map-key paths of MergeTreeConditionBloomFilterText::traverseTreeEquals
substitute the serialized map key for the compared value, but the constant
conversion added earlier in this PR was still handed the type of the
comparison's right-hand side. convertFieldToType dispatches on that type, and
it treats a FixedString(16) source as the binary form of an IPv6 address.

So for a mapKeys index over an IPv6-keyed map, WHERE m.`key_<addr>` =
toFixedString(v, 16) decoded the key's ASCII text as an address and probed the
index with the wrong bytes, dropping the matching granule and returning a wrong
result. Any other key-text length hit end of input instead, declined the atom
and silently lost a legitimate prune. A bare string literal happens to share the
key's own type, which is why this was not visible on the spellings already
covered.

Give the conversion the source type of the value it actually converts. The
mapValues sibling keeps the right-hand side's type because it does not
substitute the value. The arrayElement branch already captured the key's type
and now passes it on, although that branch is currently unreachable for an
IPv6-keyed map.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Three review rounds by an independent model that did not write the code, each
followed by a fix round. Round 3 is clean: my own cold re-review found nothing,
and the automated pass returned no findings.

Round 1 — 2 findings, both accepted and fixed

❌ IN with a subquery still probed with foreign bytes. tryPrepareSetBloomFilter
type-gated on the set's element types and then tokenized raw bytes. A literal
tuple set is type-checked by PreparedSets::findTuple and declines, but
findSubquery takes no types, so a String-typed subquery set cleared the gate
and built ASCII probes against 16-byte granules. Measured with the round-0 fix
already present: ip IN ('2001:db8::') gave 1/1 while
ip IN (SELECT '2001:db8::') gave oracle 1 / indexed 0, Granules: 0/64. Same
wrong-results class as the headline bug and inside this change's own changelog
scope, so being pre-existing did not excuse it. Fixed by reusing the same
conversion per set element; one unconvertible element declines the whole atom,
since a partial set would under-approximate membership.

⚠️ The notEquals regression row was a blind oracle: it asserted only
(63, 63), which BoolMask::operator! makes invariant to the patched arm. I
rejected the automated pass's proposal to delete the notEquals conversion
instead: an atom that is unobservable alone is not unobservable in composition.
Strengthening the oracle instead surfaced the real mechanism (below).

Round 2 — 1 finding from my own review, which the automated pass missed

❌ The conversion hint described the compared value while the value being
converted was the map key. The map-subcolumn branch substitutes the serialized
key for the compared value but left the type hint pointing at the right-hand
side, and convertFieldToType dispatches on that hint: a FixedString(16)
source is binary-decoded as an address. On Map(IPv6, ...) with a mapKeys
index and an explicitly typed compared value, a 16-byte key text was decoded
into the wrong bytes, reproducing the exact defect this change claims to fix on
that carrier, and any other key length hit EOF and silently lost a legitimate
prune. Fixed by letting a source type travel with the substituted value. The
mapValues branch correctly keeps the right-hand side's type because it does
not substitute; the latent arrayElement branch had already captured the right
type and discarded it.

Round 2 also closed round 1's second finding. The implementer escalated
rather than guess, and was right to: reverting only the notEquals conversion
left the whole reference byte-identical, while reverting only equals reddened
the row. Skip-index conditions are built from an inversion-pushed-down DAG, and
cloneDAGWithInversionPushDown renames the comparison through
inverse_relations instead of emitting a not, so NOT (ip != lit) arrives as
an equals atom and no spelling routes a notEquals probe into a deciding
position (18 spellings measured). I kept the conversion anyway: the
bloom_filter index converts both directions through one helper and is this
change's cited precedent, the call site is measurably behaviour-neutral today,
and reverting would leave a known-wrong probe guarded only by an accident of
BoolMask. That it is unobservable by any test is stated in the validation
gate rather than glossed over.

💡 Noted, not blocking: three open pull requests now queue on this file
(#112868, #112785, #113022). All are logically independent of this change and
conflict only textually, so whichever lands later re-integrates by hand.

Round 3 — clean. I enumerated the reachable constructions independently
before comparing against the plan and found no divergence. Verified against
source rather than accepted: byte-encoding equivalence on both the aggregator
and probe sides including the LowCardinality path; that the
String/FixedString early return is load-bearing, not an optimization; that
declining is always sound because an unresolved atom evaluates to
keep-the-granule; that the unconverted has/hasAny/hasAll arm is
unreachable because no common supertype exists between String and IPv6; that
the set path uses the element types rather than the key types; that no new throw
is introduced and no on-disk format changes; and that setting randomization
cannot neuter the granule assertions, because EXPLAIN force-disables the two
randomized settings that would matter and the rest only pick the filtering
algorithm.

Gate spend across all rounds: $22.25.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand, no randomization or timing dependency: clickhouse local running the new test's SQL. Confirmed on three independent binaries (pristine master snapshot, a pre-edit build of this tree, and the fixed build).
b Root cause explained? The aggregator tokenizes the indexed column's raw bytes (16 bytes 20010DB800... for IPv6), while traverseTreeEquals gated on the constant's type and tokenized the constant's own bytes (ASCII 2001:db8::). The two encodings share no prefix, so contains() was false and the matching granule was pruned. The query is valid only because the comparison function converts separately at runtime; index analysis had no conversion step (grep -c convertFieldToType on this file was 0).
c Fix matches root cause? Yes. It adds the missing conversion in the function that builds the probe, mirroring the bloom_filter sibling, which already converts and is correct on this query. Not a widened bound, not a no-random-* tag, not a guard at the pruning site. The comparison path is already correct and is untouched.
d Test intent preserved / new tests added? No existing test modified or weakened. One new stateless test with a Log twin oracle, EXPLAIN indexes = 1 granule assertions, a selectivity arm, an unreachable-arm arm, and a String/FixedString no-regression arm. Parallel-safe: no no-parallel, implicit database, no on-disk files.
e Both directions demonstrated? Yes. 26 assertions fail on the pristine master snapshot and on a pre-edit build of this tree, and pass with the fix. Build IDs recorded per arm and verified to differ. Five mutations each redden a distinct assertion group, so no group is vacuous: reverting the whole change reddens groups A, C and F; passing the target type as from_type_hint (a silent no-op) reddens group B only, since the atom then always declines; deleting the String/FixedString early return reddens the FixedString oversize row only; reverting just the set path reddens 5 group F rows and nothing else; making the set conversion decline unconditionally reddens only the group F arm that asserts a non-matching subquery value still prunes.
f Fix is general across code paths? Yes. All three reachable arms of this condition class call the one helper: equals and notEquals in traverseTreeEquals, plus tryPrepareSetBloomFilter, which had the same defect for a set built from a subquery (a literal tuple set is type-checked by PreparedSets::findTuple and declines, but findSubquery takes no types, so a String set reached the raw-byte tokenizer). Siblings enumerated: MergeTreeIndexBloomFilter.cpp already converts at five sites and is the model; MergeTreeIndexText.cpp and MergeTreeIndexConditionText.cpp never convert but their validator rejects IPv6 outright (verified live at DDL, Code: 36), so they are structurally immune rather than missed; KeyCondition already converts. Arms left alone are each verified unreachable for a non-String index domain and pinned by serverError assertions: has/hasAny/hasAll (Code: 386), all mapContains* (a String subcolumn is required), and like/match/hasToken*/startsWith/endsWith/multiSearchAny (Code: 43). Fixed at the probe construction, not at the pruning decision. One stated gap: the notEquals arm's conversion cannot be observed by any test, because skip-index conditions are built from an inversion-pushed-down DAG whose inverse_relations renames notEquals to equals under a NOT, so no spelling routes a notEquals probe into a position where it decides pruning (18 spellings measured, byte-identical with and without that call site). It is kept for consistency with its sibling and is fail-closed, but it rests on code reading rather than on a red-green mutation. The conversion is also given the source type of the value it actually converts: the map-key paths substitute the map key for the compared value, so a local source type travels with the value instead of describing the comparison's right-hand side. Without that, a FixedString(16) right-hand side made convertFieldToType binary-decode a 16-byte map-key text as an address (the same foreign-byte probe) and made any other key length decline and lose a legitimate prune. The mapValues sibling keeps the right-hand side's type because it does not substitute the value, and the latent arrayElement/mapKeys branch is fixed for consistency although it is unreachable for an IPv6-keyed map (ILLEGAL_TYPE_OF_ARGUMENT, re-measured).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, matrix measured. Column wrappers: IPv6 and LowCardinality(IPv6) both tested (getPrimitiveType strips the wrapper); Nullable(IPv6), LowCardinality(Nullable(IPv6)), Array(Nullable(IPv6)), IPv4 and UUID are rejected at DDL. Index types: ngrambf_v1, tokenbf_v1, sparse_grams. Containers: Array(IPv6), Map(IPv6, String) via mapKeys including the map-key subcolumn form, Map(String, IPv6) via mapValues, plus a Map(String, String) and Array(String) regression check. Spellings: compressed, fully expanded, uppercase, ::1, ::, and the v4-mapped and bare-v4 pair that collapse to one value. Boundaries: all-zero default, unparseable literal, and a FixedString constant shorter than, equal to and wider than the column width. For the set arm: a single-element subquery set, a multi-element set, a non-matching element (which must still prune), and NOT IN; if any element cannot be represented the whole atom declines, which is the fail-closed boundary. Compared-value types on the map-key paths: a bare literal (a String, which coincides with the key's own type), a FixedString(16) (which is what a binary address decode is keyed on), and a FixedString(8) (not address width, so unaffected); each is paired with a 16-byte and a non-16-byte key text, and the key-text lengths are asserted with length() in the test rather than counted by eye. Two carriers were outside the original scope and are broken the same way on master and fixed by the same change: the map-key subcolumn form, and IN with a subquery.
h Backward compatible? Yes. No new setting, so no SettingsChangesHistory.cpp entry is needed. No serialization or on-disk format change: granule bytes are untouched and only the probe changes, so existing indexes remain valid and do not need rebuilding, because the aggregator was always right and the query side was wrong. Strictly more rows are returned where rows were previously dropped; no query that worked before now fails.
i Invariants and contracts preserved? The probe-encoding invariant (probe bytes must come from the same encoding the aggregator tokenized) is now enforced rather than assumed. Fail-closed on every path: an empty Field from tryConvertFieldToType and a false return from tryInsert both decline the atom, which yields a full scan and a correct answer; neither throws. No new throw is introduced, and the pre-existing CANNOT_PARSE_IPV6 from the comparison function is unchanged (verified in three shapes: primary key pruned, not pruned, and on the Log twin). I grepped the suite: no test asserts that error from an index-analysis path. Zero behavior change on the String/FixedString domain, guaranteed by the early return and asserted by the no-regression arm plus its mutation. Analysis-time only: one conversion and one single-row column per constant per index, replacing one safeGet<String>; no per-row cost.

Session id: cron:clickhouse-review-slot-50:20260803-152300

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @rschu1ze, could you review this? Index analysis for the ngrambf_v1/tokenbf_v1/sparse_grams condition never converted the constant into the indexed column's type, so on an IPv6 column a string literal was tokenized as ASCII while the granule holds the 16 raw bytes, and the matching granule was pruned; the fix adds the conversion the bloom_filter sibling already does.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b263dfc]

Summary: ✅


AI Review

Summary

This PR fixes a real wrong-results bug in ngrambf_v1, tokenbf_v1, and sparse_grams skip-index analysis for IPv6 comparisons against string literals by re-encoding the probe into the indexed domain before tokenization. The current head also covers the two follow-up cases raised in prior inline review (IPv6StringToNum(...) / FixedString(16) constants and missing-key comparisons through mapValues(...)), and I did not find a remaining correctness, coverage, or PR-metadata issue in the current diff.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit b263dfc.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 85/91 (93.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9f6a640

No failures to own on this commit: 157 success, 18 skipped, 0 failures out of 175 check-runs.
Finish Workflow succeeded, and no check is queued or in progress.

Session id: cron:our-pr-ci-monitor:20260804-000000

@rschu1ze

Copy link
Copy Markdown
Member

@groeneai

cc @al13n321 @rschu1ze, could you review this? Index analysis for the ngrambf_v1/tokenbf_v1/sparse_grams condition never converted the constant into the indexed column's type, so on an IPv6 column a string literal was tokenized as ASCII while the granule holds the 16 raw bytes, and the matching granule was pruned; the fix adds the conversion the bloom_filter sibling already does.

This is complete gibberish. Please post a minimal reproducible example, otherwise we will need to close this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Sorry, that was unreadable. Minimal repro, on master:

CREATE TABLE t (ip IPv6, INDEX idx ip TYPE ngrambf_v1(3, 512, 3, 0))
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('2001:db8::');

SELECT count() FROM t WHERE ip = '2001:db8::';
-- 0, wrong

SELECT count() FROM t WHERE ip = '2001:db8::' SETTINGS ignore_data_skipping_indices = 'idx';
-- 1, correct

The row is there, the index drops it.

Cause: the index stores the address as its 16 raw bytes, but index analysis searched the
index for the bytes of the text 2001:db8::, found nothing, and skipped the granule.
ip = toIPv6('2001:db8::') is unaffected. tokenbf_v1 and sparse_grams behave the same
way, as does ip IN (SELECT '2001:db8::').

The fix makes index analysis convert the constant to the column type first, which is what
the bloom_filter index already does.

I am simplifying the test down to this repro plus a few representative cases, and dropping
the long comments and the "log twin" wording. Will push shortly.

Per review feedback, reduce 04716 from 170 to 54 SQL lines (58 to 18 reference
lines): lead with the minimal reproducer, drop the exhaustive wrapper and
spelling matrix, shorten the comments and remove the "log twin" wording. The
oracle is now the same query with the index ignored, so no second table engine
is needed.

Every remaining assertion is kept because a mutation reddens it, so the reduction
did not create a vacuous check:
  - reverting the conversion reddens the equals and per-index-type rows
  - making the helper always decline fails the first assertion
  - deleting the String/FixedString early return reddens the FixedString row
  - passing the compared value's type as the hint reddens the map-key row
  - reverting the set path reddens the IN-subquery rows

Positive queries use force_data_skipping_indices so that an atom which silently
declines is an error rather than a full scan, and the IN set has a multi-element
arm whose matching address is not first, so converting only the first element
fails. 50 of 50 runs pass under CI randomization.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2e6c6f1

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
Stress test (amd_asan_ubsan) / Hung check failed, possible deadlock found deadlock, pre-existing on master #113692 (mine, open)
Stress test (amd_asan_ubsan) / Sanitizer (STID: 2064-22d0) LeakSanitizer, 59520 bytes indirect, 0 direct #113953 (mine, merged) - not in this build, see below
Sync - CH Inc sync (private, not actionable)

The LeakSanitizer red is the Context::createCopy indirect-leak family. Its fix merged on
2026-08-09, and the GitHub compare API reports this head as diverged from that merge commit, so
this build predates the fix rather than failing with it present. It will be picked up on the next
rebase.

Neither red is caused by this diff, which touches only
src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp plus its own test.
Build (arm_release) / Post Hooks also appears as a failed row in the CI database, but that
check's own conclusion is success - bookkeeping noise, so I have not ledgered it.

Session id: cron:our-pr-ci-monitor:20260810-193000

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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
Conflicts in MergeTreeIndexBloomFilterText.cpp, both regions this branch
touches, against three master changes that landed since the last push:
FixedString padding stripping (ClickHouse#117314), the LIKE unknown-backslash-escape
decline, and FixedString padding stripping for set elements.

Resolution keeps both sides:

* traverseTreeEquals: the constant is first padding-stripped by master's
  rule, then const_source_type tracks the type of whatever value survives,
  so the conversion into the index domain sees the same value the scan
  compares. The LIKE escape decline runs after both, unchanged.

* tryPrepareSetBloomFilter: a set element on a non-string index domain is
  re-encoded, as before; every other element keeps master's path including
  the padding strip. A padded FixedString element on a non-string domain
  fails to convert and declines the atom, which costs pruning and cannot
  lose rows.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b263dfc4c with master 3805e83de (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

3 object files changed (+26.63 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp.o 257.99 KiB 284.60 KiB +26.61 KiB (+10.31%)

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

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

Job report

`WHERE ip = IPv6StringToNum('2001:db8::')` compares an `IPv6` column with a
`FixedString(16)` constant. Index analysis takes the constant's terms from the
value string comparison sees, which drops the trailing zero bytes, and then
converts that value into the index domain. Deserializing an `IPv6` from the 4
remaining bytes fails, so the atom declined: the skip index stopped being used
for a spelling that worked before, and `force_data_skipping_indices` became
`INDEX_NOT_USED`.

Zero-extend such a constant back to its declared width before converting.
Measured on a one-row table, the atom now probes the index and finds the row;
without the change the same query fails under
`force_data_skipping_indices = 'idx'`.
A key a row does not have reads as the map value type's default, and a
`mapValues` index holds only the values that are present, so such a comparison
cannot use the index. The existing guard compares the constant against the
compared expression's type default, which is the map value type only for a
string valued map: on `Map(String, IPv6)` the literal `'::'` is a `String`,
whose default is `''`, so the guard did not fire.

Before the conversion this PR adds, the atom tokenized the literal text, and
`ngrambf_v1(3, ...)` produces no ngram at all from a two byte constant, so the
probe was empty and the granule survived by accident. Converting the constant
into the index domain turns `'::'` into the 16 zero bytes of the address, and
the probe then misses every granule whose map values hold no run of three zero
bytes, dropping a row the predicate matches.

Measured on a one row `Map(String, IPv6)` table with a `mapValues(m)`
`ngrambf_v1` index over `2001:db8:1:2:3:4:5:6`: `WHERE m['missing'] = '::'`
returns 1 on master, 0 on the previous head of this PR, and 1 again here,
against an oracle of 1. The same shape on a `mapKeys` index is wrong on master
as well and needs the map value type, which is not available there, so it is
left alone. Reported by an automated review comment.

@alexey-milovidov alexey-milovidov 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.

Thanks for the clear explanation!

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 7884c95 Sep 23, 2026
174 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

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

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed: this one is real, not a false positive. The BAD_GET comes from the map value default gate I added in this PR (constantIsIndexDomainDefault calling safeGet<String> on an array needle), and it reproduces on master today for ngrambf_v1, tokenbf_v1 and sparse_grams.

Measurements, the exact carrier set, and the fix PR link are on #121729.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
ClickHouse#113157 landed on master and rewrote the same map branches of
traverseTreeEquals, so the two changes conflicted textually while staying
disjoint in purpose.

ClickHouse#113157 converts a constant into the index domain and threads
const_source_type through the map branches, then declines the index when a
map element is compared against the map value type default and the granule
is probed through a mapValues index. Its own commit message records that the
same shape on a mapKeys index stays wrong because the map value type is not
available there, which is what this branch fixes.

The resolution keeps both sides. const_source_type is still assigned on
every mapKeys substitution, so convertConstantToIndexDomain keeps converting
the substituted key, and reads_map_element_against_values_index is still set
on both mapValues arms, so the constantIsIndexDomainDefault guard keeps
firing. mapElementDefaultBreaksIndex replaces the two
unwrapped_value_type->getDefault() tests it supersedes, and the array needle
and text comparable key guards of this branch are unchanged.

Measured on the master snapshot that carries ClickHouse#113157 and not this branch, a
mapKeys index still drops matching rows: Map(String, String) with
tokenbf_v1 returns 1 against an oracle of 3, and Map(String, IPv6) with
ngrambf_v1 returns 0 against an oracle of 1.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
The guard declined a mapKeys index whenever the indexed key type was not a
string, on the reasoning that the subcolumn probe searches for the key
serialized as text while the index holds the key column's raw bytes.

ClickHouse#113157 removed that premise. It sets const_source_type to String on the
subcolumn substitution and converts the constant into the index domain before
probing, so the serialized key text is turned back into the key's own
representation and does match. Keeping the guard therefore reverted that
improvement: 04716_text_index_ipv6_string_constant, which ClickHouse#113157 added,
failed with INDEX_NOT_USED on
`m.`key_2001:db8::abcd:1` = 'v'` over Map(IPv6, String).

Removing it does not reintroduce the over-prune this branch fixes, because
mapElementDefaultBreaksIndex still runs on both map branches and is what
declines a comparison the map element default satisfies. Measured on
Map(IPv6, Nullable(String)) with a mapKeys ngrambf_v1 index: an absent key
reads as NULL, `= ''` does not hold for NULL, and the indexed and unindexed
counts agree at 0, while the present key answers 1 either way.

05186's non-String key section asserted the old disposition, so it now states
what the two spellings really do: the subcolumn spelling uses the index, and
the arrayElement spelling still declines because it needs a String,
FixedString or Array key constant.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
The literal pattern branch this PR adds tokenized the substituted key text
directly, while the equality branch converts it into the index domain first.
A map key whose type is not a string is held in the index as its own raw
bytes, so the text probe matched nothing and pruned the granule that holds
the key.

Measured on Map(IPv6, String) with a mapKeys ngrambf_v1 index and the row
map(toIPv6('2001:db8::abcd:1'), 'v'): `LIKE '%v%'` and `match(..., 'v')`
through the key subcolumn returned 0 against an oracle of 1, while `= 'v'`
returned 1. All three return 1 here, `LIKE '%zzz%'` still returns 0, the
index is still accepted under force_data_skipping_indices, and a two granule
table reports SelectedMarks 1 with the index against 2 without, so the probe
still prunes rather than declining.

Only reachable since the map merge dropped the guard that declined every
non-String key for this carrier, which ClickHouse#113157 had already made obsolete for
equality.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
Converting the substituted key covers the atoms that probe the index for the
whole key. The remaining atoms tokenize their needle as a substring or a
token, which describes the key only while the index holds it as text, and
they read const_value after the map branches have replaced it with the
serialized key. On a key type that is not text they therefore probed text
against the key column's raw bytes and pruned the granule holding the key.

Measured on Map(IPv6, String) holding map(toIPv6('2001:db8::abcd:1'), 'vvv')
with a mapKeys ngrambf_v1 index: startsWith, endsWith and hasToken on the key
subcolumn returned 0 against an oracle of 1, as did has('') on a
Map(IPv6, Array(String)) holding ['']. The array needle guard does not cover
has, whose needle is a scalar, and the default guard does not either, because
an empty needle leaves the array default unmatched.

The guard sits before the hasToken and has branches rather than after the
equality ones, because both return early. It keeps every atom for a text key,
so a String keyed map prunes exactly as before, and it exempts the five atoms
that convert, so ClickHouse#113157's equality behaviour and this branch's literal
pattern probe are unchanged. A new atom defaults to declining, which costs
pruning and not correctness.
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-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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

Development

Successfully merging this pull request may close these issues.

6 participants