Skip to content

Make array membership functions compare a constant FixedString needle zero-padded - #112953

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-array-membership-fixedstring-zero-padded
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-array-membership-fixedstring-zero-padded

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Make array membership functions compare a constant FixedString needle zero-padded

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 has, indexOf, indexOfAssumeSorted, countEqual, mapContainsKey and mapContainsValue returning a wrong result for a constant FixedString argument. String comparison ignores a FixedString's trailing NUL padding, so toFixedString('V0', 3) equals both 'V0' and 'V0\0', but these functions matched only one of them, and which one depended on whether the element type was wrapped in LowCardinality. countEqual under-counted and indexOf could return the wrong position. For a LowCardinality element, also fixes a constant of a different type matching a value it does not equal (1.5 matched 1, -1 matched 255, a non-midnight DateTime matched a Date), and a constant NULL matching the dictionary's default value.

Description

String equality is zero-padded, so toFixedString('V0', 3) equals both 'V0' and 'V0\0'. These functions reduced the needle to one exact value and matched only the member equal to it, differently in executeString, executeConst and the LowCardinality shortcut. A wider needle such as toFixedString('V0', 5) dropped every row. Rows ['V0'], ['V0\0'], ['X']:

Array(String) Array(LowCardinality(String)) =
has [1] [0] [0,1]
countEqual, both members in one row 1 1 2
indexOf, both members in one row 2 1 1

The comparison is now zero-padded in executeString and executeConst, using the primitive from #104858, which settled these semantics for equals.

The LowCardinality shortcut resolves the needle to one dictionary index and compares indices, so it now runs only when the needle provably denotes a single element value: the width relation for the string family, otherwise a cast round trip back to the needle's own type, separating a DateTime at midnight (matches a Date) from one that is not (matches nothing). A Float element is refused outright: the lookup is by byte identity while +0.0 = -0.0 and NaN != NaN. Declining costs the index-comparison speedup when the needle type differs from the element type, so array_index_low_cardinality_numbers may move.

Most new assertions carry an inline arrayExists(x -> x = needle, v) oracle with optimize_rewrite_array_exists_to_has = 0, so the expected value comes from =. Left for their own PRs: a non-constant FixedString argument, hasAny/hasAll, a bloom_filter or text index hashing only the padded needle, and has(map, key), which strips LowCardinality before the shortcut and so follows the plain path.

Reference change in 01414_low_cardinality_nullable

Four lines move from 1 to 0: has(u8, -1), has(u16, -1), has(u32, -1) and has(u64, -1) on Array(LowCardinality(Nullable(UInt8/UInt16/UInt32/UInt64))). Each column stores the wrapped value (255, 65535, 4294967295, 18446744073709551615), for which x = -1 is false, so has must not match. Four independent oracles agree on 0 at every width (arrayExists with =, arrayFilter, indexOf, countEqual), as does scalar =. The reference recorded the defect. The positive control has(u8, 255) still returns 1, and the UInt8 cell is now pinned against both its = oracle and its plain-array control in the new test.

A negative needle still matches an unsigned element in the plain Array(UInt32/UInt64) spelling, which has no dictionary and so reaches the integral comparison directly; that comparison suppresses -Wsign-compare, so -1 equals its unsigned twin at widths 32 and 64. That is a separate pre-existing defect, measured identical before and after this change, and left for its own PR.


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

groeneai and others added 12 commits July 30, 2026 23:27
… functions

String-family equality ignores a `FixedString`'s trailing NUL padding, so
`toFixedString('V0', 3)` equals both `'V0'` and `'V0\0'`: the needle denotes an
equivalence class rather than a single value. `has`, `indexOf`, `countEqual`,
`mapContainsKey` and `mapContainsValue` instead reduced the needle to one exact
value and matched only the class member equal to it, and which member survived
depended on the dispatch path:

* `executeString` passed the constant's raw bytes to the non-padded
  `memequalSmallAllowOverflow15`, so the padded member won;
* `executeArrayLowCardinality` cast `FixedString` to `String`, which strips
  trailing NULs, and then took a single `getOrFindValueIndex` hit, so the
  unpadded member won;
* `executeConst` compared `Field`s, and `Field` has no `FixedString`, so the
  padding was compared as data.

Adding a `LowCardinality` wrapper therefore changed which row a predicate
matched, `countEqual` under-counted, `indexOf` could return the wrong position,
a wider needle such as `toFixedString('V0', 5)` dropped every matching row, and
`Array(LowCardinality(FixedString(3)))` with that needle threw
`TOO_LARGE_STRING_SIZE` on a query `=` answers correctly.

Make the comparison zero-padded in `executeString` and `executeConst`, reusing
the primitive and the rationale from ClickHouse#104858, which settled these semantics for
`equals`, `less` and `isDistinctFrom`. Because the `LowCardinality` shortcut
resolves the needle to one dictionary index, it now runs only when the needle
provably denotes a single element value. That guard is an allow-list rather than
a check that the cast preserves the value: the dictionary looks up by byte
identity, which is not equality for floating point, where `+0.0` and `-0.0`
compare equal with different bytes and `NaN` compares unequal with equal bytes.
With a same-type `Float64` needle the cast is the identity, yet the lookup both
missed rows a `0.0` needle must match and invented a `NaN` match. A needle of a
wider type could also be rounded onto a stored value, so
`has(Array(LowCardinality(Int64)), 1.5)` matched `1`.

Two lines of `01414_low_cardinality_nullable.reference` change because they
recorded the defect: `has(u8, -1)` and `has(u16, -1)` over columns holding `255`
and `65535`, for which `x = -1` is false. The plain arrays, `arrayFilter`,
`hasAny` and the scalar comparison all already answered 0 there.

The new test asserts every membership answer equal to
`arrayExists(x -> x = needle, v)` evaluated with
`optimize_rewrite_array_exists_to_has = 0`, so the oracle is `=` itself and
cannot be produced by the code under test. `hasAny` and `hasAll` have a separate
implementation and are left for a follow-up change.
The changelog names both functions, but the test only covered `has(Map, ...)`,
which takes a different path: `executeMap` strips `LowCardinality` before
dispatch, so it can never reach the guarded dictionary shortcut. The two map
APIs go through `FunctionMapToArrayAdapter` with
`MapToSubcolumnAdapter::preserve_low_cardinality` false, and
`useDefaultImplementationForLowCardinalityColumns` forwards `false` as well, so
they arrive with `LowCardinality` intact and do reach it. They also select a
different tuple element from each other, leaving the key and value sides
independently uncovered, and `mapContainsValue` had no `FixedString` coverage
anywhere in the tree.

Add a value-side fixture and four rows, each asserted equal to
`arrayExists(x -> x = needle, mapKeys(m))` or the same over `mapValues(m)`, so
the oracle remains `=` itself. All four differ on an unmodified master build
(`[1]`, `[0]`, `[1]`, `[0]` against `[0,1]`), and forcing the guard to accept
every needle reddens exactly the two `LowCardinality` rows while leaving the two
plain `Map` rows green, which is what shows they reach the guard rather than
repeating the `has(Map, ...)` coverage.

Co-Authored-By: Claude Fable 5 <[email protected]>
Test-only follow-up to the array-membership zero-padded comparison fix. No
source change: the shipping binary is byte-identical.

indexOfAssumeSorted is the sixth SQL-reachable FunctionArrayIndex
instantiation, and its answer is changed by this branch. The new zero-padded
branch in executeConst precedes the IndexOfAssumeSorted lowerBound
specialisation, so a constant array with a constant FixedString needle now
takes the linear scan, which is correct because ordering under zero-padded
comparison need not match the order the binary search assumes. That behaviour
change was previously unasserted: no in-tree test combined the function with a
FixedString needle. Three rows are added to the existing constant-array block.
On an unmodified build the two FixedString rows read 2 and 0 against an oracle
of 1; a String-needle row is retained as a must-not-regress control for the
binary search, and it is identical on both builds. The position oracle is
arrayFirstIndex, which lives in a different translation unit that does not
include arrayIndex.h and is rewritten by no optimizer pass, so it cannot be
produced by the code under test. The array is in ascending bytewise order, so
the function's sorted precondition holds and no unspecified behaviour is
pinned.

The two mapContainsKey rows added in the previous round did not execute
mapContainsKey. FunctionToSubcolumnsPass rewrites it to has(map.keys, needle),
optimize_functions_to_subcolumns defaults to true and StorageMemory supports
subcolumns, so those rows exercised the array path over a subcolumn that
happens to retain LowCardinality. There is no such rewrite for
mapContainsValue, so only the key side was affected. Two rows are added with a
per-statement optimize_functions_to_subcolumns = 0 to reach the adapter's key
position, keeping the default spelling as separate coverage of the rewritten
path. Verified with EXPLAIN QUERY TREE: the default rows resolve to has over
map.keys, the new rows keep mapContainsKey over the Map column.

Both new row groups are measured per row on an unmodified build and all four
differ there, so none merely restates a contract that already held. Two
mutations, each predicted before running, both matched: deleting only the
zero-padded branch reddens exactly the two indexOfAssumeSorted FixedString rows
and leaves the String-needle control green; forcing the LowCardinality guard to
accept every needle reddens exactly the three LowCardinality Map rows and
leaves the three plain rows green. Restoring the source relinked bit-identically
to the shipping build.
A constant nullable needle arrives as Const(Nullable(T)). The dispatch check
in executeArrayImpl looks for a bare ColumnNullable, so it does not see
through the ColumnConst, and useDefaultImplementationForNulls is false for
these functions, so nothing unwraps it either. The string handlers then
decline, because checkAndGetColumnConstStringOrFixedString requires the
constant's data column to be ColumnString or ColumnFixedString, and control
falls through to executeGeneric. There getLeastSupertype(String,
FixedString(N)) is String and the cast strips the trailing NUL padding, so a
Nullable(FixedString) needle was compared unpadded while the equivalent
non-nullable needle was compared zero-padded.

The two arguments are documented as identical up to nullability, both in the
type-check error text and in allowArguments, which calls removeNullable on
each side. Peel the Nullable off the constant so the handlers receive the
shape they already treat correctly. An all-NULL needle is left alone, since
executeNothing answers it.

Measured over rows ['V0'], ['V0\0'], ['X'] with a Nullable(FixedString(3))
needle: has now matches both class members instead of one, on Array(String),
Array(LowCardinality(String)), Array(Nullable(String)) and
Array(LowCardinality(Nullable(String))); countEqual goes from 1 to 2 and
indexOf reports the first member. The peel is at the dispatch boundary, so it
reaches every instantiation: mapContainsKey, mapContainsValue,
indexOfAssumeSorted and countEqual with a wider needle all move to their
element-wise equality oracle. A Nullable(String) needle is unchanged, which
the new control row pins.

Also assert the per-row comparison in the constant-array handler, which the
existing rows cannot reach: they all pass a constant needle and take the
single linear scan instead.
The previous commit unwrapped a constant `Nullable(T)` membership needle for
every `T`. For a numeric `T` that moved the needle off the supertype cast in
`executeGeneric` and onto `executeIntegral`, whose comparison is a raw
`left[i] == right` with `-Wsign-compare` suppressed. C++ usual arithmetic
conversions then equate a negative signed value with its unsigned bit-pattern
twin, so `has(Array(Int32) storing [1, -1], CAST(4294967295 AS Nullable(UInt32)))`
answered 1 where `=` answers 0. The same peel also removed a NO_COMMON_TYPE
refusal at 64 bits, replacing a loud error with a silently wrong answer.

The peel exists only to preserve a `FixedString` layout, so gate it on the
needle being string-family, which is the set `needsZeroPaddedComparison` is
defined over. `Nullable(String)` stays inside the gate, so the exact-comparison
row it protects is unaffected.

Verified against the pristine master snapshot: all seven numeric cells return
to their pre-patch values, `Date`/`UUID`/`IPv4`/`Decimal64` nullable needles
are unchanged, and every row of 04657 stays fixed. Removing the gate reddens
exactly the new numeric rows and the three restored throws, and no string row.

Co-Authored-By: Claude Fable 5 <[email protected]>
Two of the four `mapContainsKey` rows relied on the ambient value of
`optimize_functions_to_subcolumns`, which `tests/clickhouse-test` randomizes. On roughly half of
all runs they therefore executed the same Map-to-array adapter path as the two `no-subcolumns`
rows below them, so the file asserted one path twice instead of two paths once and the four-row
structure its own comment promises silently collapsed to two. Nothing failed, because the
rewrite's destination `has(m.keys, ...)` and the un-rewritten `mapContainsKey` return the same
answer; only coverage was lost.

Pin those two rows to 1 with a statement-level clause, mirroring the `= 0` form two lines below,
and add four rows that assert the plan SHAPE rather than the answer, so a rewrite that stops
firing can no longer pass unnoticed. `EXPLAIN QUERY TREE` throws NOT_IMPLEMENTED under the old
analyzer, so `enable_analyzer` is pinned on the outer query; a subquery may not change it.

The rows key on `function_name: mapContainsKey` rather than the bare function name, which still
appears at 1 in the projection display name.

Also add one control row covering the single wrapper and needle combination that both takes the
LowCardinality dictionary shortcut and passes through the Nullable peel. Measured identical on
master and on this branch, and labelled a control rather than coverage of the fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
… non-nullable dictionary

`dictionaryIndexForConstant` answers a NULL needle by returning index 0 and success, and
`executeArrayLowCardinality` then compares dictionary indices with no null maps, under the
assumption that index 0 is always the NULL slot.

That assumption holds only for a nullable dictionary. In `ColumnUnique`, `numSpecialValues`
is 1 when `!is_nullable`, the constructor pre-seeds index 0 by cloning the type's default
value, `getDefaultValueIndex` returns 0 unconditionally, and `getNullValueIndex` throws
unless the dictionary is nullable. So for a non-nullable `LowCardinality(FixedString(N))` or
`LowCardinality(String)`, index 0 holds the zero-filled or empty string, and a NULL needle
matched every row containing that default value, returning 1 where both `=` and the
equivalent plain array answer 0.

Decline the shortcut for a NULL needle unless the dictionary is nullable. The needle then
falls through to `executeNothing`, which matches only genuinely NULL elements. The check
lives at this one call site rather than in `dictionaryIndexForConstant`, whose NULL contract
other callers rely on, and outside `needleMapsToSingleDictionaryValue`, which answers a
question about types only while nullness is a property of the value.

The defect predates this branch: master reaches `dictionaryIndexForConstant` with no gate at
all and answers 1 on the same fixture.

Also correct the neighbouring control comment in the test, which said that case passes
through the Nullable peel. It does not: the dictionary shortcut returns a column before
`executeArrayImpl` is entered, so it bypasses the peel.
…erage

Two of the test's assertions could not distinguish "the fix works" from "the
mechanism never ran".

The pair asserting that rewriting arrayExists to has preserves results compares
one query at optimize_rewrite_array_exists_to_has = 1 and at 0. The rewrite has
six silent decline gates, and a cross String/FixedString pair survives the last
of them only because tryGetLeastSupertype(String, FixedString) is String. If it
declined, both sides would be byte-identical and each row would read 1 for the
wrong reason. Two rows now pin the plan shape instead, keying on
function_name: has and function_name: arrayExists in EXPLAIN QUERY TREE. Making
the visitor decline unconditionally reddens the new row and leaves the two
agreement rows green, which is what shows they were blind to it.

The NULL needle block called only has, although the LowCardinality dictionary
shortcut it exercises is shared by every action except indexOfAssumeSorted, and
is also reached by mapContainsValue and by mapContainsKey with the subcolumn
rewrite off. Six rows extend the block to indexOf, countEqual and both Map entry
points; a position and a count over the default valued rows say more than a
boolean. Removing the guard reddens all six.

The must not regress row for the guard's nullability test used a bare NULL, which
is typed Nullable(Nothing) and is therefore refused one line later by the type
allow list, so it exercised the allow list rather than the guard. It is kept with
a corrected comment, and three rows with a typed NULL on a nullable dictionary
are added: those pass the allow list and reach the guard. Their oracle is
arrayExists(x -> isNull(x), v) rather than an equality lambda, because
equals(NULL, NULL) is NULL and arrayExists treats a non true value as false, so
an equality lambda answers the empty set for every array; ArrayExistsToHasPass
documents that asymmetry and skips the rewrite because of it.

Measured on a pre guard and a post guard build, each asserting its served
buildId() against its own ELF build id: six rows move and five are identical,
including all three typed NULL rows. Dropping only the nullability term of the
guard changes no answer, so that term is a performance guard rather than a
correctness one, and the typed NULL rows are controls that the shortcut keeps
answering. 50/50 with the randomizer live passes 100 of 100 with no tag added.
…alue-preserving

The previous round made the dictionary shortcut decline whenever the needle type
did not provably denote a single element value. For two families the resulting
fall-through is less correct than the shortcut was, because the handler that
catches it is not equality-correct.

A `String` needle at most as wide as a `FixedString` element is padded up to the
element width by the cast the lookup performs, which is exact, so it does denote
one value; declining sent it to `executeGeneric`, whose `FixedString -> String`
cast strips the trailing NULs and then compares exactly, losing the match. Admit
such a needle by its measured byte length, and keep declining a longer one.

A needle of a different type is now admitted when converting it into the element
type preserves its value, decided on the actual constant instead of by type
identity. The test is a round trip: a single cast cannot report that it lost
anything, since casting a non-midnight `DateTime` to `Date` truncates the time of
day and succeeds. A float element is still refused outright, because the
dictionary is looked up by bytes and that is not float equality; a float needle
against a non-float element is fine once it converts exactly. This restores the
`Int64`/`Float64` precision boundary and the `Date`/`DateTime` midnight cell, and
additionally makes a non-midnight needle agree with `=`.

Also narrow an over-claiming comment on the typed-NULL rows: they assert the
result only, since whether the shortcut or the `executeNothing` fallback produced
it is not observable from SQL.
The LowCardinality dictionary shortcut declined for two different kinds of
reason and reported both the same way, by falling back. One of them is a
positive result about the value: when the round trip proves the needle lies
outside the image of the element type, no element can equal it. Falling back
handed such a pair to executeIntegral, which compares raw physical numbers,
so a Date day number matched a DateTime epoch second with the same physical
value even though the two instants differ. The reason is now three-valued and
only a shape decline falls back.

A NULL needle carries no value, so the round trip inspects the nested column's
placeholder rather than the needle. On a nullable dictionary index 0 is the
NULL slot and the lookup is the right answer, so that verdict is never read as
"no element can equal it".

The needle's byte-length read peeled only Nullable while the type test next to
it normalises through recursiveRemoveLowCardinality, so the same bytes were
admitted as a String needle and declined as a LowCardinality(String) one. It
now normalises the same way. Resolving the value through the dictionary by
hand would not work: dictionary position 0 is the type's default, not the
constant's value.

The value round trip also swallowed every exception from its own cast, turning
a memory limit or a logical error into "the needle does not convert". Only the
conversion refusals the cast can legitimately raise are accepted now; the rest
propagate. The one refusal reachable in practice is nan or inf against an
integral element, where the plain array already answered 0 and only the
LowCardinality spelling raised an error.

Two rows of 01414 change from 1 to 0. The unsigned columns hold the wrapped
value, which does not equal -1, and arrayExists, arrayFilter, indexOf and
countEqual all agree with the new answer.
… value

The dictionary shortcut declines a needle whose cast into the element type
does not come back unchanged, and reported every such decline as a positive
result about the value: no element of that type can equal the needle, so the
answer is a zero-filled column.

That reading only holds while the cast is one that could have accepted some
other value of the same type. It does not hold when the type PAIR has no
conversion at all, because then the probe never got as far as asking about
the value. IPv4 and UInt8 have a common supertype, so getReturnType accepts
the query and executeGeneric compares them correctly, but neither direction
has a direct cast, so has, indexOf, countEqual and both Map spellings
answered 0 where the element-wise = answers 1 and the plain array matches.
Both directions of the pair are affected by different routes: IPv4 -> UInt8
throws, while UInt32 -> IPv4 has a plain cast and it is the accurate way back
that refuses, returning NULL.

The two facts cannot be separated by error code, because FunctionsConversion
raises CANNOT_CONVERT_TYPE for an unsupported pair and for a genuine value
refusal such as nan -> Int64 alike. So the round trip now reports whether it
completed with a different value or was refused, and a refusal is classified
by re-running it on the needle type's own default value: a cast that takes
the default but not this needle is answering about the value, while one that
refuses both is refusing the pair, which falls back to the general path. The
second trip runs only for a needle that already failed the first one.

Co-Authored-By: Claude Opus <[email protected]>
…mment

Round 11 of review is prose only: no executable statement, no test row and
neither .reference file changes, so the compiled result is unchanged.

Every comment block added by this PR is brought down to at most three lines,
in all three touched files (32 oversized added blocks before, 0 after).
Rationale is moved rather than deleted: invariants a future editor could
break silently stay at their call sites, while call chains, worked byte
examples, source citations and reconstructed history are dropped because the
PR description already carries them or the code re-derives them.

Verified behaviourally inert: the diff against the previous commit contains
only comment and blank lines, the error-code list is unchanged, and both
04657 and 01414 pass on the rebuilt binary with their references untouched.
@groeneai

groeneai commented Aug 1, 2026

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

Before opening this PR I reviewed the diff with an independent second model on every revision, plus
my own cold read of the resulting code each time, and adjudicated every finding against the source.
Eleven fix rounds. Findings that changed the shipped behaviour are listed first; each was reproduced
on the pre-fix binary and mutation-proven on the fixed one before being accepted.

# Sev Finding Verdict Evidence / action
1 ❌ A typed NULL needle on a NON-nullable dictionary matched every row holding the element type's default value. dictionaryIndexForConstant answers a NULL needle with index 0, which is the NULL slot only when the dictionary is nullable; otherwise index 0 is the default. AGREE, fixed Such a needle now falls through to executeNothing. Asserted for LowCardinality(FixedString(3)) and LowCardinality(String) with has, indexOf and countEqual, each with a non-LowCardinality control.
2 ❌ The dictionary shortcut read an unsupported type PAIR as a fact about the VALUE, answering 0 where = answers 1. IPv4 against UInt8 has no direct cast either way, yet the pair has a common supertype, so the query is accepted and the general path compares it correctly. AGREE, fixed The decline is now three-valued: re-running the round trip on the needle type's own DEFAULT separates "this value is outside the element type" from "this pair does not convert". Both cast directions asserted, 8 cells; reverting this alone reddens exactly those 8 and leaves every nan/inf and temporal cell green.
3 ❌ A cast refusal was reported as a shape decline, letting control reach executeIntegral, whose comparison is by raw physical number: a Date day number then matched an equal DateTime epoch second. AGREE, fixed Value-loss now yields a zero-filled column instead. Pinned with colliding values (day 1 against second 1); the earlier 3600-second rows are kept as the non-collision control, since they would have passed for a reason unrelated to the guard.
4 ❌ The needle's byte-length read did not peel LowCardinality, so the very same three bytes were admitted as a String needle and declined as a LowCardinality(String) one. That is the same wrapper-changes-the-answer defect this PR exists to remove. AGREE, fixed The length is read through recursiveRemoveLowCardinality plus a Nullable peel, matching the wrappers the type side strips. Both wrapper orders asserted.
5 ❌ A constant Nullable needle arrived as Const(Nullable(T)), which no handler recognizes, so it fell through to executeGeneric and lost the FixedString layout. AGREE, fixed Peeled at the executeArrayImpl dispatch boundary, string family only: a peeled numeric needle would reach executeIntegral and equate a negative signed value with its unsigned twin. That restriction is itself asserted with Int32/UInt32 rows.
6 ❌ indexOfAssumeSorted changed behaviour unannounced and unasserted: the zero-padded branch precedes the binary-search branch, so a constant FixedString needle now takes the linear scan. AGREE, fixed Correct outcome (order under zero-padded comparison need not match the order lowerBound assumes), but it shipped unlisted. The changelog entry names the function and both cases are pinned, with String and numeric needles as must-not-regress controls.
7 ❌ Two mapContainsKey rows did not execute mapContainsKey: optimize_functions_to_subcolumns defaults to 1 and rewrites it into has(m.keys, x), which strips the wrapper. The rows exercised the array path, not the Map adapter they were added for. AGREE, fixed Confirmed with EXPLAIN QUERY TREE. Key rows now run both at the default and with the rewrite disabled, and four plan rows pin that the rewrite really is on at 1 and off at 0, so the pair cannot pass vacuously.
8 ❌ The value probe's catch was too broad: any exception was read as the cast declining, so a memory limit or a logical error would have been silently turned into an answer. AGREE, fixed Narrowed to a measured list of conversion-refusal codes, each raised by an actual CAST of a plausible needle; anything else rethrows.
9 ⚠️ Array(Dynamic) membership also disagrees with =, raised as a blocker for this PR. DISAGREE Real, and worse than the case fixed here, but pre-existing and untouched. Measured on both arms with each binary's buildId() asserted against its own ELF note: byte-identical before and after, while an Array(String) control in the same run moved as intended. The predicate keys on a statically declared String/FixedString, which a Dynamic column declares neither of. Array(Variant(...)) with a FixedString needle is rejected at type-check, so Dynamic is the family's only type-erasing carrier. Tracked separately rather than widening this PR.
10 ⚠️ Retain the dictionary fast path for constants that are exactly representable, to avoid the measured slowdown. DISAGREE That is the value-preservation predicate an earlier round and a mutation test both refuted: the dictionary looks up by BYTE identity, which is not equality for floating point, so has(v, 0.0) misses -0.0 rows and a NaN needle invents a match. Adopting it buys the speed back by reintroducing wrong results. The cost is disclosed instead: about 14 to 19 percent on a constant type-mismatched needle, same-type string benchmarks unchanged within 1.3 percent, and only constant-needle queries can move at all.
11 ⚠️ Added comment blocks exceeded the repository's 3-line ceiling (32 blocks, longest 18 lines). AGREE, fixed Rationale MOVED rather than deleted: every non-re-derivable invariant is kept at its call site, while call chains, worked byte examples and reconstructed history were cut. Census by longest-consecutive-added-run: 32 oversized blocks before, 0 after, longest added run now 3.
12 💡 A non-constant FixedString needle, and an Array(FixedString(N)) with a NUL-tailed String needle, still compare unpadded. AGREE, disclosed One shared cause: getLeastSupertype(FixedString(N), String) is String, so the generic path unpads. Fixing either is a type-system change; this PR's contract is scoped to a constant FixedString needle, and the exclusion is stated in the description with the reason.
13 💡 hasAny/hasAll share the defect. AGREE, disclosed Separate implementation in hasAllAny.h, and it throws rather than answering wrongly on numerics. Left for its own PR, one concern per PR.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Two cells deliberately keep an answer that disagrees with their inline = oracle: plain
Array(Int64) with a Float64(2^63) needle, and the wider-String-needle cell. Both reach a path
with no dictionary involved and answer identically on unmodified master, so pinning their current
answers would pin a wrong result; only the LowCardinality rows are asserted, each beside its
plain-array control.

Session id: cron:clickhouse-review-slot-8:20260801-213001

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Question Answer
a Deterministic repro? Yes. One clickhouse local invocation, no server and no skip index: ENGINE = Log rows ['V0'], ['V0\0'], ['X'], needle toFixedString('V0', 3). has returns [1] on Array(String) and [0] on Array(LowCardinality(String)), while = returns [0,1]. Every run, no randomization.
b Root cause explained? Yes. String equality is zero-padded, so a FixedString needle denotes the class {'V0', 'V0\0', ...} rather than one value. Each path reduced it to one exact value and matched only the member equal to that: executeString used the non-padded memequalSmallAllowOverflow15; the LowCardinality path cast to String, stripping trailing NULs, then took one getOrFindValueIndex hit; executeConst compared Fields, which lack FixedString.
c Fix matches root cause? Yes, at the layer where the comparison happens. executeString and executeConst are made zero-padded; a constant Nullable needle is peeled at the executeArrayImpl dispatch boundary so it reaches those corrected handlers instead of the unpadding executeGeneric; and the dictionary shortcut declines when the needle does not denote a single element value. Two alternatives were refuted: "pick the other branch" (= gives [0,1], so both [1] and [0] are wrong) and declining alone (the fall-through also unpads). No widened bound, no no-random-* tag, no symptom-site guard.
d Test intent preserved / new tests added? New 04657_array_membership_fixed_string_needle.{sql,reference}: 148 labelled assertion rows over 152 reference lines, each against an inline oracle (arrayExists with =, arrayFilter, indexOf, countEqual, arrayFirstIndex, isNull) plus, where the wrapper is the variable under test, its plain-array control. Four lines of 01414_low_cardinality_nullable.reference move 1 to 0 (has(u8, -1), has(u16, -1), has(u32, -1), has(u64, -1)): those columns hold the wrapped value, so x = -1 is false, and four independent oracles plus scalar = agree on 0. The four signed rows beside them (has(i8, -1) through has(i64, -1)) are the positive control and still read 1. The reference had recorded the defect. No test weakened, no tag, nothing skipped.
e Both directions demonstrated? Yes. The new test aborts on an unmodified master build and passes on the fixed build; every row was measured individually on the unmodified build and recorded as live or as a deliberate control. All seven fix components are separately mutation-proven, every mutation predicted in writing before being run, and each reddens ONLY its own cells: reverting the unsupported-pair classification, for instance, reddens the eight IPv4 cells while every nan/inf and temporal cell stays green. Mutations that failed to compile are recorded as such, never as passes; restoring the fix relinked to the verified build with its checksum restored.
f Fix is general across code paths? All four dispatch paths audited plus the dispatch boundary. Three handlers fixed; executeGeneric is byte-identical to master and its exclusion disclosed in the description, its cause being getLeastSupertype(FixedString(N), String) = String, a type-system change. All six FunctionArrayIndex instantiations share the fixed implementation and each is asserted against an independent oracle: has, indexOf, countEqual, indexOfAssumeSorted, mapContainsKey, mapContainsValue. The three reaching it by a different route get their own rows and controls, with the reason recorded there: indexOfAssumeSorted, whose binary search follows the zero-padded branch, and both mapContains* spellings, which keep LowCardinality through the Map adapter unlike has(Map, ...). LowCardinalityExecutionHelpers.h is untouched by design, being shared with consumers that must not inherit it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Elements: String, FixedString(M) for M < N and M >= N, Nullable(String), LowCardinality of String, Nullable(String), FixedString, Float32/Float64, Int64, IPv4, plus Map keys and values. Needles: String, FixedString(M) at M < N, M == N, M > N, NULL bare and typed, same-type and wider-type numerics, Decimal, nan/inf. Boundaries: empty value, one byte, all-NUL, leading NUL, empty array, and needles of exactly 16 and of 15-plus-padding bytes, crossing the SIMD window. Three axes in BOTH directions: needle width against a FixedString element (the wider one must still decline), value-preserving versus lossy casts (Float64/Int64 at 2^53, DateTime/Date at midnight or not), unsupported type pairs (IPv4/UInt8 each way).
h Backward compatible? A bug fix toward the equals semantics already merged in #104858, so no setting default moves and no SettingsChangesHistory.cpp entry is needed. For FixedString needles the new match set is a superset, so rows are gained rather than lost. The two cells that now match less (has(unsigned, negative) and an invented NaN match) dropped answers that =, the plain array, hasAny and arrayFilter already disagreed with. Category Bug Fix (user-visible misbehavior in an official stable release).
i Invariants and contracts preserved? The zero-padded selector is a compile-time template parameter set only on the constant-FixedString branch, so the String-needle and non-const-needle paths generate unchanged code. NULL semantics unchanged: null maps are consulted before any comparison, has(v, NULL) matches master on plain and LowCardinality arrays, the null-map test from #103922 is byte-identical, and a NULL needle is excluded from the "no element can equal it" verdict since it carries no value while on a nullable dictionary index 0 IS the NULL slot. Memory safety: the over-reading SIMD primitive is used only where both operands live in PaddedPODArray, while the Field path uses a non-over-reading comparison since a Field holds a std::string without SIMD padding. The value probe rethrows anything outside the conversion-refusal codes, so a memory limit or a logical error is never read as a non-converting needle. ASAN and UBSAN clean.

What the review rounds changed. Five substantive corrections, each mutation-proven with its own
asserted cells: a NULL needle on a non-nullable dictionary matched every row holding the type's
default; the needle's byte-length read did not peel LowCardinality, so identical bytes were admitted
as a String needle and declined as a LowCardinality(String) one, exactly the defect class this PR
removes; a cast refusal was reported like a shape decline, letting control reach executeIntegral
where a Date day number matched an equal DateTime second, so the decline is now three-valued; the
value probe's catch was narrowed to conversion-refusal codes measured by instrumentation; and an
unsupported type PAIR was read as evidence about the VALUE, answering 0 where = answers 1 for
IPv4/UInt8, both ways.

Deliberately not covered. Two cells answer the same on pristine master and are left for their own
PR, disclosed in the description: plain Array(Int64) with a Float64(2^63) needle, and the
wider-String-needle cell. Both reach a path with no dictionary, so pinning their current answers
would pin a wrong result; only the LowCardinality rows are asserted, each with its control.

Sweep and repeats. 931 tests over the membership and LowCardinality surface, same selection in
both arms, baseline built from this worktree with only arrayIndex.h reverted: BASE 838 OK / 87 FAIL,
FIX 839 OK / 86 FAIL, ran-sets IDENTICAL, 0 regressions, 1 improvement (the new test). 50 repeats
of both tests: 100/100 OK.

Session id: cron:clickhouse-impl-slot-41:20260801-192517

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @CurtizJ, could you review this? String equality is zero-padded, so toFixedString('V0', 3) equals both 'V0' and 'V0\0', but has/indexOf/countEqual reduced the needle to one exact value in each of three handlers, and the LowCardinality dictionary shortcut compared indices for needles that do not denote a single element value, so the answer changed with a wrapper.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2740c26]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04846_bloom_filter_map_keys_values_array_spellings FAIL cidb
04836_bloom_filter_map_fixed_string_constant FAIL cidb
04907_bloom_filter_fixed_string_constant_array_scalar FAIL cidb
04847_bloom_filter_map_has_low_cardinality_key FAIL cidb
04872_bloom_filter_array_fixed_string_pruning FAIL cidb
04654_bloom_filter_array_fixed_string_constant FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 2, 2026
needle_constant_size = needle_data->getDataAt(0).size();
}

auto shortcut = needleMapsToSingleDictionaryValue(

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.

This guard fixes the Array(LowCardinality(...)) path, but direct has(map, key) still never reaches it: executeImpl returns from executeMap before executeArrayLowCardinality, and executeMap adapts the keys to an array and then calls executeArrayImpl on the de-lowcardinalized column. A concrete case is has(Map(LowCardinality(Date), UInt8), toDateTime(1, 'UTC')): it still falls into raw Date/DateTime numeric comparison and reports the 1970-01-02 key as present. The same gap remains for the signed/unsigned mismatch cases you fixed for arrays. The map path needs to feed its adapted arguments back through executeImpl (or otherwise reuse this guard) instead of bypassing it.

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.

The control-flow claim is right and I have added a scope line to the description for it. The causal
claim is wrong, and the difference matters for what a fix would have to do.

executeMap does return before executeArrayLowCardinality, but it is not bypassing the guard: at
its tail it already runs recursiveRemoveLowCardinality over both arguments (pre-existing, byte
identical to the merge base in this PR), so executeArrayImpl sees a plain Array(Date). There is no
dictionary left to shortcut. So has(map, key) does not follow a broken LowCardinality path, it
follows the plain path, and it is wrong there for exactly as long as the plain path is.

That is measurable on your own query. Pristine master and this PR, SET optimize_rewrite_array_exists_to_has = 0 so the oracle is =:

master this PR =
has(Map(LowCardinality(Date), UInt8), toDateTime(1,'UTC')) 1 1 0
has(Map(Date, UInt8), toDateTime(1,'UTC')) 1 1 0
has([toDate('1970-01-02')], toDateTime(1,'UTC')) 1 1 0
has([toLowCardinality(toDate('1970-01-02'))], toDateTime(1,'UTC')) 0 0 0

The map row tracks the plain array row, not the LowCardinality array row, at both arms. Nothing
regressed and nothing was masked; the wrapper is irrelevant to the answer, which is what "it is
de-lowcardinalized first" predicts.

Two corrections to the specifics. Your key 1970-01-02 does not exercise the truncation you describe:
toDateTime(1,'UTC') truncates to day 0, so a day-1 key is a plain type mismatch, not a
collision. The colliding fixture is a day-0 key, and there the guard does fire and this PR fixes
both map spellings: mapContainsKey(map(toLowCardinality(toDate('1970-01-01')), 7), toDateTime(1,'UTC'))
is 1 on master and 0 here. Second, mapContainsKey/mapContainsValue are not executeMap at all;
they are FunctionMapToArrayAdapter, which hands FunctionArrayIndex a real Array(LowCardinality(T))
and so does reach the guard. They are fixed here, including your signed/unsigned case:
mapContainsKey(map(toLowCardinality(toUInt32(4294967295)), 7), -1) and the mapContainsValue mirror
both go 1 to 0, and the FixedString half goes 0 to 1. That is why the changelog names them.

So the changelog is accurate as written and I have not narrowed it. What was genuinely missing was a
statement that bare has with a Map argument is out of scope, and that is now in the description.

The residual is the plain path equating values = says are unequal: a DateTime against a Date,
and -1 against an unsigned element at 32 and 64 bits. That is one defect in
executeIntegral's raw comparison (arrayIndex.h:107-132, -Wsign-compare suppressed, reached
before executeGeneric at :756-760), it predates this PR, and it is already owned separately with a
fix plan that replaces those comparisons with accurate::equalsOp, which is what scalar = uses.
Folding it in here would change executeIntegral for all six instantiations, so it stays its own PR.

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 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: 171/180 (95.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 80cc124

CI is fully finished and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) - -

174 check-runs: 157 success, 17 skipped, 0 queued/in_progress. Config Workflow and
Finish Workflow are both green. CIDB has ingested this commit (322081 rows across 159 distinct
checks) with 0 rows in FAIL/ERROR.

Moving to review.

Session id: cron:our-pr-ci-monitor:20260802-053000

pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Aug 17, 2026
optimize_rewrite_array_exists_to_has, on by default, rewrote
arrayExists(x -> x = c, arr) into has(arr, c) whenever the array element
and the needle had a common supertype. For a string-family pair whose
types differ that supertype exists, but reaching it casts FixedString to
String and strips trailing NULs, while equals compares the two
zero-padded. The same query therefore returned different answers
depending on the setting, and over an Array(LowCardinality(FixedString))
element the rewrite turned a working query into TOO_LARGE_STRING_SIZE.

Measured on released 26.7.4.21 and on master, with v = ['V0'] of type
Array(FixedString(3)): arrayExists(x -> x = 'V0\0', v) answers 1 with the
setting off and 0 with it on, while toFixedString('V0', 3) = 'V0\0' is 1.
The divergence starts once the needle is as wide as the element, not only
when it is wider. Over a constant array a cross-width FixedString pair
diverges too, by a second mechanism: has compares raw Fields, which are
not padded either.

Decline the rewrite when the element and needle are both in the string
family but are not the same type, recursing into tuple elements because
getLeastSupertype recurses into tuples as well and the divergence
reproduces at two nesting levels. Identical types cannot diverge, so
String/String and equal-width FixedString pairs keep the optimization, as
do numeric, Date, Enum, Array and Map elements. This mirrors the NULL
guard already in this pass and the type-equivalence guards in
HasToInPass, and it takes no position on what has() should mean for such
a needle.

Related: ClickHouse#112953
@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
…zero-padded

Resolve the one conflict in executeArrayLowCardinality as the union of both
guards. Master's float-zero decline and this branch's needle-shape classifier
answer different questions and both are kept: the first leaves a zero needle
against a float element to the value-comparing path, the second declines every
needle whose byte identity in the dictionary does not coincide with the element
type's equality.

The two overlap textually only because both end in the same return, and the
float clauses are not redundant either: this branch declines any float element
outright, master's clause additionally covers a float element reached by a
number or Enum needle before the classifier runs.
Both test corrections follow from commits that reached master while this
branch was open, and neither weakens an assertion.

04657 asserted that optimize_rewrite_array_exists_to_has rewrites
arrayExists to has for a FixedString needle over an Array(String) element.
298458b then declined the rewrite for exactly that pair, because
reaching the pair's supertype casts FixedString to String and strips
trailing NULs while equals compares the two zero-padded. The row now pins
the decline. That row exists to keep the two result-preservation rows above
it from comparing a plan against itself, and the decline makes the
FixedString one of those vacuous, so a String needle pair, which the
rewrite still fires for, is pinned beside it and carries that liveness.

04881 recorded a NaN needle and a negative needle against an unsigned
element as answering 1 where the plain-array oracle answers 0, and its own
comment names both as defects the dictionary shortcut produces that a build
which stopped taking the shortcut would move. This branch stops taking it
for both: a float element is refused because the dictionary is looked up by
bytes and NaN is one entry that equals nothing, and a needle no element can
represent answers not-found. Both rows now agree with the oracle beside
them and with scalar equals.
@groeneai

Copy link
Copy Markdown
Collaborator Author

This PR now collides with #114089 - a semantics question I cannot decide myself

The Fast test red at 2740c26b is not stale references. Merging master pulled in #114089
(a4fcc252, cc4ad335), and it standardizes the opposite answer to the question this PR changes.
Six tests fail; I have not touched any of them.

What this PR does. q_str stores 'V0' at id 7 and 'V0\0' at id 11 (Array(String), no index):

binary has(v, toFixedString('V0',3)), no index arrayExists(x -> x = toFixedString('V0',3))
master [11] [7,11]
this PR [7,11] [7,11]

'V0' = toFixedString('V0',3) is 1, so master's has disagrees with = and this PR makes it agree.

Why that breaks the index. With the skip index this PR answers [11] while the same query at
use_skip_indexes=0 answers [7,11] - wrong results, caught by 04872's keyed-vs-unkeyed cells.
And the index cannot be taught the new comparison: toFixedString('V0',3) equals 'V0', 'V0\0',
... 'V0' followed by 20 NULs (measured, all 1), so over a variable-width String element the
matching set is infinite and a bloom filter can hash only finitely many values.

I built the only sound alternative - declining the index for a FixedString needle over a String
element. It fixes the wrong results, and costs pruning: Granules: 64/64 for the FixedString
needle versus 3/64 for the String one. That reddens two more of 04872's cells, and 04872 pins
the padded outcome deliberately: "has over a bare String element keeps hashing the padded form,
so a FixedString(3) constant selects the granule holding 'V0\0' and not the one holding 'V0'."

Those pinned assertions came from my own #112693 and #114089 adopted them unchanged, so the padded
semantics is a reviewed contract, not a test I should quietly update. Same for the seven
-- { serverError TOO_LARGE_STRING_SIZE } arms that now succeed: master throws there today, so the
annotations were correct before this PR.

The question. Over a variable-width String element, should has(v, toFixedString('V0',3)) be

  1. the padded-bytes lookup Fix bloom_filter index skipping granules for a FixedString constant #114089 standardized, which the index can answer - then this PR's
    premise is wrong and I close it; or
  2. value equality with =, which is not indexable - then the index must decline and Fix bloom_filter index skipping granules for a FixedString constant #114089's
    pruning assertions change.

I would rather not pick. @alexey-milovidov, since #114089 is yours and it adopted my test, which of
the two do you want? I have made no code change this round and pushed nothing.

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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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.

2 participants