Repository navigation
Compare array elements accurately in has/indexOf/countEqual - #117313
Conversation
The vectorized numeric path compared an element to the needle with a plain C++ `==` after an implicit cast, with `-Wsign-compare` suppressed. For a mismatched numeric pair that disagrees with `equals`: `-1` wraps to the `UInt64` maximum, and `16777217` rounds to a `Float32`. The constant-array path uses `accurateEquals` and returned the right answer, so the same haystack gave different results depending on whether it was a constant or a materialized column. The default-on `optimize_rewrite_array_exists_to_has` turns `arrayExists(x -> x = c, arr)` into `has(arr, c)`, so a correct predicate became one that returns phantom rows. Both `compare` and `lessOrEqual` now use `accurate::equalsOp`/`greaterOrEqualsOp`, which for a matching pair is the same plain comparison as before. `lessOrEqual` drives the binary search in `lowerBound` and has to stay consistent with `compare`. Closes: #116928
|
Workflow [PR], commit [11744f2] Summary: ✅
AI ReviewSummaryThis PR closes the original Tests
Final VerdictNeeds one more focused regression before merge. LLVM Coverage ReportMeasured on commit 11744f2.
Changed lines: Changed C/C++ lines covered: 42/44 (95.45%) · Uncovered code |
|
Verified the fix reasoning against the
Verified on master and 24.8/25.8/26.8 (all wrong): SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE m (id UInt8, a8 Array(LowCardinality(UInt8)), a64 Array(LowCardinality(UInt64)), af32 Array(LowCardinality(Float32))) ENGINE = MergeTree ORDER BY id;
INSERT INTO m VALUES (1, [255], [18446744073709551615], [16777216]), (2, [5], [5], [5]);
SELECT id FROM m WHERE has(a8, -1); -- row 1, wrong
SELECT id FROM m WHERE has(a64, -1); -- row 1, wrong
SELECT id FROM m WHERE has(af32, 16777217); -- row 1, wrong
SELECT has(materialize([toUInt8(255)]), -1); -- 0, correct (non-LC path)The After this PR merges as-is, the non-LC column path becomes accurate while the LC path keeps the phantoms, so |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+498.85 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units13 translation units recompiled, 93 s compile time in total, 13 of them have a recent master baseline. |
…ionary path `has`/`indexOf`/`countEqual` over an `Array(LowCardinality(T))` column with a constant needle answer from the dictionary index instead of comparing values. `dictionaryIndexForConstant` narrows the constant to the dictionary type with a plain `castColumn`, which wraps `Int8(-1)` into `UInt8(255)` and rounds `16777217` to a `Float32`, and it consulted the accurate `targetTypeRepresentsValue` check only when that cast image collided with the dictionary's default slot. An image colliding with any other entry was answered from `getOrFindValueIndex` with no accuracy check, so the very phantom matches this pull request removes from the vectorized path survived on `LowCardinality` columns, and the default-on `optimize_rewrite_array_exists_to_has` carried them into `arrayExists`. Decline the constant up front whenever a numeric cast could not preserve it: a constant that did not survive the cast equals no element, whichever slot its image happens to hit. The check stays inside the numeric domain, because casting a `String` to a `FixedString` pads it and the padded form is exactly the element the function is meant to match. Closes: #117316
|
🕵 Thanks — all three repros are fixed here in ff39f2b, so #117316 is closed by this pull request rather than left as a follow-up.
The check is deliberately confined to the numeric domain (
The |
…ld one `dictionaryIndexForConstant` answered a `NULL` constant from `dictionary_index = 0` unconditionally, but `ColumnUnique::getNestedTypeDefaultValueIndex` is `is_nullable ? 1 : 0`: slot 0 is the null value only in a nullable dictionary, and in a non-nullable one it holds the nested type's default value. Every element equal to that default was therefore reported as a `NULL`, so `has(materialize(CAST(['', 'a'], 'Array(LowCardinality(String))')), NULL)` returned 1 where the plain `Array(String)` path returns 0. It reached `indexOf` and `countEqual` too: `countEqual(materialize(CAST(['', 'a', ''], 'Array(LowCardinality(String))')), NULL)` counted 2, and the same held for a numeric element type, `has(materialize(CAST([0, 5], 'Array(LowCardinality(UInt8))')), NULL)`. A `NULL` needle is now declined unless `nestedIsNullable`, which leaves a nullable dictionary finding its `NULL` element in slot 0 as before.
…t, at any slot
The accurate `targetTypeRepresentsValue` check ran before the lookup only for a numeric pair, and
after the lookup only when the cast image collided with the dictionary's default-value slot. A cast
loses just as silently outside the numeric domain, and the slot an image lands on says nothing about
whether the constant survived the cast, so
`has(materialize(CAST([toDate('2020-01-01')], 'Array(LowCardinality(Date))')), toDateTime('2020-01-01 00:00:05'))`
was answered from the `2020-01-01` entry while the plain `Array(Date)` path answers 0. `indexOf` and
`countEqual` diverged the same way.
The two checks are now one, run before the lookup for every cast that changes the type, so the
default slot is no longer a special case: it is declined for the same reason as any other.
Padding a `String` to a `FixedString` needs no exception. The two meet as `String`, and the
`FixedString`-to-`String` conversion trims exactly the zero padding the cast added, so
`has(materialize(CAST(['ab'], 'Array(LowCardinality(FixedString(3)))')), 'ab')` still matches, as does
an `Enum8` needle against a `FixedString` element, which meets as `String` too. Both are now in
`05059_array_index_accurate_numeric_comparison`, together with the `Date`/`DateTime` counterexample
and a `Date32` needle that a `Date` element represents exactly and must keep finding.
`04881_low_cardinality_default_value_needle` already drove its `FixedString(4)`-needle and
`Enum8`-needle rows through this same predicate at the default slot, so applying it at every slot
reuses a check those rows exercise.
`has`/`indexOf`/`countEqual` read both sides as the raw numbers they are stored as, and a `Date`
counts days while a `DateTime` counts seconds since the epoch, so an `Array(Date)` holding
`2024-01-01` searched with `toDateTime('2024-01-01 00:00:00')` compared `19723` against
`1704067200` and found nothing. The constant-array path answered the same way, comparing `Field`s
that carry no logical type either. `equals` brings such a pair to the type the two meet in and calls
it equal, and so does `IN`.
The `Array(LowCardinality(Date))` encoding of the same haystack resolves the constant needle by a
cast to the dictionary type and then checks that the constant survived it, which is that same
comparison, so it did find the needle: one haystack answered differently depending on how it was
encoded. It was the paths comparing values that were wrong, not the dictionary shortcut, so
`executeArrayImpl` -- which the constant path, the materialized path and the `Map` path all funnel
into -- now brings a pair whose two sides count different units to the type they meet in before
comparing.
A needle the element does not represent is still found nowhere: `toDateTime('2024-01-01 00:00:05')`
meets an `Array(Date)` holding `2024-01-01` as `DateTime`, where the element is midnight and the
needle is not. `indexOfAssumeSorted` keeps its binary search valid, because the conversion to the
common type is monotonic.
`isTimeOrTime64` was declared for every argument type in `IDataType.h` but defined for none, so the
first caller outside a `WhichDataType` failed to link. It is now defined beside its neighbours.
Addresses #117313 (comment)
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| SELECT countEqual(materialize(CAST([NULL, 'a', NULL], 'Array(LowCardinality(Nullable(String)))')), NULL) AS lc, countEqual(materialize(CAST([NULL, 'a', NULL], 'Array(Nullable(String))')), NULL) AS oracle; | ||
| SELECT indexOf(materialize(CAST(['a', NULL, ''], 'Array(LowCardinality(Nullable(String)))')), '') AS lc, indexOf(materialize(CAST(['a', NULL, ''], 'Array(Nullable(String))')), '') AS oracle; | ||
|
|
||
| SELECT 'a needle counting another unit is compared in the type the pair meets in'; |
There was a problem hiding this comment.
The new mixed-unit branch is broader than the regression block here: executeDifferentDateTimeUnits now also serves Time/Time64 pairs (the new isTimeOrTime64 dependency exists only for that), and the same cast-to-common-type logic is what indexOfAssumeSorted relies on when the pair is temporal. This test only proves has/indexOf/countEqual on Date*/DateTime* arrays, so the epoch-prepending Time semantics and the "conversion is monotonic" claim for sorted arrays are still just asserted in prose. Please add a focused Array(Time/Time64) case and at least one indexOfAssumeSorted mixed-temporal case here.
One conflict, in the `Impl::Main` comparison block of `src/Functions/array/arrayIndex.h`: master's ClickHouse#117313 dropped `constexpr` from `lessOrEqual(PaddedPODArray<Initial>, Result)` because `accurate::greaterOrEqualsOp` is not constexpr, and this branch adds a `compare` overload for a FixedString element against a zero-padded needle immediately above it. Kept both: master's signature and body verbatim, our overload unchanged. The two changes are independent -- ClickHouse#117313 fixes the numeric compare, this branch adds the string-like one -- and `is_zero_padded_needle_v` still excludes the new needle from `lowerBound`, where master's three `lessOrEqual` overloads remain the only ordering comparisons.
That cell asserted `has(v, unhex('6100')) = 1` over an
`Array(LowCardinality(FixedString(4)))` column, which the dictionary shortcut in
`LowCardinalityExecutionHelpers::dictionaryIndexForConstant` answers, not the comparison this
branch adds. Master's ClickHouse#117313 turned that shortcut's representability check from one that only
guarded the default dictionary slot into an unconditional decline, and a String needle whose own
tail is a zero byte does not survive the round trip through `FixedString(N)` that the check
measures: `'a\0'` casts to `'a\0\0\0'` and casts back as `'a'`, since the reverse conversion
trims every trailing zero rather than only the padding it added. So the shortcut now declines and
`has` answers 0 where `=` answers 1, measured identically on a pristine master build and on this
branch: the carrier is master's, not this change's.
The materialized-needle cell stays, as it does reach `executeFixedStringLeft` and does read 1
here against 0 on master.
Master's ClickHouse#117313 landed in the same file and for the same class of defect: it brought `has`/`indexOf`/`countEqual` closer to `equals` for native numbers (`accurate::equalsOp` replacing the hand-rolled comparisons) and for date/time types that count different units (`executeDifferentDateTimeUnits`, hooked at the top of `executeArrayImpl`). Both of its insertion points sit right where this branch adds its own erased-element dispatch, which is why the textual merge could not place them. Resolved as a union, with master's block kept where master put it: the date/time arm stays first after `allowArguments`, this branch's `executeArray` / `executeArrayAfterErasedEquality` / `tryGetDecayedCommonType` and the erased-equality machinery follow, and both new includes are kept. The two arms do not overlap: `dateTimeUnitOf` answers `NotDateTime` for an erased type, so master's arm declines on every shape this branch handles, and the undecided-row fallback still reaches it through `executeArrayAfterErasedEquality`.
Closes: #116928
Closes: #117316
Related: #115311
Related: #103521
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
has,indexOfandcountEqualover an array of numbers returning a match for a needle thatequalsdoes not consider equal —has(arr, -1)matched anArray(UInt64)element equal to theUInt64maximum, andhas(arr, 16777217)matched anArray(Float32)element equal to16777216.The constant-array path already answered correctly, so the same haystack gave different results
depending on whether it was a constant or a materialized column. The same phantom matches were
returned for an
Array(LowCardinality(T))column, where the constant needle is resolved to adictionary index with a narrowing cast. That column also matched a needle its element type cannot
represent outside the numeric domain, such as a
DateTimeneedle carrying a time of day that aDateelement does not, and reported every element equal to the element type's default value as amatch for a
NULLneedle. In the other direction, a needle counting a different unit than theelement -- a
DateTimesearched in anArray(Date), where days were compared against seconds --was found nowhere although
equalsconsiders the pair equal, and although theArray(LowCardinality(Date))encoding of the same haystack did find it; such a pair is now comparedin the type the two meet in.
Description
ArrayIndexNumImpl::comparecompared with a plain C++==after an implicit cast, with-Wsign-compareand-Wdouble-promotionsuppressed. For a mismatched numeric pair that disagreeswith
equals, which compares accurately: the integer side wraps for a sign mismatch, and the integerside rounds for an int-vs-float pair.
The constant path (
linearSearchConst) usesaccurateEqualsonFields and returned the correctanswer, which is what made the two paths of one function disagree — the numeric analogue of #115311.
The default-on
optimize_rewrite_array_exists_to_hasrewritesarrayExists(x -> x = c, arr)intohas(arr, c), so a correct predicate turned into one returning phantom rows. Fixinghasitselfrather than adding another guard to the rewrite pass also closes the constant-vs-column
inconsistency, as the issue notes.
compareandlessOrEqualnow useaccurate::equalsOp/accurate::greaterOrEqualsOp. For amatching pair
accurate::equalsOpisa == b, so nothing changes there;lessOrEqualdrives thebinary search in
lowerBoundand has to stay consistent withcompare. NaN behaviour is unchanged(
nanwas and remains not found).Array(LowCardinality(T))An
Array(LowCardinality(T))column with a constant needle takes a separate fast path(
executeArrayLowCardinality) that compares dictionary indices instead of values, so it neverreaches the code above.
LowCardinalityExecutionHelpers::dictionaryIndexForConstantnarrows theconstant to the dictionary type with a plain
castColumnand consulted the accuratetargetTypeRepresentsValuecheck only when that cast image collided with the dictionary'sdefault-value slot; an image colliding with any other entry was answered from
getOrFindValueIndexwith no accuracy check. So
has(a8, -1)over anArray(LowCardinality(UInt8))holding255keptreturning a phantom row, at every integer width, and for
Float32as well.The constant is now declined up front whenever the cast could not preserve it: a constant that did
not survive the cast equals no element, whichever slot its image happens to hit. The default slot is
no longer a special case — the single pre-lookup check replaces the one that ran only on a
default-slot collision — and the check is not confined to the numeric domain, because a cast loses
just as silently outside it:
has(materialize(CAST([toDate('2020-01-01')], 'Array(LowCardinality(Date))')), toDateTime('2020-01-01 00:00:05'))was answered from the
2020-01-01entry although the needle carries a time of day the element doesnot.
Padding a
Stringto aFixedStringis not such a loss and is not treated as one: the two meet asString, where theFixedString-to-Stringconversion trims exactly the padding the cast added, sohas(Array(LowCardinality(FixedString(3))), 'ab')still matches, as does anEnum8needle against aFixedStringelement, which meets asStringtoo.A
NULLneedleThe same fast path answered a
NULLneedle fromdictionary_index = 0, butColumnUnique::getNestedTypeDefaultValueIndexisis_nullable ? 1 : 0: slot 0 is the null value onlyin a nullable dictionary, and in a non-nullable one it holds the nested type's default value. So
has(materialize(CAST(['', 'a'], 'Array(LowCardinality(String))')), NULL)returned 1 where the plainArray(String)path returns 0,countEqualover['', 'a', '']counted 2, and a numeric elementtype behaved the same. A
NULLneedle is now declined unless the dictionary can hold one.A needle counting another unit
Both paths that compare values read the two sides as the raw numbers they are stored as, and a
Datecounts days while aDateTimecounts seconds since the epoch, sohas(materialize(CAST([toDate('2024-01-01')], 'Array(Date)')), toDateTime('2024-01-01 00:00:00'))compared
19723against1704067200and returned0, as did the constant-array path, whichcompares
Fields that carry no logical type either.equalsbrings such a pair to the type the twomeet in and returns
1, and so doesIN.The
Array(LowCardinality(Date))encoding of the same haystack resolves the constant needle by acast to the dictionary type and then checks that the constant survived it, which is equivalent to
comparing in the type the pair meets in, so that encoding returned
1-- on master as well as here.So it was the paths comparing values that were wrong, not the dictionary shortcut: keeping the pair
on the fallback path would have aligned the shortcut with the wrong answer and regressed it.
executeArrayImplnow brings a pair whose sides count different units -- days, seconds since theepoch, seconds within a day -- to the type they meet in before comparing, and both the constant and
the materialized path funnel into it, so the constant array, the materialized array and the
dictionary now agree, on the answer
equalsgives. A needle the element does not represent is stillfound nowhere:
toDateTime('2024-01-01 00:00:05')meets anArray(Date)holding2024-01-01asDateTime, where the element is midnight and the needle is not.indexOfAssumeSortedkeeps itsbinary search valid, because the conversion to the common type is monotonic.
The two counterexamples in the changelog entry are needles that
equalscalls absent andhascalled present; this is the same defect with the signs reversed, a needle that
equalscalls presentand
hascalled absent.Tests
Test
05059_array_index_accurate_numeric_comparisoncovers both counterexamples on both paths, forhas/indexOf/countEqual, thearrayExistsrewrite, theArray(LowCardinality(UInt8/UInt64/Float32))column, and that matching and cross-width matching pairs still match. It also covers the
Date/DateTimecounterexample beside its plain-array oracle, aDate32needle that aDateelement represents exactly and must keep finding on a non-default slot, the
String-to-FixedStringand
Enum8-to-FixedStringpadding controls, and theNULLneedle over a non-nullable and anullable dictionary. The references of
01414_low_cardinality_nullableand04881_low_cardinality_default_value_needlemove accordingly: both pinned the old phantom answer fora negative needle over an unsigned
LowCardinalityelement, and04881printed it beside theplain-array oracle it now agrees with.
For the needle counting another unit the same test prints the constant array, the materialized array
and the dictionary side by side, with the
equalsandINanswers above them, forhas/indexOf/countEqualoverArray(Date),Array(Date32)andArray(DateTime), in bothdirections, for a non-constant needle, for a
Nullableelement and aNULLneedle, and for theintraday needle that must still be found nowhere. The reference of
03916_has_to_indoes not move --its
Date-versus-DateTimerow is a needle at midnight against an element at12:34:56, sohasis still
0whileinis1and the rewrite still must not fire -- only the comment stating why.Workflow [PR]
Sync PR [sync-upstream/pr/117313]
Version info
26.9.1.839(included in26.9and later)