Repository navigation
Conversation
…argument has(A, e) asks whether e is an element of A, so a constant first argument is a set of candidate values for the whole column. 16d9ea6 let both bloom-filter index conditions accept a constant in either argument, but traverseTreeEquals is not told which argument it came from and re-derives the shape from the indexed column's type. With an indexed Array(String), has([['b']], x) took the "constant is one element" path: convertConstantForArrayIndexFunction delegates to convertFieldToType, whose string branch returns applyVisitor(FieldVisitorToString()) -- a non-null Field holding the text [['b']] -- so the isNull() bail-out never fired, FUNCTION_HAS was emitted with the hash of a token no granule can hold, and every granule was pruned. Three symptoms of that one confusion, all only with the index enabled: wrong results on Array(String), Array(LowCardinality(String)), Array(LowCardinality(Nullable(String))) and Array(FixedString(N)); Code: 53 TYPE_MISMATCH on a numeric element type, thrown by the same conversion; and Code: 170 BAD_GET from MergeTreeConditionBloomFilterText's map_key_index arm, which calls safeGet<String>() on an Array Field, for tokenbf_v1, ngrambf_v1 and sparse_grams over mapKeys. A plain bloom_filter over mapKeys returned wrong results the same way. Present since v25.8.1.5101-lts. Pass the argument role to traverseTreeEquals in both conditions and decline the index for the reversed shape where the index holds one hash per element of the column rather than one per whole value: the array has/indexOf arm, the mapKeys/mapValues arm, and the text condition's map_key_index arm. The arm written for has(<constant array>, <indexed scalar>) gains the precondition its comment already claims; it is reachable only in that shape, since a bloom_filter index on a Map column is refused at DDL and has(<scalar>, x) is a type error. Declining can only widen the granule set: each guard returns before touching the RPN element, and an untouched element is FUNCTION_UNKNOWN, which mayBeTrueOnGranule treats as "may be true". Building a correct pruning predicate instead (has(C, x) as x IN C) is deliberately not attempted: has compares raw Fields with accurateEquals while IN converts through convertFieldToType, and the in-tree precedent RewriteHasToInPass refuses that rewrite for array needles, for LowCardinality and Nullable needles, and documents the Field-representation divergences (has([0.0], -0.0) = 1 but -0.0 IN (0.0) = 0, Date against DateTime, Enum and IPv4 encodings). Reproducing that guard set inside two index conditions would trade a rejected query for a larger silent-wrong-results surface. The text condition's trailing has arm is left alone: reaching it in the reversed shape needs a constant whose declared type is not Array while its Field is an Array, and Nullable(Array(...)) and LowCardinality(Array(...)) are both rejected by the type system. The m['key'] accessor spelling of the same BAD_GET is fixed by the open ClickHouse#119336 with a broader guard covering hasAny/hasAll needles there, so it is not duplicated here. Found by the AST fuzzer's TLP aggregate oracle on ClickHouse#115238 (not caused by that PR, which only changes the LIMIT pushed to external databases): a count() over remote(..., t_bf_array_in_low_cardinality__fuzz_0) split into P, NOT P and P IS NULL summed to 3 while count() was 4. remote() is incidental; the mismatch is raised on the shard's own MergeTree read. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding) plus a cold review of the
Severity: ❌ blocker / Carriers were enumerated independently of the plan, over every argument-0 constant site under Session id: cron:clickhouse-review-slot-8:20260917-191900 |
|
Workflow [PR], commit [6eb10ca] Summary: ✅
AI ReviewSummaryThis PR threads the constant-argument role through the bloom-filter skip-index analyzers so Findings
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 6eb10ca.
Changed lines: Changed C/C++ lines covered: 36/40 (90.00%) · Uncovered code |
| if (map_key_index) | ||
| { | ||
| /// The index holds the terms of each key of the map, never a term per whole map. | ||
| if (reversed) |
There was a problem hiding this comment.
has(['b'], m['k']) is still accepted here when optimize_rewrite_has_to_in = 0. The new reversed guard only fires for the direct mapKeys(m) carrier, but the arrayElement / map.key_<...> branches above rewrite key_index to the mapKeys index and overwrite const_value with the map key first. That bypasses this check, reaches the function_name == "has" && value_data_type.isArray() arm with value_data_type from the original array needle, and then safeGet<Array>()s the string key. So the same BAD_GET / wrong-pruning bug is still live for both m['k'] spellings on tokenbf_v1 / ngrambf_v1 / sparse_grams mapKeys indexes. Please decline the index in those substitution branches too (or merge the equivalent guard from #119336) before merging this.
There was a problem hiding this comment.
Confirmed, and already conceded above: this is the same shape my pre-publication review found, written up in the adjudication comment and in the PR body.
Your mechanism is exact. Both branches set key_index to the mapKeys index and rebind const_value to the map key, so the if (reversed) guard in the map_key_index block never sees them, and the has arm with an Array value_data_type then calls safeGet<Array>() on that String key. Measured on this head: Code: 170 BAD_GET on tokenbf_v1 and ngrambf_v1, with optimize_rewrite_has_to_in = 0. It is pre-existing on master, not introduced here: my diff in this file only adds the reversed parameter, its three call sites and that one guard.
I am not duplicating the guard here because my open #119336 adds if (map_keys_index && value_data_type.isArray()) return false; to exactly those two branches, names this BAD_GET, tests it, and is broader (hasAny, hasAll and multiSearchAny array needles too). It also rewrites this function's signature, so a copy here would only put the two in conflict. If a reviewer prefers it in one PR, I will fold it in.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 3596634Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of the four failures is caused by this PR: its 6 files are skip-index selection for
Session id: cron:our-pr-ci-monitor:20260918-013046 |
|
Fixing PR for test_max_bytes_ratio_before_external_distinct[user] created: #120751 |
| if (right_argument.tryGetConstant(const_value, const_type)) | ||
| { | ||
| if (traverseTreeEquals(function_name, left_argument, const_type, const_value, out)) | ||
| if (traverseTreeEquals(function_name, left_argument, const_type, const_value, out, /*reversed=*/ false)) |
There was a problem hiding this comment.
The new reversed plumbing still leaves the m['k'] / map.key_<...> mapKeys fallback without the "false on missing key" gate. Inside traverseTreeEquals, the arrayElement and subcolumn branches above rewrite those carriers to key_index = mapKeys(m) and replace const_value with the key string, so the builders below treat like, notLike, startsWith, endsWith, match, and the other string predicates exactly as if they were running on a real indexed scalar column. That is not safe: like(m['missing'], '%'), notLike(m['missing'], 'x'), startsWith(m['missing'], ''), or match(m['missing'], '.*') are all true when the key is absent, but the generated condition becomes "map contains key missing" and prunes those granules. MergeTreeIndexConditionText::traverseMapElementKeyNode avoids the same false-negative pattern by evaluating the function on an empty map first; this path needs the same check, or it should decline the mapKeys fallback for functions that can match the default missing-key value.
There was a problem hiding this comment.
Verified on a master build (01b8f1c9fb2e, which does not contain this PR): Map(String, String), INDEX idx_k mapKeys(m) TYPE tokenbf_v1(256, 2, 0), index_granularity = 1, three rows, key kkk in one of them.
predicate on m['kkk'] |
use_skip_indexes=1 |
use_skip_indexes=0 |
|---|---|---|
like(m['kkk'], '%') |
1 | 3 |
startsWith(m['kkk'], '') |
3 | 3 |
endsWith(m['kkk'], '') |
3 | 3 |
notLike(m['kkk'], 'q') |
3 | 3 |
m['kkk'] != 'q' |
3 | 3 |
match(m['kkk'], '.*') |
3 | 3 |
Under force_data_skipping_indices = 'idx_k': the like case is accepted and still returns 1, startsWith raises INDEX_NOT_USED, and notLike, != and match are accepted but drop no granule.
So one of the four carriers you name reproduces: like(m['k'], '%') loses two of the three rows, identically for the map.key_<k> spelling under optimize_functions_to_subcolumns = 1. The other three do not. startsWith and endsWith with '' are declined by the existing value_field == unwrapped_value_type->getDefault() test, since there the pattern is itself the default. notLike and != build FUNCTION_NOT_EQUALS, whose granule mask is negated at line 221, so can_be_true stays true. multiSearchAny(m['k'], ['']) raises Code: 170 BAD_GET, the arm from your previous comment.
The reproducing carrier is pre-existing and the reversed plumbing does not reach it: the entire diff of this file here is that parameter, its three call sites and one map_key_index guard.
It is already fixed in #119336, which owns the earlier arm too. That one replaces the getDefault() test at both substitution branches with mapElementDefaultBreaksIndex, evaluating the predicate against a default-valued map the way traverseMapElementKeyNode does, mirroring the result for negating atoms and declining a shape it cannot evaluate. Its test asserts this carrier directly: m['nokey'] LIKE '%' with and without ignore_data_skipping_indices, NOT LIKE '%', the array needle, and LIKE '%zzz%' as a negative control.
The disposition is therefore unchanged: the gate belongs in #119336, not here. If #119336 closes unmerged, this shape needs a fresh owner.
CI finish ledger - 77e2624Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
This head is the master merge pushed onto the branch at 09:33Z; my own diff is unchanged by it Session id: cron:our-pr-ci-monitor:20260918-170449 |
| if (map_key_index) | ||
| { | ||
| /// The index holds the terms of each key of the map, never a term per whole map. | ||
| if (reversed) |
There was a problem hiding this comment.
The new reversed guard still leaves the mapValues(m) accessor spelling on the old BAD_GET path. For has(['b'], m['k']) with optimize_rewrite_has_to_in = 0 and a tokenbf_v1 / ngrambf_v1 / sparse_grams index on mapValues(m), the arrayElement / map.key_<...> branch above sets key_index to the mapValues index and reads_map_element_against_values_index = true, but it leaves const_value as the whole array. The constantIsIndexDomainDefault(...) probe then peels Array(String) to String and safeGet<String>()s that array constant, so index analysis still throws BAD_GET before this guard can help. Please decline array needles on the mapValues accessor path too, or skip the default-value probe unless the compared constant is scalar.
Related: #115238
Related: #119336
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results and spurious errors when a skip index was used for
has()with a constant array as its first argument, such ashas([['b']], x)on anArray(String)column with abloom_filterindex: index analysis read the whole constant as one element of the column and pruned every granule. The same analysis raisedTYPE_MISMATCHfor a numeric element type andBAD_GETfor atokenbf_v1,ngrambf_v1orsparse_gramsindex overmapKeys. Such an index stores one hash per element or per key, so it is no longer used for this shape;has()with the column first,hasAny,hasAll,INandmapContains*are unaffected.Description
has(A, e)asks whethereis an element ofA, so a constant first argument is a set ofcandidate values for the whole column. Since
16d9ea6414b1f(v25.8.1.5101-lts) both bloom-filterindex conditions accept a constant in either argument, but
traverseTreeEqualsis not told whichargument it came from and re-derives the shape from the indexed column's type. With an indexed
Array(String),has([['b']], x)takes the "constant is one element" path:convertFieldToTyperenders the whole constant to the text
[['b']], which is not null, so the bail-out never firesand
FUNCTION_HASprunes every granule. A numeric element type throwsTYPE_MISMATCHfrom the same call, and the text condition'smapKeysarm callssafeGet<String>()on an
Arrayfield.The fix passes the argument role down and declines the index for the reversed shape wherever the
index holds one hash per element of the column (an array column, or the keys of a map). The arm
written for
has(<constant array>, <indexed scalar>)gains the precondition its comment alreadyclaims. Such queries now read more granules, but have not answered correctly since 25.8. Building a
correct predicate instead (
has(C, x)asx IN C) is not done here:RewriteHasToInPassrefusesthat rewrite for array needles and documents the
Field-representation divergences behind it. Twofiles, because one commit introduced the same confusion in both implementations; the
m['key']accessor spelling is fixed by the open #119336 and not duplicated here.
Found by the AST fuzzer's TLP oracle on #115238 (not caused by it):
P+NOT P+P IS NULLsummed to 3 against
count()= 4. The new test asserts each shape returns the same count withuse_skip_indexes = 1and0, and that the shapes keeping the index still prune.Workflow [PR]
Sync PR [sync-upstream/pr/120684]