Repository navigation
Treat a NULL array element as NULL in hasAll, hasAny and hasSubstr - #116239
Conversation
hasAll, hasAny, hasSubstr and the startsWith/endsWith family compared a NULL element of an Array(Nullable(T)) as whatever value was physically stored beneath it, so they disagreed with has() on identical input: hasAll([1, 2, NULL, 4], [0]) returned 1 while has([1, 2, NULL, 4], 0) returned 0. Both wrong-answer directions occurred, and because only the needle equal to the hidden value matched, two arrays a user cannot tell apart got different answers. arrayAllAny is the only caller of the sliceHas overload set, and it passes rvalues because NullableArraySource::getWhole() returns by value. The three null-map-carrying overloads took non-const lvalue references, which cannot bind an rvalue, so they were removed from the candidate set. NullableSlice derives from the plain slice, so derived-to-base conversion made the plain overload viable and it won by default, passing nullptr for both null maps. Every downstream null-map branch was therefore unreachable in production: the AVX2 widening, the hasAllIntegralLoopRemainder skip, the generic path's hasNull prechecks and the NULL-matches-NULL logic in sliceHasImplSubstr and sliceHasImplStartsEndsWith. Those branches were individually correct; nothing ever fed them. Taking the nullable arguments by const reference makes the intended overloads selectable. Their bodies had never been instantiated and did not compile, because they passed slice types to comparators that expect element types, so the comparators are now passed as contextual overload sets exactly as the plain generic overload already did. Non-nullable input still selects the plain overload: comparing has_all.cpp and has_any.cpp built with and without this change gives no removed or altered symbols, and all 6 shared non-nullable sliceHas bodies compile to byte-identical instruction streams. No .reference file needed changing. The 48 NULL-carrying arms across 00555_hasAll_hasAny, 00555_hasSubstr and 02206_array_starts_ends_with are unaffected, including the documented hasAll([1, Null], [Null]) = 1, so this aligns the implementation with the documentation rather than contradicting it. Closes ClickHouse#68310. Co-Authored-By: Claude Opus 5 <[email protected]>
The tests added with the null-map fix never reached the SIMD kernels the fix makes live. Each kernel admits its vector loop only when both array sizes exceed a per-width threshold (3 for 64-bit, 7 for 32-bit, 15 for 16- and 8-bit), and arrayAllAny passes the needle as the second argument, so the needle size gates entry too. Every needle in the test was one element, so only the remainder loop ran, and the arm that claimed to cover the vectorised loop did not. Add a per-width section with 16-element needles (pure vector) and 22-element needles (vector plus remainder on all four kernels; 20 is a multiple of the 64-bit stride and would leave that one with no remainder), over a haystack whose only absent value is the one hidden under the NULL, so a reddening arm is attributable to the null map. Each width also gets two keep-matching controls and a second-null-map arm. Reword the remainder-only arm's heading to say what it does. The text index test asserted returned rows only, and after the fix every path returns the same row, so it would have passed even if index evaluation declined. It also left query_plan_direct_read_from_text_index unpinned while the test runner randomizes it, so the two labelled modes could swap. Pin it per arm and assert the plan shape, with a negative control so a token that matches something unrelated cannot read as a pass. Also replace the deprecated allow_experimental_full_text_index alias with enable_full_text_index, and fix a heading that stated the inverse of the invariant its reference asserts. No source change. No existing reference file changes.
The large-needle arms added in the previous round did enter the SIMD vector loop, but they placed the NULL at haystack index 24. For a 25-element haystack the inner loop runs over i = [0] (stride 16, Int8 and Int16), [0,8,16] (stride 8, Int32) and [0,4,8,12,16,20] (stride 4, Int64), so index 24 lies outside the vector range on all four kernels. The four first_null_map widening loads therefore only ever saw zero bytes and the andnot suppression was never asked to suppress anything: the arms reddened through the scalar tail null check that follows the vector block, so deleting every first_nm_mask term would have left them passing. Moving the payload to index 0 puts the set null bit in the first lane of the first vector iteration on all four kernels, and leaves no set null byte in the tail range, so suppression can now only come from the vector masking. With a 16-element needle the outer loop runs once, correct masking leaves has_mask at zero and the early return yields 0, while ignoring first_nm_mask lets lane 0 match the payload and yields 1. The reference file is unchanged: the visible value multiset, the single NULL and the payload are all the same as before. Base versus fix over the eight widths: payload_16 and payload_22 move 1 to 0 on 8/8, needle_null_16 moves 0 to 1 on 8/8, and both present_* keep-matching controls stay at 1 on both binaries.
Internal second-model reviewBefore opening this PR I put the change through an independent cold review plus a ❌ Blocker — the vectorised kernels this change makes live were not executed.
Fixed by adding per-width arms with 16- and 22-element needles over a ❌ Major — entering the vector loop was not enough: the null-map masking inside The expressions this change actually resurrects are the haystack null-map widening
They asserted returned rows only, and after the fix every path returns the same
💡 Nit — a test heading stated the inverse of its invariant. AGREED, fixed. Findings recorded and dismissed with evidence. The bloom-filter index is not a Findings recorded and dismissed with evidence (continued). The change also makes the A third round found nothing: an independent cold re-review of the delta and a second-model The source change itself was not modified by any round. |
|
Workflow [PR], commit [04ae9e0] Summary: ✅
AI ReviewSummaryThis PR fixes the nullable-slice overload selection bug in Missing context / blind spots
Final Verdict✅ No blocking review findings in the current version. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 2/6 (33.33%) · Uncovered code |
Pre-PR validation gate (click to expand)
|
|
cc @george-larionov @Algunenano, could you review this? |
Build profile diff (arm_release)Comparing Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/Functions/GatherUtils/CMakeFiles/clickhouse_functions_gatherutils.dir/ends_with.cpp.o |
3.01 MiB | 3.28 MiB | +269.59 KiB (+8.74%) |
src/Functions/GatherUtils/CMakeFiles/clickhouse_functions_gatherutils.dir/starts_with.cpp.o |
3.01 MiB | 3.26 MiB | +253.85 KiB (+8.24%) |
src/Functions/GatherUtils/CMakeFiles/clickhouse_functions_gatherutils.dir/has_all.cpp.o |
3.02 MiB | 3.24 MiB | +223.80 KiB (+7.23%) |
src/Functions/GatherUtils/CMakeFiles/clickhouse_functions_gatherutils.dir/has_any.cpp.o |
3.02 MiB | 3.23 MiB | +211.16 KiB (+6.82%) |
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Compile time of recompiled translation units
30 translation units recompiled, 132 s compile time in total, 30 of them have a recent master baseline.
The two EXPLAIN probes only covered hasAll. hasAny reaches the text index through a different RPN element and a different evaluator: hasAny builds FUNCTION_HAS_ANY_TOKENS and is answered by hasAnyTokensInRange, while hasAll builds FUNCTION_HAS_ALL_TOKENS and is answered by hasAllTokensInRange. Post-fix every path returns the same row, so the hasAny arms were result-only and would still have passed if index evaluation had silently declined. Measured on the direct-read arm: with the rewrite disabled the new assertion reads 0 where the reference says 1, while the row set stays the same in all three configurations, which is the blindness being removed. The mode token distinguishes which element was built. The condition description prints the global search mode, which is Any only when an element requires reading all tokens. For a one element needle that is true for the folded hasAny element and false both for hasAll and for the per element fallback, so the assertion arms the intended path rather than merely being sensitive. Confirmed by changing only the tokenizer, which routes the same query to the fallback and reads All.
The test runner randomizes use_query_condition_cache, and the setting defaults to true. The cache looks each condition up under the bare condition hash as well as under one salted with the skip-index profile that analysis ran (filterPartsByQueryConditionCache in MergeTreeDataSelectExecutor.cpp). Row-level entries under the bare hash are deliberately shared across profiles, so the earlier use_skip_indexes = 0 arms in this test prime entries that the later indexed arms then reuse. Measured on this test's own table: with the index deliberately ignored to simulate an index that declines, the read reports SelectedMarks = 1 after that population, the same value a working index produces, against SelectedMarks = 2 with a cold cache. Pinning the setting restores 2. Over the committed test's 21 queries the cache is consulted 4 times with the setting left to the runner and 0 times with it pinned. The EXPLAIN probes added earlier cannot close this, because EXPLAIN disables the cache, so they prove the plan while the result arms can still be served from a primed entry. Matches the in-tree convention: 30 text index tests already pin this setting. Liveness is unaffected: the test still passes 8/8 on the fixed build and fails 3/3 on the pre-fix build under both injected values of the setting.
The AVX2/SSE kernels `sliceHasImplAnyAllImplInt8/16/32/64` are `NO_INLINE` and take the null maps as runtime pointers. Before ClickHouse#116239 they were only called with `nullptr` null maps, and the ThinLTO build folded the null-map handling away. Since ClickHouse#116239 Nullable arrays reach the same instantiation with real null maps, so the null-mask loads and masking stay in the inner loop for every array, and `hasAll` on non-Nullable integer arrays became 16-60% slower in the amd performance tests. Add a `with_null_maps` template parameter to the kernels and dispatch to the `false` instantiation when both null maps are absent, so the null-map-free kernel no longer depends on interprocedural constant propagation. Nullable arrays keep using the current code. The analysis and patch come from ClickHouse#123380. Closes ClickHouse#123380 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
hasAll,hasAny,hasSubstr,startsWithandendsWithreturning wrong results onArray(Nullable(T)). ANULLelement was compared as whatever value was physically stored beneath it, so these functions disagreed withhason identical input:hasAll([1, 2, NULL, 4], [0])returned1whilehas([1, 2, NULL, 4], 0)returned0. Closes #68310.Description
Reported in #68310; reproduces on 26.7.5.10, 26.3.21.7 and 25.8.32.4. Only the needle equal to the hidden value matches, so two arrays a user cannot tell apart answer differently, and a
NULLneedle is wrong the other way:Root cause.
arrayAllAny, the only caller of thesliceHasoverload set, passes rvalues becauseNullableArraySource::getWhole()returns by value. The three null-map-carrying overloads took non-const lvalue references, which cannot bind an rvalue, so they left the candidate set;NullableSlicederives from the plain slice, so derived-to-base made the plain overload viable and it won, passingnullptr, nullptr. Both null maps were always null and every downstream null-map branch unreachable.Change. Those overloads now take their nullable arguments by
const &. Their bodies had never been instantiated and did not compile, because they passed slice types to comparators expecting element types; they now pass the comparators as contextual overload sets, as the plain generic overload already did. The already-correct null-map branches start being fed. Non-nullable input still picks the plain overload.Validation. Fails without the change, passes with it, and answers #68310's reproducer correctly. No
.referencefile changed: all 48NULL-carrying arms in the existing membership tests are unaffected, including the documentedhasAll([1, Null], [Null]). 65 array-membership tests pass, the new tests pass 100/100 under randomized settings, and the vectorised kernels' dead null-map paths are covered per width under ASAN+UBSAN.05043pins a second symptom: a text index answers these functions with its own already-correct evaluator, so results used to depend on whether an index existed.Not fixed here, different cause: on arrays
startsWithCaseInsensitive,startsWithUTF8andstartsWithCaseInsensitiveUTF8test a suffix, since onlyNameStartsWithpicks the prefix branch.Workflow [PR]
Sync PR [sync-upstream/pr/116239]
Version info
26.10.1.233-master(included in26.10and later)