Skip to content

Fix bloom_filter index skipping granules for a FixedString constant - #112693

Closed
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-array-fixedstring-const
Closed

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-array-fixedstring-const

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixes hasAny, hasAll, has and indexOf returning too few rows, or failing with TOO_LARGE_STRING_SIZE, when a bloom_filter index is queried with a FixedString constant. The index hashed the padded form of the constant while the function compares the unpadded one, so a matching granule was skipped.

Description

A bloom_filter skip index silently returns too few rows for a plain SELECT when the constant is a
FixedString, and in four cases raises Code: 131 TOO_LARGE_STRING_SIZE on a query that succeeds
without the index. No unusual setting is required.

CREATE TABLE k (id UInt64, v Array(String), INDEX idx v TYPE bloom_filter GRANULARITY 1)
ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 1;
INSERT INTO k VALUES (0,['V0']),(1,['V0\0']),(2,['X']);

SELECT count() FROM k WHERE hasAny(v, [toFixedString('V0',3)]);                        -- 0, wrong
SELECT count() FROM k WHERE hasAny(v, [toFixedString('V0',3)]) SETTINGS use_skip_indexes=0; -- 1

Root cause: traverseTreeEquals converts the constant with convertFieldToType, a Field-level
conversion that pads a String shorter than FixedString(N) and passes an oversized one through
unchanged. The array-search functions instead coerce with castColumn, and a FixedString to
String cast strips trailing zero bytes. The index therefore hashed a value the function never
compares, the hash missed, and the granule was pruned. The TOO_LARGE_STRING_SIZE cases are the same
cause: an oversized Field reaches insert inside index analysis.

This teaches the index to coerce the way the executing function coerces, so it stays exact rather than
declining. The mode comes from the raw element type, because the predicates genuinely compare
different representations: has and indexOf over a bare String element compare the padded bytes
and are left untouched, a LowCardinality element casts straight to the dictionary type, and
everything else routes through getLeastSupertype. Where a constant has no representation in the
element domain the index declines, so a runtime TOO_LARGE_STRING_SIZE stays reachable instead of
becoming a silent 0. The shared createColumnFromConstantArray is deliberately unchanged: the
has(<const array>, <indexed scalar>) arm needs the padded form.

Validation

New test 04654_bloom_filter_array_fixed_string_constant, 115 assertions: 83 compare the keyed answer
against an unindexed oracle so no expected value is baked into the reference, 23 assert the plan the
index produces, 8 pin the exact rows it selects, and 1 pins a count directly. Eight cover
multi-element constant arrays, where an element must survive both hops in its own position. Every
reference row answers 1.

An 18-cell defect matrix over Array(String), Array(FixedString(N)),
Array(LowCardinality(String)) and Array(LowCardinality(FixedString(N))) times has, indexOf,
hasAny, hasAll times four constant widths is measured wrong before and correct after, on two
independent binaries. Both directions through the test runner: the fixed build passes, the
origin/master build fails.

Pruning is preserved, which is the point of coercing rather than declining: on a 64-granule fixture
there are zero pruning regressions, 46 cells are byte-identical, and all 18 fixed cells still prune to
1/64 or 3/64. Twenty-eight mutation arms each redden a disjoint predicted subset; three reddened
nothing and are documented rather than presented as passes. A 139-test bloom-filter and skip-index
sweep against two live servers shows zero regressions, and a tag-free 50-run randomized pass is clean.

groeneai and others added 8 commits July 30, 2026 02:38
…ex analysis

MergeTreeIndexConditionBloomFilter::traverseTreeEquals converted the query
constant with convertFieldToType, which is a Field-level conversion: for a
FixedString(N) target it pads a shorter String and passes an oversized one
through unchanged. The array-search functions instead coerce with castColumn,
and a FixedString to String cast strips trailing zero bytes. The index
therefore hashed a value the function never compares, the hash missed, and a
matching granule was pruned. For an element type narrower than the constant the
same unchanged oversized Field reached insert and raised TOO_LARGE_STRING_SIZE
from inside index analysis.

Add a mode-aware helper that reproduces the executing path's coercion, chosen
from the raw element type because the predicates genuinely compare different
representations. has and indexOf over a bare String element take executeString,
which compares the raw padded bytes without coercing, so they keep the existing
conversion. A LowCardinality element casts straight to the dictionary value
type, mirroring dictionaryIndexForConstant. Everything else routes through
getLeastSupertype, which strips the padding and re-encodes into the element
width; a single direct cast is not equivalent, because it rejects a constant
wider than the element before the padding is stripped and so loses pruning the
function does perform. When a constant has no representation in the element
domain the helper declines and the caller skips the index, which keeps a
runtime TOO_LARGE_STRING_SIZE reachable instead of turning it into a silent 0.

The shared createColumnFromConstantArray is left unchanged and a separate
cast-aware builder is added for hasAny and hasAll, because the
has(<const array>, <indexed scalar>) arm executes a Field-level accurateEquals
and needs the padded form. Numeric element types are excluded by an explicit
gate: executeIntegral and executeConst run before executeGeneric, so their
coercion is not the one the helper models.

Only TOO_LARGE_STRING_SIZE is caught, by error code, so a logical error, an
allocation failure or a cancellation still propagates. Cost is one extra
one-row castColumn per constant at index-analysis time, once per query rather
than per granule or per row. The change only widens what is read, so no query
starts returning fewer rows.

Co-Authored-By: Claude Opus 5 <[email protected]>
Review round 1 found that the constant-coercion helper added by this PR threw
BAD_GET instead of declining the index when the query constant was a typed NULL.

castConstantToIndexDomain materialized the constant by stripping Nullable and
LowCardinality from the constant type and inserting the field into a column of
the stripped type. For a NULL field whose type is Nullable(String) or
Nullable(FixedString(N)) that column is the non-nullable inner type, so insert
reached safeGet<String>() on a Null field and threw
"Bad get: has Null, requested String" (BAD_GET). The helper's catch only handles
TOO_LARGE_STRING_SIZE and rethrows, and no caller catches, so the query failed
where master answers it. RPNBuilder keeps the constant type Nullable only when
the value is Null, so that pair is exactly what arrives.

Only the scalar has/indexOf arm was reachable. The hasAny/hasAll arm is safe by
construction because BloomFilter::getPrimitiveType strips Nullable, leaving its
existing null-element test to decline first.

Measured on a 48-cell matrix of four element types times three constant
spellings times four predicates, each cell comparing the keyed answer against an
unindexed oracle: pristine master 0 mismatches, this PR before the fix 12, after
the fix 0. The 12 are has and indexOf over FixedString(3),
LowCardinality(String) and LowCardinality(FixedString(3)) element types with a
Nullable(String) or Nullable(FixedString(3)) constant.

Guard the helper rather than widening the catch, so every current and future
caller funnels through one check and genuine type confusion still surfaces.

Also add the pruning assertions that were missing for
Array(LowCardinality(FixedString(N))). That wrapper had only result comparisons,
which pass identically whether the index coerces the constant or declines
outright, leaving the claim that this fix preserves pruning unmeasured on the one
element type where the two coercion modes could diverge. A 64-granule fixture now
pins all four predicates, and both modes agree at 1/64.

Tests: 04654 grows from 62 to 90 assertions (22 typed-NULL cells, 6 pruning
cells). Removing only the new guard reddens exactly the 12 NULL cells with the
BAD_GET text; forcing that wrapper to decline the index reddens exactly the 4 new
pruning cells while all 8 pre-existing cells stay green.
…vacuous

Review round r2, test-only. No source line changes.

The test header claimed "Every cell asserts keyed == oracle". Classifying all 90
cells gives 68 oracle comparisons, 17 EXPLAIN granule-reduction assertions and 5
absolute-id pins, so the universal clause was false for 22 of them, and because
the file runs under -- { echo } it shipped in the reference too. The header now
names the three assertion classes and keeps the guarantee that actually holds:
every reference row answers 1, so no expected value is baked in.

Ten of the 17 EXPLAIN prune cells asserted only a strict reduction, which a full
prune to 0/64 also satisfies, and they sat on the three fixtures with no other
assertions. Each now carries the same granule lower bound the seven sound cells
already used, so a prune-everything regression cannot read as success.

Measured: reverting the hasAny/hasAll arm to the padded shared helper drives
prune lcstr hasAny FS3 to Granules: 0/64 against 3/64 on the fixed build, and
that cell now reddens where it previously stayed green. Making the coercion
helper always decline reddens 13 of the 17 prune cells; the other four never
reach the helper, taking the bare-String branch, the numeric branch, or the
shared const-array builder. The reference diff contains no result rows.
createColumnFromConstantArrayCastAware called the scalar coercion helper once
per array element, so for every element it allocated a one-row column, re-derived
the stripped source type, re-computed getLeastSupertype from two loop-invariant
arguments, and re-resolved both cast functions. Measured on a 200,000-element
constant array, that added 0.45 seconds of index-analysis time per query.

Do the whole pipeline once for the array instead: build one source column,
compute the common type once, and run the same two castColumn hops over the
whole column. This is also what the function being mirrored does, since
hasAllAny.h resolves the common type once and casts whole argument columns.

Behaviour is unchanged. The element screen still rejects a NULL in a
non-nullable target and a Decimal field before any cast runs, one
unrepresentable element still declines the whole predicate, and the catch still
handles only TOO_LARGE_STRING_SIZE. A 64-cell defect matrix and 64 granule
counts are byte-identical to the per-element form, and the difference-in-
differences planning cost against a String control drops from 0.45 seconds to
within run-to-run noise.

Also reword the catch-block comment. It claimed the executing function raises
the same error on the same input, which does not hold for a nullable dictionary
element: there the runtime casts the constant to a nullable target, so an
over-wide FixedString becomes NULL and the function finds no match instead of
throwing. The comment now states the invariant that does hold, which is that the
constant has no representation in the index domain and the index must decline.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The batched whole-array coercion added in the previous commit was certified only
by single-element measurements: the test's hasAny/hasAll element-count histogram
was {1: 66}, and both offline matrices interpolate one constant. Three
consequences of batching exist only for arrays of two or more elements, and none
was measured: element order and identity across the two cast hops, the
casted->size() != elements.size() and per-index isNullAt guards, and a non-first
element that cannot be re-encoded now declining from the batched catch instead of
a per-element return.

The only pre-existing multi-element coverage of the changed block was
04100_bloom_filter_low_cardinality's hasAny(arr, ['t1','t6']), whose second
element is dead data: its fixture yields only t0..t3, so dropping 't6' cannot
redden the test, and both casts there are String to String identities.

Add a two-elements-per-row fixture and three cells: a non-first-only match, a
hasAll needing both elements, and a later element that does not fit the element
width. On an unpatched server all three raise TOO_LARGE_STRING_SIZE where the
unindexed oracle answers, so they are regression cells. Every constant shares one
width because a mixed-width literal array types as Array(String) and would reach
the coercion with a different element type.

Also wrap literal SQL, type and function names in the comment lines this change
adds inside inline code blocks, per the repository convention. Comments only; the
code with comments stripped is unchanged, and both offline matrices still
reproduce their baselines byte-identically.
The three multi-element cells added previously compare the keyed answer against
an unindexed oracle, so a full scan leaves them green. Index analysis declines by
returning a null column, which changes only the plan, so none of them can observe
a lost multi-element pruning claim. None of the existing granule-reduction cells
uses a constant array with more than one element either.

Add a 64-granule fixture whose matching row carries two elements, reachable only
through the non-first element for hasAny and needing both for hasAll, and assert
the granule reduction for both plus the identity of the surviving granule. On a
decline the Skip block disappears from EXPLAIN and only the primary key row
remains, so the bound fails; a wrong hashed value keeps the count and moves the
granule, so the identity cell catches what a bound cannot.

Also quote literal type, function and identifier names in the test's comments,
which the echo directive copies into the reference twice.

Co-Authored-By: Claude Fable 5 <[email protected]>
…onstant paths

Three test-only additions to the bloom_filter constant-representation test.

Array(LowCardinality(Nullable(...))) was uncovered. It is the one element type
carrying both wrappers, so getPrimitiveType strips both and the raw type is
neither String nor bare LowCardinality: it selects the Direct coercion mode,
which no other cell pinned. bloom_filter accepts it because the array's data
column is a ColumnLowCardinality rather than a ColumnNullable, and two existing
tests already index this exact type. Five of its cells answer 0 or raise
Code 131 on master and are fixed by this change.

The multi-element pruning fixture could not observe a dropped element hash: its
two needles co-occurred on one row, so no row could distinguish them. The rows
now place one needle each on two rows and both on a third, across three
granules, so dropping either hash changes the selected row set.

The scalar unrepresentable-constant path had no cell. A constant that does not
fit the element width even after the padding is stripped must make analysis
decline, because the engine answers that query without any index and a decline
has to leave the answer intact.

Verified with five mutation arms, each reddening only its predicted cells:
dropping the first or the last batched element hash, declining every
multi-element constant array, and making each of the two catches rethrow
independently.
Both unrepresentable-constant cells asserted `count() > 0` over the granule
rows where selected equals total. `EXPLAIN indexes = 1` always emits a
`PrimaryKey` entry with `Granules: 64/64`, so such a row exists whether or not
the skip index declined: the predicate read 1 for the declining `WXYZ` query
and also 1 for the `V0` queries that prune to 3/64 and 1/64. Nothing in the
test could fail if the index hashed the unrepresentable constant and pruned.

Both now assert that the `idx` skip-index block is absent from the plan.
`Name:` is emitted only for a named index and the always-present `PrimaryKey`
entry carries no name, so the tautology cannot recur. Measured 1 for the
declining query and 0 for both pruning queries, identically at
`explain_query_plan_default` legacy and pretty and at `compatibility = 25.1`.

The multi-element case gains a plan cell beside its existing result cell.
That result cell is blind by construction: hashing only the representable
`V0` and dropping `WXYZ` selects exactly the rows `hasAny` returns, so the
answer stays right while the stated contract, that one unrepresentable element
declines the whole predicate, is broken. A mutation keeping a partial hash set
reddens the new cell alone and leaves the result cell green.

Both cells fail on master and pass here: master applies the index to the
scalar query and prunes to 3/64, and raises a logical error on the
multi-element one.

Also qualify the `LowCardinality(Nullable(...))` comment. The coercion mode is
per predicate, not per type: `has` and `indexOf` see the raw `LowCardinality`
and take the direct cast, while `hasAny` and `hasAll` always route through the
common-type hop.
@groeneai

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

This change was reviewed by an independent model pass before publication, plus a separate cold code
review. Findings and their dispositions:

# Finding Verdict
❌ A typed NULL constant made the query throw where master answers it. The new helper inserted the constant into a column of the non-nullable inner type, so a NULL field with a Nullable(String)/Nullable(FixedString) type reached safeGet<String> and raised Code: 170 BAD_GET. The narrow catch handles only TOO_LARGE_STRING_SIZE, and nothing above index analysis catches it. convertFieldToType returns a NULL field unchanged, so master declines instead of throwing, making this a regression introduced by the change rather than a pre-existing defect. Found independently by static trace and by a runtime diagnostic. Fixed. A value_field.isNull() guard now declines in the helper, so both callers are covered. Measured on a 48-cell typed-NULL matrix, each cell compared against an unindexed oracle in its own process: master 0 wrong, the pre-fix revision 12 wrong, now 0. 22 typed-NULL assertions added.
⚠️ No test covered a NULL constant at all, although the design named Nullable as a wrapper to strip. A bare NULL literal would have been vacuous (it is Nullable(Nothing), which the existing gate already declines), so typed nulls were required. Fixed together with the finding above, using CAST(NULL AS Nullable(...)).
⚠️ The LowCardinality(FixedString(N)) pruning claim was unpinned. All eight cells for that wrapper would have passed identically if index analysis had declined for it, yet preserving pruning rather than declining is the whole justification for coercing. Fixed. A 64-granule fixture plus four EXPLAIN cells, one per predicate. All four prune to 1/64 and each selects exactly the expected row, so both coercion modes are pinned on that wrapper.
💡 The test header claimed every cell compares against an oracle, whereas the assertions split into oracle comparisons, plan assertions and row-id pins. Raised independently by the model pass and the cold review. Fixed. Header reworded to describe the assertion classes. The guarantee it was reaching for still holds: every reference row answers 1, so no expected value is baked in.
💡 Most granule-reduction cells asserted only that the selection shrank, with no lower bound, so a prune to zero granules would also have satisfied them. Not an actual coverage hole: the paired oracle cells and the always-decline mutation arm catch both failure directions, verified against the recorded arms. Fixed anyway, since these cells are what a future reader will treat as pinning the pruning claim. They all carry a lower bound now.
❌ Two plan assertions could not detect the failure they exist to catch. EXPLAIN indexes = 1 always emits a PrimaryKey ... Granules: N/N row, so an EXISTS-form selected = total predicate reads true for a pruning plan just as for a declining one. The same blindness applied to the multi-element later-unrepresentable cell, whose result comparison stays green even if analysis silently drops the unrepresentable element and hashes only the valid one, since that selects exactly the rows the runtime returns. Both were green under every mutation except a rethrow, while the stated contract is that analysis declines. Fixed. Both now assert the skip index is absent from the plan, which is what a decline actually looks like, and two new mutation arms pin them: hashing a truncated constant instead of declining, and keeping a partial hash set instead of declining. Each reddens only its own cell while the paired result cells stay green, which is the proof those result cells alone were blind.
💡 A comment described a coercion mode as a property of the element type, but the mode is per-predicate: has and indexOf take the direct cast on a LowCardinality(Nullable(...)) element, while hasAny and hasAll always take the common-type hop. Fixed by qualifying the comment; no cell changed.
💡 Four countable claims in this description were stale or wrong. A per-line recount of the shipped test gives 115 assertions split 83 oracle / 23 plan / 8 row pins / 1 count, against the stated 114 and 22; eight cells cover multi-element constant arrays, not seven; and 28 mutation arms were run, not 22. The multi-element miscount was found only by the recount, not by any review pass. Fixed in the description. Each figure was re-derived from the file that records the measurement rather than from the previous wording.

The final review pass raised no blockers and no majors, and the independent model pass returned no
findings against the published contract.

One finding is real but deliberately not fixed here. The mapContains family reaches the same
index-analysis conversion and mis-hashes a FixedString constant when the map key or value type is
itself FixedString(N), which is a legal type and is already indexed in the test suite. It is a
genuine sibling of this defect, not a false positive: mapContainsKey and mapContainsValue are
built on the same FunctionArrayIndex implementation whose coercion this change corrects. It is
tracked separately rather than folded in, so this pull request stays one fix. The earlier claim that
that arm was verified correct was based on Map(String, ...) keys only, a shape this change would not
affect either way; the scope statement has been corrected.

Also verified against source and found accurate, so no action: every coercion claim in the added
comments (getLeastSupertype plus castColumn for hasAny/hasAll and for the generic
has/indexOf path, a single direct cast for the LowCardinality path); that
TOO_LARGE_STRING_SIZE is the only error code able to escape either cast hop, so the narrow catch is
complete; that the two other deliberately-unchanged arms (has over a constant array, and scalar
equals/notEquals, whose match set is many-to-one so its remedy is to decline instead) still
convert exactly as before; and that no open pull request edits the same lines.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Plain SELECT, no randomization and no forced settings: on a 3-row Array(String) table with a bloom_filter index, hasAny(v, [toFixedString('V0',3)]) answers 0 while the unindexed oracle answers 1. 18 defect cells reproduce identically on two independent binaries (the master snapshot and a fresh origin/master build 333 commits newer).
b Root cause explained? Yes. traverseTreeEquals converts the constant with convertFieldToType, a Field-level conversion that pads a String shorter than FixedString(N) and passes an oversized one through unchanged. The array-search functions instead coerce with castColumn, and a FixedString to String cast strips trailing zero bytes. The index hashed "V0\0" where the function compares "V0", the hash missed, and mayBeTrueOnGranule dropped the granule. The TOO_LARGE_STRING_SIZE cells are the same cause: the oversized Field reaches insert inside index analysis.
c Fix matches root cause? Yes. The index is taught to coerce the way the executing function coerces, at the one place it converts the constant. Not a band-aid: no widened bound, no tag, no reduced dataset, and specifically not the decline-everything guard. M4 measures what declining would cost: 9 live pruning reductions lost while every correctness row stays green.
d Test intent preserved / new tests added? Yes. New 04654_bloom_filter_array_fixed_string_constant with 115 assertions: 83 compare the keyed answer against an unindexed oracle, 23 assert the plan the index produces, 8 pin the exact rows it selects, and 1 pins a count directly, so no expected value is baked into the reference (every reference row answers 1). Among them are 22 typed-NULL cells, 6 LowCardinality(FixedString) pruning cells, and 8 multi-element constant arrays where an element must survive both cast hops in its own position. No existing test weakened or removed; the sweep shows 0 regressions.
e Both directions demonstrated? Yes, through the real runner against two live servers differing only in the binary: the fixed build reports [ OK ], the origin/master build reports Having 1 errors! and aborts on Code 131. Because the runner stops at the first exception, a per-statement pass also drives every row against both servers: 21 rows fail pre-fix and pass post-fix, 35 are unchanged controls.
f Fix is general across code paths? Yes for the array-search arms: one change covers has, indexOf, hasAny and hasAll. Every constant-conversion site in the file was enumerated and classified. IN/NOT IN was already correct precisely because it uses castColumn, which is the in-tree convention this follows. The shared createColumnFromConstantArray is left byte-identical because the has(<const array>, <indexed scalar>) arm needs the padded form, which mutation M6 confirms. Two siblings are deliberately out of scope and stated as such rather than claimed correct: scalar equals/notEquals (its match set is many-to-one, so the remedy is to decline, split to #112639) and mapContains*, whose own coercion runs through the map-access path. Map(String, ...) keys are measured correct there for String, FixedString(3) and FixedString(5) constants; Map(FixedString(N), ...) keys are a legal type sharing this implementation and are left for a follow-up rather than folded in, so this stays one fix per pull request.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The matrix covers String, FixedString(N), LowCardinality(String) and LowCardinality(FixedString(N)) element types, times String and FixedString(M) constants for M < N, M = N and M > N, times four predicates. Nullable and LowCardinality are both stripped from the constant. LowCardinality(Nullable(...)) is the one element type carrying both wrappers and is covered for both coercion modes. Array(Nullable(T)) is not a carrier: BloomFilterHash::unwrapArraySlice raises BAD_ARGUMENTS for a nullable array element while building the index, so no such indexed table can hold data. Numeric elements are excluded by an explicit gate and covered by a control row that still prunes 1/64.
h Backward compatible? Yes. No setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry is due. The behaviour change is strictly in the safe direction: granules that were wrongly skipped are now read and four queries stop failing. No query starts returning fewer rows. Not gated behind a setting, since that would leave the wrong answer reachable by default.
i Invariants and contracts preserved? Yes. The helper is pure and touches no shared state. Only TOO_LARGE_STRING_SIZE is caught, by error code, so LOGICAL_ERROR, OOM and cancellation propagate by construction. A NULL constant is rejected before the wrapper strip, because the strip yields a non-nullable column whose insert would raise BAD_GET; a typed NULL is measured on a 48-cell matrix at 0 of 48 throwing, matching master. On every failure path the helper returns false and the caller declines the index, which is the conservative direction. A runtime TOO_LARGE_STRING_SIZE stays reachable rather than becoming a silent 0, verified post-fix. Cost at index-analysis time is two castColumn hops per predicate, over the whole constant array at once rather than per element, once per query, not per granule or per row. No lock, no hot-loop allocation, no format change.

Twenty-eight mutation arms back the assertions; each reddens a disjoint predicted subset, and the three
that reddened nothing are documented as such rather than presented as passes. Two weak assertions were
found this way and strengthened: one pruning row was being satisfied by a full prune to 0/64, and
the const-array rows did not use the index at all until they were moved to a scalar indexed column.

Session id: cron:clickhouse-review-slot-48:20260731-010800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @CurtizJ, could you review this? Index analysis converted the query constant with convertFieldToType, which pads a short String out to FixedString(N), while the array-search functions coerce with castColumn, whose FixedString to String cast strips trailing zero bytes, so the index hashed a value the function never compares and a matching granule was skipped.

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

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [57b2b8a]

Summary: ✅


AI Review

Summary

This PR fixes bloom_filter predicate analysis for has, indexOf, hasAny, and hasAll when the indexed array side and the query constant differ in String/FixedString representation. The new coercion logic matches the current execution paths for plain String, FixedString, and LowCardinality array elements, preserves conservative decline behavior for unrepresentable constants, and the added stateless coverage plus all-green CI are consistent with the claimed fix. I did not find any new correctness, safety, or coverage gaps in the current patch.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 75/85 (88.24%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 57b2b8a

No failures to own: 174 checks reported, 156 success, 18 skipped, 0 failure at any depth.
Config Workflow, Finish Workflow, Style check, Fast test and all three
Bugfix validation arms are green. Verified two ways - the paginated check-runs API, and the
S3 report result_pr.json walked recursively to every leaf (top status=OK, no non-OK
descendant).

The 18 skipped are the normal gated set for a MergeTree-plus-stateless-test diff, not jobs
dropped by a failure.

Session id: cron:our-pr-ci-monitor:20260805-043000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correcting one scope claim I made in gate row (f) above, now that I have measured the
mapContains* sibling instead of only reading it.

I stated the follow-up shape is Map(FixedString(N), ...) keys. It is wider than that: a
Map(LowCardinality(String), String) key diverges too, with no FixedString anywhere in the
column type. On master f9801d5, mapContainsKey(m, toFixedString('V0', 5)) returns 0 against
an oracle of 1. The LowCardinality wrapper is what matters, because that element casts the
constant straight to the dictionary type and strips the padding, whereas a plain String
element compares the constant's raw padded bytes and is correct. So a fix for that arm cannot
gate on isFixedString() alone.

Five arms diverge there in total (mapKeys + FixedString(N) key, mapValues +
FixedString(N) value, mapKeys + LowCardinality(String) key, an over-wide constant that
should decline rather than silently prune, and both mapContains spellings). It stays out of
scope here. It is also not authorable until the shared coercion helper is settled between this
pull request and #114089, since the map arm is two lines that call whichever helper wins.

alexey-milovidov added a commit that referenced this pull request Aug 15, 2026
The array-search functions coerce a string constant with CAST before
comparing it to the elements: `hasAny`/`hasAll`, and `has`/`indexOf` over
a `FixedString` element, cast both sides to the least supertype, and
`has`/`indexOf` over a `LowCardinality` element cast the constant straight
to the dictionary type. A CAST of `FixedString` to `String` strips the
trailing zero padding, while the index converted the constant with
`convertFieldToType`, which keeps it. The index therefore hashed a value
the function never compares and pruned granules that match, and in four
cases an oversized constant reached a column `insert` during index
analysis and raised `TOO_LARGE_STRING_SIZE` for a query that succeeds
without the index.

Replicate the coercion at the `Field` level: strip the padding of a
`FixedString` constant, re-pad it to the width of the element type, and
decline the index when the constant has no stored representation, so a
runtime `TOO_LARGE_STRING_SIZE` stays reachable instead of becoming a
silent empty result. `has`/`indexOf` over a plain `String` element compare
the constant's raw padded bytes and keep the old conversion, as does
`has(<constant array>, <indexed scalar>)`, whose runtime compares `Field`s
directly.

This is a reimplementation of #112693
with the same semantics; the tests are taken unchanged from that pull request.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@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
@alexey-milovidov

Copy link
Copy Markdown
Member

Closing: this is superseded by #114089, which landed the same fix on master in a4fcc2527d8 under the same title.

Checked while resolving this branch's conflict with master:

  • the source change is redundant: master implements the same coercion, with the helpers named coerceStringFieldLikeSearchFunction, searchFunctionCoercesConstant and convertConstantForArrayIndexFunction instead of this branch's ConstantCoercion, constantCastAppliesToIndexDomain and createColumnFromConstantArrayCastAware;
  • the test coverage is redundant too, and collides by name: master already has 04654_bloom_filter_array_fixed_string_constant, split in 1c53f2b9ea8 into that test plus 04872_bloom_filter_array_fixed_string_pruning to fit the flaky-check time budget. Those two together create exactly the same 24 fixtures as the single test here (k_fs3, k_fs3m, k_lcfs3, k_lcnfs3, k_lcnstr, k_lcstr, k_sc, k_str, the matching o_*/p_* tables and q_str), so nothing here is left uncovered.

Reopen if you find a case the merged fix gets wrong - that would be a bug report against master, not a merge of this branch.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants