Skip to content

Portable SIMD for hasAll and hasAny on integer arrays - #123420

Merged
Algunenano merged 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/hasall-kernels-without-null-maps
Oct 13, 2026
Merged

Algunenano merged 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/hasall-kernels-without-null-maps

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #123380
Related: #116239
Related: #116224

Since #116239, hasAll on non-Nullable integer arrays was 16-60% slower on x86, because the AVX2/SSE kernels kept the null-map handling in their inner loops.

This PR replaces those x86-only kernels with code written with clang vector extensions, which compiles to SSE/AVX2 on x86 and NEON on AArch64:

  • hasAll and hasAny on all integer types search each value in blocks of 128 bytes with one mask test per block.
  • hasAll on 1-byte elements compares 16 values against the 16 rotations of 16 elements, as the previous SSE kernel did, and exits when all 16 are found.
  • Null maps are handled without extra work per comparison, and checking whether an array has nulls no longer loops byte by byte.

Measured with perf.py against the previous kernels on Zen 4, and against the previous scalar code on Neoverse-V3, with has_all.xml and extra cases for missing values, Nullable arrays and hasAny:

  • x86: has_all.xml up to 1.77x faster, hasAny 5x to 15x faster, hasAll on Nullable arrays up to 1.69x faster, no query slower.
  • ARM: every query 1.08x to 9.87x faster, and 1-byte hasAll up to 2.26x faster again after the latest commit.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

hasAll and hasAny on integer arrays use SIMD on both x86 and ARM, including Nullable arrays and hasAny, which previously used a scalar loop. hasAny is up to 15x faster, and hasAll becomes several times faster on ARM.


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

Version info

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

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 2, 2026
@groeneai

groeneai commented Oct 2, 2026

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

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review of the same tree (0 blocker, 0 major).

# Sev Finding Verdict Evidence / action
1 💡 Description labelled has_all #3 (small Int64, 391 -> 584 ms) as small Int32 AGREE, fixed in the description perf tests number queries template-first; small Int32 is #2, 218 -> 336 ms
2 💡 Changelog entry claimed a speed-up over a release that never had the regression AGREE, entry reworded #116239 is master-only; the 26.9 binary already has the small kernels

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-11:20261002-051100

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7ba2505]

Summary: ✅


AI Review

Summary

This PR replaces the x86-only integer hasAll/hasAny kernels with portable vector code, adds a new performance benchmark, and expands stateless coverage. I found one unresolved performance contract violation: the new generic multi-byte hasAll path still regresses the PR's own nullable_found_medium_Int16 workload by 11%-15%, so I am requesting changes.

Findings

⚠️ Majors

  • [src/Functions/GatherUtils/sliceHasImplAnyAll.h:157] The new multi-byte hasAll implementation re-scans first for each element of second, which drops the old batched-needle behavior for 16-bit arrays. The PR's own perf notes still show nullable_found_medium_Int16 slower than both master and the previous head (543 ms vs 482/484 ms; see Portable SIMD for hasAll and hasAny on integer arrays #123420 (comment)). For a Performance Improvement PR, that is an unresolved contract violation.
    Suggested fix: restore a grouped hasAll path for 16-bit integer arrays here, or rerun the benchmark on the current head and narrow the PR's performance claims if this slowdown is an accepted tradeoff.
Performance & Safety
  • ⚠️ The regression above is on one of the PR's own committed benchmark shapes (Array(Nullable(Int16)) in tests/performance/has_any_has_all_nullable.xml), so the current performance story is mixed rather than uniformly improved.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Either recover the nullable_found_medium_Int16 regression in the multi-byte hasAll path, or provide current-head benchmark evidence that it is gone and narrow the PR description if the slower case is an accepted tradeoff.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 2, 2026
@groeneai
groeneai requested review from Algunenano and Ergus October 2, 2026 05:40
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 945cb31b-537b-4a72-ac93-a4c3d1e367ce
  • MIRAI run: 48911c1f-0ef4-4ef4-8ac6-94594597084d
  • PR check IDs:
    • clickbench_657275_1791602879
    • clickbench_657281_1791602879
    • clickbench_657287_1791602879
    • tpch_adapted_1_official_657299_1791602879
    • tpch_adapted_1_official_657311_1791602879
    • tpch_adapted_1_official_657348_1791602879

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7ba250527 with master 727bdd7b6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0d2ade023; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

13 object files changed (+219.46 KiB total), 0 added.

Object file Master PR Δ
src/Functions/GatherUtils/CMakeFiles/clickhouse_functions_gatherutils.dir/has_all.cpp.o 3.27 MiB 3.39 MiB +121.80 KiB (+3.63%)
src/Functions/GatherUtils/CMakeFiles/clickhouse_functions_gatherutils.dir/has_any.cpp.o 3.30 MiB 3.39 MiB +93.79 KiB (+2.78%)

719 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

51 translation units recompiled, 352 s compile time in total, 51 of them have a recent master baseline.

Job report

@Algunenano Algunenano self-assigned this Oct 2, 2026

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this x86 branches should exist to begin with. We can use a generic kernel instead which will both be faster and benefit other architectures. I'll try to push it here

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, a generic kernel is the better shape. I'll leave the branch to you and won't push to it.

Two things that may help:

The AVX2/SSE kernels only covered `hasAll` on x86. They are replaced with
code written with clang vector extensions, which compiles to SSE/AVX2 on x86
and to NEON on AArch64:

- `sliceContains` searches one value in blocks of 128 bytes with one test
  per block. It serves `hasAny` and `hasAll` for all integer types.
- `sliceHasAllBytes` keeps the SSE algorithm for `hasAll` on 1-byte
  elements: 16 values against all 16 rotations of 16 elements of `first`.
  Null elements of `first` are replaced with a non-null element of `first`
  instead of masking each rotation.
- `hasNull` ORs the whole null map instead of a scalar loop with an early
  exit, which took a fifth of `hasAll` on `Nullable` arrays without nulls.

Compared with the previous kernels, `has_all.xml` is up to 1.77x faster with
no regressions, `hasAny` is 5x to 15x faster, and `hasAll` on `Nullable`
arrays is up to 1.69x faster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member

I pushed a commit on top of this branch (422ca55) that replaces the AVX2/SSE hasAll kernels with portable code written with clang vector extensions. It compiles to SSE/AVX2 on x86 and to NEON on AArch64, so ARM gets vectorized hasAll/hasAny too, and the with_null_maps split is no longer needed.

What changed in sliceHasImplAnyAll.h:

  • sliceContains searches one value in blocks of 128 bytes with a single mask test per block. It is used for hasAny and hasAll on all integer types.
  • sliceHasAllBytes keeps the SSE algorithm for hasAll on 1-byte elements (16 values against the 16 rotations of 16 elements of first), because Int8 values repeat and are found within a few elements. Null elements of first are replaced with a non-null element of first instead of masking every rotation.
  • hasNull ORs the null map without an early exit. The scalar loop took about 20% of hasAll on Nullable arrays without nulls.
  • The comments explain the constructs that exist for codegen (reduction spellings, fixed loop bounds, unsigned max instead of |).

Local results on x86 (Ryzen 9 7950X3D, perf.py, 10 runs, previous head of this PR vs the new commit, both servers pinned to the same CCD):

  • has_all.xml: 1.04x to 1.77x faster for Int16/32/64 and 1.02x to 1.34x faster for Int8, except large_Int32, which is unchanged.
  • Additional cases (independent subset so values are missing, Nullable arrays with nulls, hasAny; the XML is below): all faster or unchanged. hasAny is 5x to 15x faster, hasAll on Nullable arrays 1.12x to 1.69x.

Correctness: a differential test of the kernels against a scalar reference under ASan/UBSan (2 million random cases, all 8 integer types, hasAll and hasAny, null rates from none to all), identical clickhouse local results against the previous binary on 600 thousand random rows (Nullable and not), and the related stateless tests (00555_hasAll_hasAny, 01812_has_generic, 05042_array_membership_null_map, 02893_array_enum_has_hasAny, the bloom filter and text index tests with hasAny/hasAll).

The NEON code has been checked only in the generated assembly so far, not run.

@groeneai could you review the change and run the tests and performance comparisons on your machine as well, including on ARM if you have one? Please also update the PR description if you agree with the approach, since it no longer describes the change.

Additional performance cases
<test>
    <substitutions>
        <substitution>
            <name>array_type</name>
            <values>
                <value>Int8</value>
                <value>Int16</value>
                <value>Int32</value>
                <value>Int64</value>
            </values>
        </substitution>
    </substitutions>

    <!-- `subset` is drawn independently of `set`, so most values are missing. -->
    <create_query>CREATE TABLE missing_small_{array_type} (set Array({array_type}), subset Array({array_type})) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <create_query>CREATE TABLE missing_medium_{array_type} (set Array({array_type}), subset Array({array_type})) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <!-- Nullable arrays where one value in 64 is null; `subset` is drawn from `set`, so all values are found. -->
    <create_query>CREATE TABLE nullable_found_small_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <create_query>CREATE TABLE nullable_found_medium_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <!-- Nullable arrays with nulls only in `set`; `subset` is drawn independently, so most values are missing. -->
    <create_query>CREATE TABLE nullable_missing_medium_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>

    <fill_query>INSERT INTO missing_small_{array_type} SELECT groupArraySample(5000)(rand64(1)), groupArraySample(500)(rand64(2)) FROM numbers(10000000) GROUP BY number % 5000</fill_query>
    <fill_query>INSERT INTO missing_medium_{array_type} SELECT groupArraySample(50000)(rand64(1)), groupArraySample(5000)(rand64(2)) FROM numbers(25000000) GROUP BY number % 50000</fill_query>
    <fill_query>INSERT INTO nullable_found_small_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(5000)(rand64(1))), arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(500)(rand64(1))) FROM numbers(10000000) GROUP BY number % 5000</fill_query>
    <fill_query>INSERT INTO nullable_found_medium_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(50000)(rand64(1))), arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(5000)(rand64(1))) FROM numbers(25000000) GROUP BY number % 50000</fill_query>
    <fill_query>INSERT INTO nullable_missing_medium_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(50000)(rand64(1))), arrayMap(v -> toNullable(v), groupArraySample(5000)(rand64(2))) FROM numbers(25000000) GROUP BY number % 50000</fill_query>

    <query>SELECT hasAll(set, subset) FROM missing_small_{array_type} FORMAT Null</query>
    <query>SELECT hasAll(set, subset) FROM missing_medium_{array_type} FORMAT Null</query>
    <query>SELECT hasAny(set, subset) FROM missing_small_{array_type} FORMAT Null</query>
    <query>SELECT hasAny(set, subset) FROM missing_medium_{array_type} FORMAT Null</query>
    <query>SELECT hasAll(set, subset) FROM nullable_found_small_{array_type} FORMAT Null</query>
    <query>SELECT hasAll(set, subset) FROM nullable_found_medium_{array_type} FORMAT Null</query>
    <query>SELECT hasAll(set, subset) FROM nullable_missing_medium_{array_type} FORMAT Null</query>
    <query>SELECT hasAny(set, subset) FROM nullable_missing_medium_{array_type} FORMAT Null</query>

    <drop_query>DROP TABLE IF EXISTS missing_small_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS missing_medium_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS nullable_found_small_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS nullable_found_medium_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS nullable_missing_medium_{array_type}</drop_query>
</test>

@Algunenano

Copy link
Copy Markdown
Member

Measurements of 422ca55 on ARM (Neoverse-V3, 48 cores, clang 22.1.8, RelWithDebInfo), against the previous head of this PR (860e473), which runs the scalar loop on ARM. Both servers were pinned to the same cores; perf.py, 10 runs.

All 44 queries are faster, from 1.08x to 9.87x, with p ≤ 2e-6 for each. The related stateless tests pass (3 runs each), and the randomized clickhouse local comparison gives identical results for both binaries, with Nullable and non-Nullable arrays. The NEON hot loops are ext/cmeq/umax for 1-byte elements and cmeq blocks for the wider types, with no lane-by-lane moves.

has_all.xml:

table old ms new ms change
test_table_small_Int8 218.3 82.5 2.65x faster
test_table_small_Int16 886.4 112.6 7.87x faster
test_table_small_Int32 898.8 232.2 3.87x faster
test_table_small_Int64 906.2 343.1 2.64x faster
test_table_medium_Int8 1436.1 241.3 5.95x faster
test_table_medium_Int16 2395.0 242.5 9.87x faster
test_table_medium_Int32 2411.6 550.0 4.38x faster
test_table_medium_Int64 1657.4 579.7 2.86x faster
test_table_large_Int8 127.2 18.8 6.77x faster
test_table_large_Int16 125.1 28.5 4.39x faster
test_table_large_Int32 133.5 50.0 2.67x faster
test_table_large_Int64 129.8 67.0 1.94x faster

Additional cases (the XML from my previous comment):

function table old ms new ms change
hasAll missing_small_Int8 233.5 88.9 2.63x faster
hasAll missing_small_Int16 11.4 7.9 1.44x faster
hasAll missing_small_Int32 14.6 11.8 1.24x faster
hasAll missing_small_Int64 21.1 18.6 1.13x faster
hasAll missing_medium_Int8 41.5 26.5 1.57x faster
hasAll missing_medium_Int16 27.7 19.0 1.46x faster
hasAll missing_medium_Int32 42.3 34.7 1.22x faster
hasAll missing_medium_Int64 49.8 45.6 1.09x faster
hasAny missing_small_Int8 6.2 5.7 1.08x faster
hasAny missing_small_Int16 121.0 18.5 6.55x faster
hasAny missing_small_Int32 1741.0 391.0 4.45x faster
hasAny missing_small_Int64 1768.0 609.6 2.90x faster
hasAny missing_medium_Int8 17.4 13.3 1.31x faster
hasAny missing_medium_Int16 1199.4 126.0 9.52x faster
hasAny missing_medium_Int32 4609.5 1007.6 4.57x faster
hasAny missing_medium_Int64 3186.0 1089.6 2.92x faster
hasAll nullable_found_small_Int8 256.0 86.5 2.96x faster
hasAll nullable_found_small_Int16 964.8 149.4 6.46x faster
hasAll nullable_found_small_Int32 976.3 283.4 3.44x faster
hasAll nullable_found_small_Int64 1008.5 793.1 1.27x faster
hasAll nullable_found_medium_Int8 1754.8 258.6 6.79x faster
hasAll nullable_found_medium_Int16 2746.0 365.8 7.51x faster
hasAll nullable_found_medium_Int32 2752.5 689.5 3.99x faster
hasAll nullable_found_medium_Int64 1644.8 1190.2 1.38x faster
hasAll nullable_missing_medium_Int8 66.5 36.2 1.84x faster
hasAll nullable_missing_medium_Int16 47.5 29.2 1.62x faster
hasAll nullable_missing_medium_Int32 60.3 44.1 1.37x faster
hasAll nullable_missing_medium_Int64 56.8 49.4 1.15x faster
hasAny nullable_missing_medium_Int8 36.2 22.3 1.63x faster
hasAny nullable_missing_medium_Int16 1269.0 189.8 6.69x faster
hasAny nullable_missing_medium_Int32 4749.1 1282.1 3.70x faster
hasAny nullable_missing_medium_Int64 2809.9 2334.0 1.20x faster

The smallest gains are on Nullable Int64 (1.20x to 1.38x). There, widening the null map from bytes to 8-byte lanes takes more instructions than the comparisons. That can be improved later by applying the null mask only to blocks that have a match.

The 16 comparison masks were folded into one accumulator with 16 dependent
unsigned maximums. AArch64 kept that chain in order, so each block of 16
elements waited for 16 `umax` latencies. Combining them pairwise makes the
chain 4 levels deep; the compiler turns the tree into `orr` and keeps a single
`umax` into the accumulator.

On Neoverse-V3, 1-byte `hasAll` is 1.24x to 2.26x faster. On Zen 4 it is
unchanged, because x86 already split the chain in two.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano Algunenano changed the title Avoid null-map work in the x86 hasAll SIMD kernels for non-Nullable arrays Portable SIMD for hasAll and hasAny on integer arrays Oct 2, 2026
@Algunenano

Copy link
Copy Markdown
Member

🤖 I pushed 4f4be82 on top of the previous commit. In the 1-byte hasAll kernel, the 16 rotation comparisons were folded into one accumulator with 16 dependent unsigned maximums, and AArch64 kept that chain in order. They are now combined pairwise as a tree. The compiler turns it into a 4-level orr tree plus a single umax into the accumulator, so only that umax carries a dependency from one block to the next.

Results with perf.py (10 runs, servers pinned), 1-byte queries only, since nothing else changed:

function table ARM (Neoverse-V3) x86 (Zen 4)
hasAll test_table_small_Int8 2.23x faster not significant
hasAll test_table_medium_Int8 2.11x faster not significant
hasAll test_table_large_Int8 1.34x faster not significant
hasAll missing_small_Int8 2.26x faster not significant
hasAll missing_medium_Int8 1.47x faster 1.06x slower
hasAll nullable_found_small_Int8 1.82x faster 1.02x faster
hasAll nullable_found_medium_Int8 1.69x faster not significant
hasAll nullable_missing_medium_Int8 1.24x faster 1.02x slower

x86 is essentially unchanged because it already split the chain in two. The two small x86 differences are within what I saw between builds that differ only in code layout: in the same run, hasAny on Int8 also moved by up to 1.20x, and patch B does not touch it, while on ARM hasAny was unchanged.

Against #116224 on ARM, 1-byte hasAll is now faster on every table except missing_medium_Int8 (1.09x slower), for example 2.45x faster on test_table_medium_Int8.

Both the randomized clickhouse local comparison and the kernel differential test under ASan/UBSan give identical results with the change.

I also tried sending 1-byte hasAll to the per-value search with 32-byte blocks, as #116224 does. It was faster when most values are missing, but up to 2.55x slower on x86 and 1.33x slower on ARM when values are found late in long arrays, so I did not keep it.

…arrays

`hasNull` ORed the whole null map, so `hasAny` became linear in the array
length even when both arrays start with a null and the result is already
known. It now tests 64 bytes at a time with whole-vector ORs and returns at
the first block that has a null, which keeps the loop vectorized.

The new test checks `hasAll` and `hasAny` on Int8, UInt8, Int16, Int32, Int64
and UInt64 arrays, `Nullable` and not, against a reference that checks each
element with `has`. Lengths cross the 16-element groups and 128-byte blocks of
the vectorized search, and nulls are placed in neither, either or both arrays,
including a first array of only nulls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member

🤖 I pushed dd49f49, which addresses both points from the AI review.

hasNull without an early exit. This was a real regression: when both arrays start with a null, hasAny already knows the answer, but hasNull read the whole null map first. With 2000 rows of 100000-element Nullable(Int64) arrays that start with a null, a query took 0.005 s instead of 0.001 s. hasNull now tests 64 bytes at a time with whole-vector ORs and returns at the first block that has a null. The same query takes 0.000 to 0.001 s again. The loop is still vectorized (on x86, vmovdqu + vpor + vptest per block), so the earlier fix for Nullable arrays without nulls stays: the 16 Nullable queries from the extra performance cases are unchanged (all within ±3%, most not significant).

Coverage. The new test 05318_array_has_all_has_any_long_integer_arrays checks hasAll and hasAny on Int8, UInt8, Int16, Int32, Int64 and UInt64 arrays, as Nullable, non-Nullable and mixed, against a reference that checks each element with has. Its 3240 rows cover every combination of:

  • first array lengths from 1 to 300 around the 16-element groups and 128-byte blocks,
  • second array lengths from 1 to 100,
  • value ranges of 2, 16 and 100,
  • nulls in neither, either or both arrays, or a first array of only nulls,
  • second arrays that are independent, taken from the first, or taken from the first with a missing value at the end.

The test passes 3 times in a row under the runner's random settings. The build before this PR's changes gives byte-identical output.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

I read through the header and agree with the approach; I have no code comments. I measured 422ca55, before your two later commits.

Setup: Intel Xeon 6975P-C, ThinLTO release builds, four servers up at the same time on identical data: master (bbba881), the previous head (860e473), and 422ca55 twice for an A/A floor. 7 rounds, max_threads = 4, the has_all.xml tables plus your extra cases (same shapes, deterministic data).

Performance:

  • has_all.xml: 1.04x to 1.89x faster than the previous head (large_Int64 unchanged), 1.22x to 2.81x faster than master.
  • hasAny with missing values: 3.5x to 11x faster for 16/32/64-bit types, about 1.4x for Int8.
  • hasAll on Nullable arrays where all values are found: 1.15x to 1.67x faster, except nullable_found_medium_Int16, which is 1.12x to 1.18x slower against both the previous head and master, in each of the four new-vs-old pairings (the A/A difference on that query is 3.5%). Your Zen 4 run does not show it, so it may be specific to this CPU. I will re-measure it on dd49f49.
  • Everything else was faster or within the A/A floor, which was wide here (up to about 28% between the two identical servers on some queries).

Correctness, all on 422ca55:

  • clickhouse local comparison against arrayAll/arrayExists over has: 8 integer types, 200k rows each, array lengths 0 to 300, hasAll and hasAny, Nullable, non-Nullable and mixed: 0 mismatches, and the result hash is the same for master, the previous head and 422ca55.
  • The header compiled on its own against an independent scalar reference: 4M random cases each for x86-64-v3, baseline x86-64 and ASan/UBSan, and 2M each for AArch64 (armv8.2-a and armv8-a) under qemu-aarch64: 0 mismatches. Four injected bugs (no overlapping last block, no overlapping last rotation, no null masking, no filler blend) are each caught on both architectures.
  • The 10 related stateless tests pass 20 runs each with randomized settings.

I have no ARM machine, so no ARM timings from me. The description you wrote matches the change, so I left it as is.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Re-measured on dd49f49 (15 rounds; the A/A difference was within 3% on every query this time): hasAll on nullable_found_medium_Int16 is still 1.12x to 1.14x slower than both master and the previous head (543 ms against 482 and 484 ms; 95% CI of the change +11% to +15%). Its neighbours are faster than the previous head: nullable_found_small_Int16 1.49x, nullable_found_medium_Int8/Int32/Int64 1.37x/1.19x/1.39x, medium_Int16 1.16x.

That table has 50k rows of 500-element Array(Nullable(Int16)) arrays with 1 value in 64 null, and subset is a shuffle of set, so every value is found.

The kernel harness (x86-64-v3, ASan/UBSan, AArch64 under QEMU) and the clickhouse local comparison also pass on dd49f49: 0 mismatches, and the same result hash as master.

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add a performance test for the new fast path?

The reported speedup numbers in a comment are not committed and has_all.xml only covers non-Nullable hasAll, so a potential later regression in the hasAny or null-map paths could pass unnoticed.

countIf(hasAny(x, y)) AS any_true, countIf(hasAny(x, y) != arrayExists(v -> has(x, v), y)) AS any_mismatches
FROM (SELECT CAST(arrayMap(v -> assumeNotNull(v), a), 'Array(Int8)') AS x, CAST(arrayMap(v -> assumeNotNull(v), b), 'Array(Int8)') AS y FROM arrays);

SELECT 'Int8', 'mixed', count(),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this mixed test does not test really mixed paths cause FunctionArrayHasAllAny casts both arguments to their least common supertype. So Array(Nullable(Int8)) with Array(Int8) reaches the kernel with a null map on both sides.

So "Mixed" reruns the same code path as the "Nullable" rows, with no nulls in the second array, which null_mode 0/1 already covers.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. executeImpl casts both arguments to their least common supertype (hasAllAny.h#L66-L71), and it is the only caller of the hasAll/hasAny kernels, so no query reaches them with a null map on one side only. The mixed rows add only that cast on top of the Nullable path. Without them the remaining 12 rows still match the reference on dd49f49 and on the previous head, and dropping them is part of what I asked about in #123420 (comment).

groeneai and others added 2 commits October 2, 2026 20:42
`has_all.xml` only covers `hasAll` on arrays without null maps. The new test
measures `hasAny` with values that are never found (disjoint value ranges, so
Int8 and Int16 scan the whole first array too), and `hasAll` and `hasAny` on
`Nullable` arrays with one null in 64. Table sizes keep every query under the
2 s single-run limit of the performance check on the reference build as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FunctionArrayHasAllAny` casts both arguments to their least common
supertype, so a `Nullable` first array with a non-`Nullable` second array
reaches the kernel with null maps on both sides: the mixed rows ran the same
path as the `Nullable` rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

@Ergus agreed, has_all.xml alone would not catch a regression in hasAny or in the null-map handling. Below is a test for both (tests/performance/has_any_has_all_nullable.xml), built from @Algunenano's extra cases above with two changes:

  • The hasAny tables use disjoint value ranges (0 to 99 against 100 to 199), so nothing is found for Int8 and Int16 either. With random values those types usually found a match early, and the Int8 queries took about 10 ms.
  • The medium tables are 2x and 4x smaller, so no query goes over the check's 2 s single-run limit on the reference build. At 50k rows, hasAny on nullable_missing_medium_Int32 takes 6.1 s on the reference build on x86, and 4.7 s on ARM in your run.

I ran it with perf.py against the CI amd_release builds of 860e473 (old, the same code as master for these queries) and dd49f49 (new), with max_threads = 12 as in the check. It has 20 queries and takes 3 minutes in total, 9.6 s of that to create and fill. The old build takes 78 ms to 1.55 s per query and the new one 49 to 478 ms. Every query is faster: hasAny 3.6x to 26x, hasAll on Nullable arrays 1.17x to 1.72x. Every row of the found tables gives hasAll = 1, and every row of the missing ones gives hasAny = 0. On ARM, going by your Neoverse-V3 numbers, the slowest reference query should be hasAny on missing_small at about 1.8 s (I kept that table's size).

@Algunenano the branch is yours: should I push this as a test-only commit, together with dropping the mixed rows of 05318 (see Ergus's inline comment), or would you rather add it yourself?

tests/performance/has_any_has_all_nullable.xml
<test>
    <!-- `hasAny` on integer arrays, and `hasAll` on `Nullable` integer arrays with nulls. `has_all.xml` covers `hasAll` without nulls. -->
    <substitutions>
        <substitution>
            <name>array_type</name>
            <values>
                <value>Int8</value>
                <value>Int16</value>
                <value>Int32</value>
                <value>Int64</value>
            </values>
        </substitution>
    </substitutions>

    <!-- The values of `subset` are never in `set` (0 to 99 against 100 to 199, also for Int8), so `hasAny` reads all of `set`. -->
    <create_query>CREATE TABLE missing_small_{array_type} (set Array({array_type}), subset Array({array_type})) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <create_query>CREATE TABLE missing_medium_{array_type} (set Array({array_type}), subset Array({array_type})) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <!-- One value in 64 is null, and `subset` is drawn from `set`, so all values are found. -->
    <create_query>CREATE TABLE nullable_found_small_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <create_query>CREATE TABLE nullable_found_medium_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>
    <!-- Nulls only in `set`, and the values of `subset` are never in `set`. -->
    <create_query>CREATE TABLE nullable_missing_medium_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>

    <fill_query>INSERT INTO missing_small_{array_type} SELECT arrayMap(v -> v % 100, groupArraySample(5000)(rand64(1))), arrayMap(v -> 100 + v % 100, groupArraySample(500)(rand64(2))) FROM numbers(10000000) GROUP BY number % 5000</fill_query>
    <fill_query>INSERT INTO missing_medium_{array_type} SELECT arrayMap(v -> v % 100, groupArraySample(5000)(rand64(1))), arrayMap(v -> 100 + v % 100, groupArraySample(5000)(rand64(2))) FROM numbers(6250000) GROUP BY number % 12500</fill_query>
    <fill_query>INSERT INTO nullable_found_small_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(5000)(rand64(1))), arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(500)(rand64(1))) FROM numbers(10000000) GROUP BY number % 5000</fill_query>
    <fill_query>INSERT INTO nullable_found_medium_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(5000)(rand64(1))), arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(5000)(rand64(1))) FROM numbers(12500000) GROUP BY number % 25000</fill_query>
    <fill_query>INSERT INTO nullable_missing_medium_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v % 100), groupArraySample(5000)(rand64(1))), arrayMap(v -> toNullable(100 + v % 100), groupArraySample(5000)(rand64(2))) FROM numbers(6250000) GROUP BY number % 12500</fill_query>

    <query>SELECT hasAny(set, subset) FROM missing_small_{array_type} FORMAT Null</query>
    <query>SELECT hasAny(set, subset) FROM missing_medium_{array_type} FORMAT Null</query>
    <query>SELECT hasAll(set, subset) FROM nullable_found_small_{array_type} FORMAT Null</query>
    <query>SELECT hasAll(set, subset) FROM nullable_found_medium_{array_type} FORMAT Null</query>
    <query>SELECT hasAny(set, subset) FROM nullable_missing_medium_{array_type} FORMAT Null</query>

    <drop_query>DROP TABLE IF EXISTS missing_small_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS missing_medium_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS nullable_found_small_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS nullable_found_medium_{array_type}</drop_query>
    <drop_query>DROP TABLE IF EXISTS nullable_missing_medium_{array_type}</drop_query>
</test>

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Build (ppc64le) fails on dd49f49. On PowerPC the type of a vector comparison depends on -faltivec-src-compat, and -Wdeprecated-altivec-src-compat fires at all four comparisons in sliceHasImplAnyAll.h (lines 91, 186, 195 and 217). The CI log shows only 186 and 217 because the job stopped at if.cpp, which does not instantiate the kernels. The patch below replaces them with a conversion to bool lanes, as in 22a9797 and 6b892bd.

Checked locally with clang 22:

  • The 27 TUs that include the header build for ppc64le with the CI flags. Before the patch, 22 of them fail.
  • The assembly of the kernel harness is byte-identical before and after, at -O2 and -O3, for x86-64-v3, x86-64, armv8.2-a and armv8-a.
  • Under qemu-ppc64le, 2M random hasAll/hasAny cases over the 8 integer types match a scalar reference, and three mutants of the new code are caught. x86 ASan/UBSan and -O0 runs also have 0 mismatches.

If you want, I can push it on top of dd49f49, together with the perf test from my previous comment.

Patch
diff --git a/src/Functions/GatherUtils/sliceHasImplAnyAll.h b/src/Functions/GatherUtils/sliceHasImplAnyAll.h
index fc0ff009c9e3c..918db01449400 100644
--- a/src/Functions/GatherUtils/sliceHasImplAnyAll.h
+++ b/src/Functions/GatherUtils/sliceHasImplAnyAll.h
@@ -37,6 +37,21 @@ ALWAYS_INLINE bool allLanesSet(Mask mask)
     return __builtin_reduce_and(mask) == ~0ULL;
 }
 
+/// All ones in the lanes that are not zero. Converting to `bool` lanes is `!= 0`; a comparison would depend on
+/// `-faltivec-src-compat` on PowerPC.
+template <typename Vector>
+ALWAYS_INLINE Vector nonZeroLanes(Vector vector)
+{
+    using Lanes = bool __attribute__((ext_vector_type(__builtin_vectorelements(Vector))));
+    return -__builtin_convertvector(__builtin_convertvector(vector, Lanes), Vector);
+}
+
+template <typename Vector>
+ALWAYS_INLINE Vector equalLanes(Vector lhs, Vector rhs)
+{
+    return ~nonZeroLanes(lhs ^ rhs);
+}
+
 inline ALWAYS_INLINE bool hasNull(const UInt8 * null_map, size_t null_map_size)
 {
     if (null_map == nullptr)
@@ -88,7 +103,7 @@ ALWAYS_INLINE bool sliceContains(const NumericArraySlice<T> & slice, const UInt8
         {
             Vector elements;
             memcpy(&elements, slice.data + begin + offset, sizeof(elements));
-            auto equal = elements == needle;
+            auto equal = equalLanes(elements, needle);
             if constexpr (has_null_map)
             {
                 NullBytes nulls;
@@ -183,7 +198,8 @@ bool sliceHasAllBytes(const NumericArraySlice<T> & first, const NumericArraySlic
         {
             NullBytes nulls;
             memcpy(&nulls, first_null_map + begin, sizeof(nulls));
-            elements = nulls == 0 ? elements : fillers;
+            const auto null_lanes = reinterpret_cast<Vector>(nonZeroLanes(nulls));
+            elements = (elements & ~null_lanes) | (fillers & null_lanes);
         }
         /// The comparison masks are combined with an unsigned maximum, which is an OR for lanes that are 0 or 0xFF. With
         /// `|`, LLVM merged the 16 masks into booleans and rebuilt the bytes from them in every iteration (`psllw` and
@@ -192,7 +208,7 @@ bool sliceHasAllBytes(const NumericArraySlice<T> & first, const NumericArraySlic
         Bytes hits[lanes];
         [&]<size_t... shift>(std::index_sequence<shift...>) ALWAYS_INLINE
         {
-            ((hits[shift] = reinterpret_cast<Bytes>(values == rotateLanes<shift>(elements, lane_indices))), ...);
+            ((hits[shift] = reinterpret_cast<Bytes>(equalLanes(values, rotateLanes<shift>(elements, lane_indices)))), ...);
         }(lane_indices);
         /// Combined as a tree: a chain of 16 dependent maximums limited AArch64 to one per `umax` latency.
         for (size_t width = lanes / 2; width > 0; width /= 2)
@@ -214,7 +230,7 @@ bool sliceHasAllBytes(const NumericArraySlice<T> & first, const NumericArraySlic
         {
             NullBytes nulls;
             memcpy(&nulls, second_null_map + begin, sizeof(nulls));
-            found = reinterpret_cast<SearchMask<16>>(nulls != 0);
+            found = reinterpret_cast<SearchMask<16>>(nonZeroLanes(nulls));
         }
 
         size_t i = 0;

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Yes please, push the tests and the fixx for ppc

groeneai and others added 2 commits October 9, 2026 16:55
On PowerPC the result type of a vector comparison depends on
`-faltivec-src-compat`, which made the ppc64le build fail with
`-Wdeprecated-altivec-src-compat` at the four comparisons in
`sliceHasImplAnyAll.h`. Each one is replaced by a conversion to `bool`
lanes, which is the same `!= 0` per lane and has a fixed type, as in
22a9797 and 6b892bd. The generated code is unchanged on x86-64
and AArch64.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…or search

A null map can hold any nonzero value for NULL. Without short-circuit
evaluation, `if(cond, NULL, x)` uses its `UInt8` condition as the null map,
so `arrayMap(i -> if(i % 3, NULL, i), ...)` has null bytes of 2. The vector
search subtracted one from each null byte to build a mask, which left the
lowest bits set for a byte of 2, so `hasAny` and `hasAll` found a value that
is only present as NULL.

For lanes wider than one byte the subtraction is kept, and the test of each
block ignores the low byte of every lane, the only one a null lane can keep.
On x86-64-v3 this adds one broadcast outside the loop, and a benchmark of
full scans with a null map is unchanged for every width. One-byte lanes have
no other byte, so they are compared with zero, which costs the same as the
subtraction there. Converting the null bytes to `bool` first was correct but
made x86 narrow the 8-byte comparison results again, 22-42% slower in that
benchmark for 2-, 4- and 8-byte lanes.

`05318` gets the `if` case for the six integer types; before this change it
returns 42 wrong results out of 128 for each of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/hasall-kernels-without-null-maps branch from 1565ac9 to 2bb342d Compare October 9, 2026 18:10
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed:

  • 72c8cce adds tests/performance/has_any_has_all_nullable.xml, and 8f453d3 drops the mixed rows of 05318.
  • 45ac46c is the ppc64le fix. The 27 TUs that include the header build for ppc64le with the CI flags.
  • 2bb342d fixes a wrong result found while reviewing the whole PR. Any nonzero null-map byte means NULL, but the - 1 mask in sliceContains keeps the low bit of a byte of 2. Without short-circuit evaluation, if uses its condition as the null map, so this returns 1 instead of 0 (master and has return 0):
SELECT hasAny(arrayMap(x -> if(x % 3, NULL, toInt64(x)), arrayMap(x -> toUInt8(x), materialize(range(64)))), [toInt64(2)])
SETTINGS short_circuit_function_evaluation = 'disable'

For lanes wider than one byte I kept the subtraction, and the per-block test now ignores the low byte of each lane. Their inner loop is unchanged; on x86-64-v3 the only addition is one broadcast outside the loop. 1-byte lanes compare with zero instead. Converting the null bytes to bool first was 22-42% slower for 2-8 byte lanes on x86-64-v3, because of the narrowing your comment describes. A micro-benchmark of full scans with a null map on x86-64-v3 stays within 2% for every width.

05318 now has the if case for the six types (before the fix, 42 of 128 per type were wrong). It passes 20 times under random settings. The real-header harness reports no mismatches for null bytes 1, 2, 255 and random on x86-64-v3, x86-64, ASan/UBSan, AArch64 and ppc64le.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2bb342d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests, 7 sequential jobs (amd_debug; amd_debug, distributed plan; arm_binary; arm_binary, AsyncInsert; arm_binary, ParallelReplicas; arm_binary, DBReplicated; arm_asan_ubsan, azure) / 05243_query_condition_cache_top_k_parquet not from this PR: a master regression from my #123903 (merged 17:15Z), after which a TopK read of a File(Parquet) table filtered only on _file stopped using the query condition cache (0 0 instead of 1 0 / 1 1); master was red until the revert #124977 (external, merged 19:25Z, reverts #123903; #124991 re-lands it with a fix). This run was dispatched at 18:12Z, before the revert, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the rows above (Failed: 6; the azure job is allow_failure and does not gate) #124977 (external, merged)

Session id: cron:our-pr-ci-monitor:20261010-003008

}
}
}
const bool has = sliceContains<has_first_null_map>(first, first_null_map, second.data[i]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This multi-byte hasAll path now probes first separately for every element of second, so the old batched-needle behavior disappears for 16-bit arrays. In the PR's own perf discussion, this is still the one reproducible regression: nullable_found_medium_Int16 stays 11%-15% slower than both master and the previous head (543 ms vs 482/484 ms; see #123420 (comment)).

For a Performance Improvement PR that is still an unresolved contract violation, not just noise. Please either restore a grouped hasAll path for 16-bit integer arrays here, or rerun the benchmark on the current head and narrow the PR's performance claims if this slowdown is an accepted tradeoff.

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if some corner case is slightly slower we don't mind. The net result is extremely positive and removes intrinsics

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-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements 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.

hasAll on integer arrays is up to 60% slower on x86 since #116239: the AVX2 kernels now keep null-map handling for non-Nullable arrays

4 participants