Skip to content

Treat a NULL array element as NULL in hasAll, hasAny and hasSubstr - #116239

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-array-membership-null-map
Sep 19, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-array-membership-null-map

Conversation

@groeneai

@groeneai groeneai commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixed hasAll, hasAny, hasSubstr, startsWith and endsWith returning wrong results on Array(Nullable(T)). A NULL element was compared as whatever value was physically stored beneath it, so these functions disagreed with has on identical input: hasAll([1, 2, NULL, 4], [0]) returned 1 while has([1, 2, NULL, 4], 0) returned 0. 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 NULL needle is wrong the other way:

SELECT hasAll(arrayMap(x -> nullIf(x, 42), [42, 5]), [42]);   -- 1, should be 0
SELECT hasAll(arrayMap(x -> nullIf(x, 42), [42, 5]), [NULL]); -- 0, should be 1

Root cause. arrayAllAny, the only caller of the sliceHas overload set, 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 left the candidate set; NullableSlice derives from the plain slice, so derived-to-base made the plain overload viable and it won, passing nullptr, 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 .reference file changed: all 48 NULL-carrying arms in the existing membership tests are unaffected, including the documented hasAll([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. 05043 pins 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, startsWithUTF8 and startsWithCaseInsensitiveUTF8 test a suffix, since only NameStartsWith picks the prefix branch.


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

Version info

  • Merged into: 26.10.1.233-master (included in 26.10 and later)

groeneai and others added 3 commits August 24, 2026 22:52
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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Before opening this PR I put the change through an independent cold review plus a
second-model review pass, over two rounds, and adjudicated every finding against
the recorded evidence. Verdicts and the reasoning behind them:

❌ Blocker — the vectorised kernels this change makes live were not executed.
AGREED, fixed.

arrayAllAny passes (haystack, needle) to sliceHas, and each AVX2/SSE kernel
admits its vector loop only when both arrays exceed a per-width threshold
(3 for Int64, 7 for Int32, 15 for Int16 and Int8). Every needle in the
first version of the test was one element, so no arm entered a vector loop,
including the arm that claimed to. The same held for the sanitizer sweep, which
varied the haystack length but not the needle, so it never issued one of the
null-map loads it existed to check. gtest_has_all's null-map arms do not reach
those loops either: they cross the threshold only for Int64, and there the
first null map is all zeroes, so the early return fires before the loop.

Fixed by adding per-width arms with 16- and 22-element needles over a
25-element haystack (16 is a pure vector pass, 22 straddles the vector/remainder
hand-off on all four kernels), a second arm carrying a NULL inside the needle so
the second null map's intrinsics are exercised too, and a keep-matching control
per width, so a reddening arm distinguishes "the null map is now respected" from
"large needles now always fail". The sanitizer sweep was re-run with the raised
needle sizes.

❌ Major — entering the vector loop was not enough: the null-map masking inside
it still only ever saw zero bytes. AGREED, fixed.

The expressions this change actually resurrects are the haystack null-map widening
loads and the masking they feed, and those only do observable work when a set
null-map bit falls inside the vector chain's index range. With the hidden value at
the end of the haystack it fell outside that range on all four kernels, so the
arms reddened through the scalar tail check instead, and deleting every masking
term would have left the tests passing. Fixed by moving the hidden value to index
0, the first lane of the first vector iteration, which leaves the expected results
unchanged while making the arms flip on the masking expressions alone. The
sanitizer sweep was moved the same way, so it now exercises the in-vector bit at
every haystack length rather than a fraction of them.

⚠️ Major — the two text-index arms neither forced nor proved their labels.
AGREED, fixed.

They asserted returned rows only, and after the fix every path returns the same
row, so the test would still pass if index evaluation silently declined. Two of
the settings involved are also randomized by the test runner and were not pinned,
so the labelled modes could swap. Fixed by pinning them per arm and adding
EXPLAIN indexes = 1 plan-shape assertions in the
SELECT ... FROM (EXPLAIN ...) WHERE explain ILIKE ... form, with tokens chosen
from measured plan text so each discriminates between the modes, plus a negative
control that must report zero on all of them when skip indexes are off.

⚠️ Major — deprecated setting alias. AGREED, fixed. The text-index test set
allow_experimental_full_text_index, which is an alias for
enable_full_text_index and defaults to true since the text index went GA.
Switched to the current name.

💡 Nit — a test heading stated the inverse of its invariant. AGREED, fixed.
The heading said two arrays that print identically must answer differently;
answering differently is the bug, and the reference correctly expects them to
answer identically once fixed.

Findings recorded and dismissed with evidence. The bloom-filter index is not a
carrier for this defect by construction, not merely untested: a bloom filter
cannot be built on Array(Nullable(T)) at all, so the hasAll/hasAny rewrite
is unreachable for the affected type. There is no undocumented divergence from the
planned change: the source diff is the three signature changes plus the comparator
arguments they require, with the non-nullable overloads untouched. And one
deviation from my own prescribed test fixture turned out to be required rather
than discretionary, because the fixture I specified removed a value that every
prescribed needle contained, so those arms would have passed for the wrong reason.

Findings recorded and dismissed with evidence (continued). The change also makes the
null-map branches of the substring (KMP) and prefix/suffix implementations live, not only
the any/all ones, so those needed their own check against existing expectations rather than
being covered by the any/all argument. The pre-existing substring test carries seven
multi-element NULL-needle arms and the prefix/suffix test carries ten NULL arms; all pass
unchanged with no reference edit, so the newly-live symmetric-NULL semantics were already
pinned upstream and no new arm was needed.

A third round found nothing: an independent cold re-review of the delta and a second-model
re-review both returned zero findings, and the overload resolution was re-derived from
scratch a final time, including the partial ordering that keeps non-nullable input on the
plain overload.

The source change itself was not modified by any round.

@clickhouse-gh clickhouse-gh Bot closed this Aug 25, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [04ae9e0]

Summary: ✅


AI Review

Summary

This PR fixes the nullable-slice overload selection bug in sliceHas, so the existing null-map-aware logic is now reached again for hasAll, hasAny, hasSubstr, startsWith, and endsWith on Array(Nullable(T)). I did not find a remaining correctness issue in the current diff, and the two earlier inline concerns on the text-index test coverage are addressed in the current head.

Missing context / blind spots
  • ⚠️ The Praktika report available during this review only exposed the build-profile diff, so I could not cross-check the usual functional CI jobs from the shared report. This gap closes once the normal stateless/integration reports are attached.
Final Verdict

✅ No blocking review findings in the current version.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 2/6 (33.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT hasAll([1, 2, NULL, 4], [0]), has([1, 2, NULL, 4], 0) returns 1, 0 in one clickhouse local invocation. 100% reproducible, no randomization or timing dependence. Also reproduced on released binaries 26.7.5.10, 26.3.21.7 and 25.8.32.4.
b Root cause explained? Yes. arrayAllAny is the only caller of the sliceHas overload set and 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 left the candidate set; NullableSlice derives from the plain slice, so derived-to-base made the plain overload viable and it won by default, passing nullptr, nullptr. Both null maps were therefore always null, and every downstream null-map branch was unreachable in production.
c Fix matches root cause? Yes. It makes the intended overloads selectable rather than guarding a symptom: no widened bounds, no defensive check, no per-function special case, no no-random-* tag. The already-correct null-map branches simply start being fed.
d Test intent preserved / new tests added? Yes. No existing test was weakened, removed, or re-referenced, and no .reference file was edited. Two new tests added: 05042_array_membership_null_map and 05043_array_membership_null_map_text_index. Both were run against the unpatched binary and both fail there, so neither is vacuous. Every payload arm of the large-needle section moves base-to-fix on all 8 widths while its keep-matching controls stay put. The text index arms pin query_plan_direct_read_from_text_index (the runner randomizes it) and assert the plan shape with a negative control, so they cannot pass if index evaluation silently declines. gtest_has_all.cpp passes unmodified.
e Both directions demonstrated? Yes, with the repro from (a) on two binaries differing only in this patch, and additionally as a .reference diff on both new tests. Ten arm-groups move, every one toward the answer has() already gives. Controls that do not move: no-NULL haystack, non-nullable haystack, needle unequal to the hidden value, hasAll([1, Null], [Null]) = 1, and genuine prefix/suffix results.
f Fix is general across code paths? Yes. grep -rn "sliceHas<" src/ returns exactly one caller, so fixing the shared source covers hasAll, hasAny, hasSubstr and all 8 startsWith/endsWith names, whose dispatch sites in has_all.cpp, has_any.cpp, has_substr.cpp, starts_with.cpp and ends_with.cpp all route through it. All three nullable overloads were fixed, not only the both-nullable one, so mixed pairs cannot regress later. The other getWhole() call sites (FunctionStartsEndsWith.h:265, HasSubsequenceImpl.h:98, padString.cpp:280) are string-byte paths with no nullable-slice overload set, so they carry no analogous trap.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured, with every answer cross-checked against has(): LowCardinality(Nullable(String)), all 8 integer widths, String, Tuple, empty arrays on both sides, Int64 min, UInt64 max, the zero-hidden-value case that made the old behavior look right, all-NULL and multi-NULL arrays, constant vs materialized on both sides, literal vs MergeTree column, and 16- and 22-element needles over a 25-element haystack on every width so the vectorised kernels run and not only the remainder loop. Each kernel gates its vector loop on the needle size exceeding a per-width threshold (3, 7, 15, 15), so a one-element needle never enters one; 22 also leaves a remainder on all four. Each width carries two keep-matching controls, so a reddening payload arm is attributable to the null map rather than to large needles failing generally.
h Backward compatible? This deliberately changes results for Array(Nullable(T)), toward the documented behavior (array-functions.mdx states "Null is processed as a value" with hasAll([1, Null], [Null]) as a worked example), so it is a bug fix rather than a semantics change. No new or changed setting, therefore no SettingsChangesHistory.cpp entry, which records default changes. No serialization or on-disk format change. If a reviewer wants a compatibility gate, that is an owner decision rather than something to invent here.
i Invariants and contracts preserved? Yes. The bodies are unchanged apart from the comparator template arguments; they only read .null_map and forward to sliceHasImpl, which already took const &. const & is strictly weaker than the previous non-const reference, so no caller loses a capability and nothing can now be mutated that could not before. No allocation, ownership, lifetime, locking or error path is touched. The newly-live SIMD null-map loads stay inside PaddedPODArray's 64-byte right padding against a 16-byte over-read, confirmed by an ASAN+UBSAN sweep with 16- and 22-element needles (the sizes that actually enter the vector loops) over 24..103-element haystacks, on every width, both null maps and the generic path, with zero diagnostics. The sweep carries positive controls that match 80/80 per width, so the clean result is not a vacuous pass.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @george-larionov @Algunenano, could you review this? arrayAllAny calls sliceHas with rvalues, because NullableArraySource::getWhole() returns by value, so the three null-map-carrying overloads (non-const lvalue refs) were never viable and the plain overload won by derived-to-base conversion, passing nullptr, nullptr. hasAll, hasAny, hasSubstr, startsWith and endsWith therefore compared a NULL element as the value physically stored under it; taking those overloads by const & makes the already-correct null-map branches reachable, and non-nullable input still selects the plain overload unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 04ae9e03e with master 608eeb80f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 709.96 MiB 707.20 MiB -2.75 MiB (-0.39%)

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 ⚠️

15 object files changed (+963.52 KiB total), 0 added.

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.

Job report

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.
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit ee32c21 Sep 19, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
alexey-milovidov pushed a commit to ygxio/ClickHouse that referenced this pull request Oct 13, 2026
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]>
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-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Array functions - hasAny() and hasAll() returns unexpected result for array of nullable types

3 participants