Repository navigation
Conversation
…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.
Internal second-model review (click to expand)This change was reviewed by an independent model pass before publication, plus a separate cold code
The final review pass raised no blockers and no majors, and the independent model pass returned no One finding is real but deliberately not fixed here. The Also verified against source and found accurate, so no action: every coercion claim in the added |
Pre-PR validation gate (click to expand)
Twenty-eight mutation arms back the assertions; each reddens a disjoint predicted subset, and the three Session id: cron:clickhouse-review-slot-48:20260731-010800 |
|
cc @shankar-iyer @CurtizJ, could you review this? Index analysis converted the query constant with |
|
Workflow [PR], commit [57b2b8a] Summary: ✅
AI ReviewSummaryThis PR fixes Final Verdict✅ No findings. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 75/85 (88.24%) · Uncovered code |
CI finish ledger - 57b2b8aNo failures to own: 174 checks reported, 156 success, 18 skipped, 0 failure at any depth. The 18 skipped are the normal gated set for a MergeTree-plus-stateless-test diff, not jobs Session id: cron:our-pr-ci-monitor:20260805-043000 |
|
Correcting one scope claim I made in gate row (f) above, now that I have measured the I stated the follow-up shape is Five arms diverge there in total ( |
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]>
|
Closing: this is superseded by #114089, which landed the same fix on Checked while resolving this branch's conflict with
Reopen if you find a case the merged fix gets wrong - that would be a bug report against |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
hasAny,hasAll,hasandindexOfreturning too few rows, or failing withTOO_LARGE_STRING_SIZE, when abloom_filterindex is queried with aFixedStringconstant. 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_filterskip index silently returns too few rows for a plainSELECTwhen the constant is aFixedString, and in four cases raisesCode: 131 TOO_LARGE_STRING_SIZEon a query that succeedswithout the index. No unusual setting is required.
Root cause:
traverseTreeEqualsconverts the constant withconvertFieldToType, aField-levelconversion that pads a
Stringshorter thanFixedString(N)and passes an oversized one throughunchanged. The array-search functions instead coerce with
castColumn, and aFixedStringtoStringcast strips trailing zero bytes. The index therefore hashed a value the function nevercompares, the hash missed, and the granule was pruned. The
TOO_LARGE_STRING_SIZEcases are the samecause: an oversized
Fieldreachesinsertinside 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:
hasandindexOfover a bareStringelement compare the padded bytesand are left untouched, a
LowCardinalityelement casts straight to the dictionary type, andeverything else routes through
getLeastSupertype. Where a constant has no representation in theelement domain the index declines, so a runtime
TOO_LARGE_STRING_SIZEstays reachable instead ofbecoming a silent
0. The sharedcreateColumnFromConstantArrayis deliberately unchanged: thehas(<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 answeragainst 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))andArray(LowCardinality(FixedString(N)))timeshas,indexOf,hasAny,hasAlltimes four constant widths is measured wrong before and correct after, on twoindependent binaries. Both directions through the test runner: the fixed build passes, the
origin/masterbuild 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/64or3/64. Twenty-eight mutation arms each redden a disjoint predicted subset; three reddenednothing 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.