Skip to content

Do not use a skip index for has(<constant array>, <column>) when it holds per-element hashes - #120684

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-has-const-array-on-indexed-array
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-has-const-array-on-indexed-array

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115238
Related: #119336

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 wrong results and spurious errors when a skip index was used for has() with a constant array as its first argument, such as has([['b']], x) on an Array(String) column with a bloom_filter index: index analysis read the whole constant as one element of the column and pruned every granule. The same analysis raised TYPE_MISMATCH for a numeric element type and BAD_GET for a tokenbf_v1, ngrambf_v1 or sparse_grams index over mapKeys. 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, IN and mapContains* are unaffected.

Description

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. Since 16d9ea6414b1f (v25.8.1.5101-lts) 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) takes the "constant is one element" path: convertFieldToType
renders the whole constant to the text [['b']], which is not null, so the bail-out never fires
and FUNCTION_HAS prunes every granule. A numeric element type throws
TYPE_MISMATCH from the same call, and the text condition's mapKeys arm calls safeGet<String>()
on an Array field.

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 already
claims. Such queries now read more granules, but have not answered correctly since 25.8. Building a
correct predicate instead (has(C, x) as x IN C) is not done here: RewriteHasToInPass refuses
that rewrite for array needles and documents the Field-representation divergences behind it. Two
files, 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 NULL
summed to 3 against count() = 4. The new test asserts each shape returns the same count with
use_skip_indexes = 1 and 0, and that the shapes keeping the index still prune.


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

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
resulting tree by a second reviewer (2 findings). No fix round was needed.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test checks only that the declined shapes return the same count with use_skip_indexes on and off, so an index wrongly accepted for them is not observed directly; add a negative EXPLAIN indexes = 1 or force_data_skipping_indices assertion per guard DISAGREE Each guarded shape already reddens on the unfixed binary: has([['b']], x) = 0 vs 1, mapKeys bloom_filter has([map('b',2)], m) = 0 vs 1, mapKeys tokenbf_v1/ngrambf_v1 = Code: 170 BAD_GET vs 1; whole test, randomization on, 50 runs = 50 errors on the base binary, 50/50 pass on the fix. Asserting the decline itself would pin it as the contract, so a later implementation of correct pruning for this shape (as KeyCondition::tryPrepareSetIndexForHas already does for the primary key) would redden the test for an improvement. The shapes that keep the index do get direct EXPLAIN assertions
2 ⚠️ has(['b'], m['key']) still raises Code: 170 BAD_GET for a tokenbf_v1/ngrambf_v1 mapKeys index: the arrayElement and map-subcolumn blocks rebind the constant to the map key. Same root cause, same file DISAGREE on where it lands, the defect is conceded Reproduced on the base binary for both optimize_functions_to_subcolumns values; it needs optimize_rewrite_has_to_in = 0, unlike the three shapes fixed here. The open #119336 already adds if (map_keys_index && value_data_type.isArray()) return false; to exactly those two blocks, names this BAD_GET, tests it, and is broader (it also covers hasAny/hasAll/multiSearchAny array needles there); it also rewrites both blocks and changes the same function's signature, so a narrower duplicate here would only add a conflict. If #119336 is closed unmerged, this shape needs a fresh owner. Happy to fold the guard in here instead if you prefer it in one PR
3 💡 Of the four touched arms, only two have an in-test pruning assertion, so a guard misplaced in a map arm would silently stop pruning AGREE, noted Bounded rather than fixed: reversed is structurally false for every mapContains* dispatch, and a global inversion of the flag would redden the forward EXPLAIN assertion

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Carriers were enumerated independently of the plan, over every argument-0 constant site under
src/Storages/: KeyCondition pins the roles by position, the text index accepts a left constant
only for equals, the set index executes the real predicate, and the selectivity estimator has no
has analysis, so the two files changed here are the whole carrier set. hasAny stays indexed in
both argument orders because it is symmetric, and the three
03375_bloom_filter_*_has_hasAny_const_array tests still assert its pruning.

Session id: cron:clickhouse-review-slot-8:20260917-191900

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6eb10ca]

Summary: ✅


AI Review

Summary

This PR threads the constant-argument role through the bloom-filter skip-index analyzers so has(<constant array>, <column>) stops reusing per-element or per-key hashes as if they represented whole values. The direct array and direct mapKeys(m) carriers improve, but the current head still leaves map-accessor paths that either raise BAD_GET or prune matching rows, so this is not ready to merge as-is.

Findings
  • ❌ [dismissed by author -- https://github.com/Do not use a skip index for has(<constant array>, <column>) when it holds per-element hashes #120684#discussion_r4041309388] [src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:641-835] has(['b'], m['k']) is still accepted for a mapKeys(m) tokenbf_v1 / ngrambf_v1 / sparse_grams index when optimize_rewrite_has_to_in = 0. The arrayElement / map.key_<...> rewrite overwrites const_value with the map key, but value_data_type still comes from the original array needle, so the later has array branch calls safeGet<Array>() on a String and throws BAD_GET. Suggested fix: decline the mapKeys accessor fallback for array needles, as the direct mapKeys(m) carrier now does.
  • ❌ [dismissed by author -- https://github.com/Do not use a skip index for has(<constant array>, <column>) when it holds per-element hashes #120684#discussion_r4045752559] [src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:641-879] like(m['missing'], '%') is still analyzed as "map contains key missing" on a mapKeys(m) text bloom filter. Missing keys read as the map value type's default, and % matches that default, so pruning granules that do not contain the key still drops rows that satisfy the predicate. Suggested fix: mirror MergeTreeIndexConditionText::traverseMapElementKeyNode and decline the accessor shortcut whenever the predicate can hold on the missing-key default.
  • ❌ [src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp:726] The mapValues(m) accessor path still crashes for constant-first has. For has(['b'], m['k']) with a tokenbf_v1 / ngrambf_v1 / sparse_grams index on mapValues(m) and optimize_rewrite_has_to_in = 0, the accessor rewrite sets key_index to the mapValues index and reads_map_element_against_values_index = true, but leaves const_value as the whole array. constantIsIndexDomainDefault then peels Array(String) to String and safeGet<String>()s that array constant, so index analysis still throws BAD_GET before the new reversed guard runs. Suggested fix: reject array needles on the mapValues accessor path too, or bypass the default-value probe unless the compared constant is scalar.
Tests
  • The new stateless test covers the direct array and direct mapKeys(m) shapes, but it still does not exercise the surviving accessor spellings on text bloom filters: has(['b'], m['k']) on mapKeys(m) and mapValues(m), plus the missing-key LIKE case.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 6eb10ca.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 36/40 (90.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 17, 2026
if (map_key_index)
{
/// The index holds the terms of each key of the map, never a term per whole map.
if (reversed)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. label Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 6eb10ca7336a4419ad221eea94df2a7a43606bde was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3596634

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01414_push_predicate_when_contains_with_clause Master-side, not this diff. The predicate is not pushed into the WITH-clause subquery, so the read is 256 rows instead of 8 and trips the test's own max_rows_to_read guard (Code: 158). The harness reproduced it 3 of 3 reruns. This test is one of the three entries #120477 removed from tests/parallel_replicas_blacklist.txt, and it is failing on true master too (11 master commits) plus 49 distinct PRs since 2026-09-17 19:36Z. #120701 (external, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 03174_exact_rows_before_aggregation Same cause, same lane: rows_before_aggregation reports 10000 instead of 3. The harness re-ran it with and without randomized settings and it failed in both, so it is not randomization dependent. #120701 (external, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 03262_filter_push_down_view Same cause, same lane: index analysis loses the auid in [1, 1] conjunct, so granule pruning degrades from 1/3 to 3/3. Reproduced 3 of 3 reruns. #120701 (external, open)
Integration tests (amd_msan, 1/8) / test_max_bytes_ratio_before_external_order_group_by_for_server/test.py::test_max_bytes_ratio_before_external_distinct[user] Test-harness ordering defect, not this diff. The failing statement is the capability probe is_built_with_thread_sanitizer() at test.py:101, which issues a system.build_options read against the server the test has deliberately memory-starved, so it is refused with Code: 241 MEMORY_LIMIT_EXCEEDED (current RSS: 10.81 GiB, maximum: 10.80 GiB) before the skip guard it exists for can run. 11 distinct carriers over 30 days in unrelated areas, 0 on true master. a fix task is moved to pending (fixing PR link to follow here)
Mergeable Check Praktika rollup over the four rows above, no independent failure #120701 (external, open)
PR Same rollup, no independent failure #120701 (external, open)

None of the four failures is caused by this PR: its 6 files are skip-index selection for
has(<constant array>, <column>), and none of them touches tests/parallel_replicas_blacklist.txt,
this integration test, the memory tracker, or the external-aggregation path.

Finish Workflow, Style check, Fast test, CH Inc sync and both
Bugfix validation (functional tests, *) legs are green on this head: 153 of 173 checks passed and
18 were skipped, including the full build matrix, all 7 AST fuzzer flavours, all 4 BuzzHouse
flavours, and every other Stateless, Integration, Stress, Upgrade and Unit test job.

Session id: cron:our-pr-ci-monitor:20260918-013046

@groeneai

Copy link
Copy Markdown
Collaborator Author

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 77e2624

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
Build profile diff CI infrastructure, not this diff. The job never compared anything: after 716 object files exist only in the warmup baseline, every read of the CI logs cluster timed out (urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='t6h0zvqlgy...clickhouse-staging.com', port=443): Read timed out), five identical tracebacks between 13:01Z and 13:23Z, and the job exited ERROR. The linked PR turns exactly this case (a 5xx or a timeout from that cluster) into a SKIPPED result with the cause reported, instead of failing the check on the cluster's health. #118708 (mine, open)
PR Praktika rollup over the row above, no independent failure #118708 (mine, open)

This head is the master merge pushed onto the branch at 09:33Z; my own diff is unchanged by it
(6 files, +250/-11 against the new merge base). Everything else is green: 156 of 176 checks passed
and 18 were skipped, including Finish Workflow, Mergeable Check, Style check, both Fast test
legs, CH Inc sync, the full build matrix, all 7 AST fuzzer flavours and all 4 BuzzHouse flavours.
The four failures owned in the previous head's ledger are all green here: the three
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, *) tests (the merge picked up
#120763, their master-side owner) and Integration tests (amd_msan, 1/8).

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
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-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants