Repository navigation
Conversation
… 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.
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260801-213001 |
Pre-PR validation gate
What the review rounds changed. Five substantive corrections, each mutation-proven with its own Deliberately not covered. Two cells answer the same on pristine master and are left for their own Sweep and repeats. 931 tests over the membership and Session id: cron:clickhouse-impl-slot-41:20260801-192517 |
|
cc @Ergus @CurtizJ, could you review this? String equality is zero-padded, so |
|
Workflow [PR], commit [2740c26] Summary: ❌
|
| needle_constant_size = needle_data->getDataAt(0).size(); | ||
| } | ||
|
|
||
| auto shortcut = needleMapsToSingleDictionaryValue( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 171/180 (95.00%) · Uncovered code |
CI finish ledger - 80cc124CI is fully finished and there are no failures to own.
174 check-runs: 157 success, 17 skipped, 0 queued/in_progress. Moving to review. Session id: cron:our-pr-ci-monitor:20260802-053000 |
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
…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.
This PR now collides with #114089 - a semantics question I cannot decide myselfThe What this PR does.
Why that breaks the index. With the skip index this PR answers I built the only sound alternative - declining the index for a Those pinned assertions came from my own #112693 and #114089 adopted them unchanged, so the padded The question. Over a variable-width
I would rather not pick. @alexey-milovidov, since #114089 is yours and it adopted my test, which of |
Make array membership functions compare a constant
FixedStringneedle zero-paddedChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
has,indexOf,indexOfAssumeSorted,countEqual,mapContainsKeyandmapContainsValuereturning a wrong result for a constantFixedStringargument. String comparison ignores aFixedString's trailing NUL padding, sotoFixedString('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 inLowCardinality.countEqualunder-counted andindexOfcould return the wrong position. For aLowCardinalityelement, also fixes a constant of a different type matching a value it does not equal (1.5matched1,-1matched255, a non-midnightDateTimematched aDate), and a constantNULLmatching 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 inexecuteString,executeConstand theLowCardinalityshortcut. A wider needle such astoFixedString('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 rowindexOf, both members in one rowThe comparison is now zero-padded in
executeStringandexecuteConst, using the primitive from #104858, which settled these semantics forequals.The
LowCardinalityshortcut 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 aDateTimeat midnight (matches aDate) from one that is not (matches nothing). AFloatelement is refused outright: the lookup is by byte identity while+0.0 = -0.0andNaN != NaN. Declining costs the index-comparison speedup when the needle type differs from the element type, soarray_index_low_cardinality_numbersmay move.Most new assertions carry an inline
arrayExists(x -> x = needle, v)oracle withoptimize_rewrite_array_exists_to_has = 0, so the expected value comes from=. Left for their own PRs: a non-constantFixedStringargument,hasAny/hasAll, abloom_filteror text index hashing only the padded needle, andhas(map, key), which stripsLowCardinalitybefore the shortcut and so follows the plain path.Reference change in
01414_low_cardinality_nullableFour lines move from
1to0:has(u8, -1),has(u16, -1),has(u32, -1)andhas(u64, -1)onArray(LowCardinality(Nullable(UInt8/UInt16/UInt32/UInt64))). Each column stores the wrapped value (255,65535,4294967295,18446744073709551615), for whichx = -1is false, sohasmust not match. Four independent oracles agree on0at every width (arrayExistswith=,arrayFilter,indexOf,countEqual), as does scalar=. The reference recorded the defect. The positive controlhas(u8, 255)still returns1, and theUInt8cell 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-1equals 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]