Repository navigation
Fix text and token skip indexes over-pruning IPv6 columns - #113157
alexey-milovidov merged 7 commits into
Conversation
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.
Internal second-model review (click to expand)Three review rounds by an independent model that did not write the code, each Round 1 — 2 findings, both accepted and fixed ❌
Round 2 — 1 finding from my own review, which the automated pass missed ❌ The conversion hint described the compared value while the value being Round 2 also closed round 1's second finding. The implementer escalated 💡 Noted, not blocking: three open pull requests now queue on this file Round 3 — clean. I enumerated the reachable constructions independently Gate spend across all rounds: $22.25. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-50:20260803-152300 |
|
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. |
|
Workflow [PR], commit [b263dfc] Summary: ✅
AI ReviewSummaryThis PR fixes a real wrong-results bug in Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit b263dfc.
Changed lines: Changed C/C++ lines covered: 85/91 (93.41%) · Uncovered code |
CI finish ledger - 9f6a640No failures to own on this commit: 157 success, 18 skipped, 0 failures out of 175 check-runs. Session id: cron:our-pr-ci-monitor:20260804-000000 |
This is complete gibberish. Please post a minimal reproducible example, otherwise we will need to close this PR. |
|
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, correctThe row is there, the index drops it. Cause: the index stores the address as its 16 raw bytes, but index analysis searched the The fix makes index analysis convert the constant to the column type first, which is what I am simplifying the test down to this repro plus a few representative cases, and dropping |
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.
CI finish ledger - 2e6c6f1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The LeakSanitizer red is the Neither red is caused by this diff, which touches only Session id: cron:our-pr-ci-monitor:20260810-193000 |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes3 object files changed (+26.63 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline. |
`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
left a comment
There was a problem hiding this comment.
Thanks for the clear explanation!
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
It is used by the constant conversion into the index domain added in master (ClickHouse#113157). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121390&sha=a1baeaacd53eafb1c90d18fed383604ba579c113&name_0=PR ClickHouse#121390 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Confirmed: this one is real, not a false positive. The Measurements, the exact carrier set, and the fix PR link are on #121729. |
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.
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.
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.
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.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
ngrambf_v1,tokenbf_v1andsparse_gramsskip indexes silently dropping matching rows when anIPv6column is compared with a string literal, as inWHERE 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
IPv6column drops the matching row:No forced index or unusual setting.
tokenbf_v1,sparse_grams,LowCardinality(IPv6), the map-key subcolumn form andip IN (SELECT ...)do the same;ip = toIPv6('2001:db8::')is unaffected.Root cause. The index tokenizes the column's raw bytes, for
IPv6the 16 bytes20010DB800..., butMergeTreeConditionBloomFilterText::traverseTreeEqualschecked only the constant's type and tokenized its own bytes, the ASCII2001:db8::. The encodings share nothing, so the filter reported no match and the granule was pruned. Thebloom_filterindex 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
INset 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/FixedStringkeep the old path. A map element compared with the map value type's default declines too: an absent key reads as that default, which amapValuesindex does not hold. Granules are untouched, so existing indexes need no rebuild.Validation.
04716_text_index_ipv6_string_constantuses the index-ignored query as its oracle andforce_data_skipping_indiceson 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
26.10.1.488-master(included in26.10and later)