Skip to content

Optimize countBytesInFilter and countBytesInFilterWithNull for AArch64 NEON - #119555

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
JoshyDo:aarch64-neon-count-bytes-in-filter
Sep 13, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
JoshyDo:aarch64-neon-count-bytes-in-filter

Conversation

@JoshyDo

@JoshyDo JoshyDo commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Optimize countBytesInFilter and countBytesInFilterWithNull for AArch64 NEON.

Closes: #116073
Related: #116173

Target branch: master
Source branch: aarch64-neon-count-bytes-in-filter


Changelog category (leave one):

  • Performance Improvement

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

Accelerate countBytesInFilter and countBytesInFilterWithNull on AArch64 using direct NEON vector register accumulation, improving filter counting throughput by up to 15x.


Detailed Description

Prior to this PR, countBytesInFilter on AArch64 fell back to scalar byte-by-byte iteration, running at ~8 GB/s. A previous attempt in PR #116173 converted 64 bytes into a 64-bit mask via pairwise additions before popcounting, reaching ~58 GB/s.

This PR implements direct NEON in-register vector accumulation:

  1. 64-Byte Unrolled Processing:
    Processes four 16-byte registers per iteration with vld1q_u8.
  2. Modulo-256 Non-Zero Normalization:
    vcgtq_u8(v, zero) produces 0xFF for non-zero bytes and 0x00 for zero bytes. Using uint8 wrapping arithmetic, vsubq_u8(acc, vcgtq_u8(v, zero)) adds 1 for every matching byte (0 - 0xFF == +1), completely eliminating expensive bit-packing or popcount instructions.
  3. Periodic 16-Bit Widening:
    Every 255 iterations (16,320 bytes), lanes are accumulated pairwise into 16-bit registers using vpadalq_u8, preventing 8-bit lane overflow (max lane count: 4 * 510 = 2040 << 65535).
  4. Reduction to 64-bit Count:
    Horizontal reduction vaddlvq_u16 flushes each chunk to the 64-bit count.
  5. Strict Null-Map Handling in countBytesInFilterWithNull:
    Computes (filt != 0) && (null == 0) by pre-normalizing boolean masks before combining via vandq_u8(vcgtq_u8(filt, zero), vceqzq_u8(null_map)). This avoids incorrect matches on non-boolean filter bytes (such as 2, 42, 255) that raw byte-wise vbicq_u8 produced.
  6. Range Safety:
    An empty range (start == end) returns 0 without touching the pointers; any other invalid precondition (start > end, or a null filt/null_map for a non-empty range) is a programming error and is caught loudly by chassert instead of being silently absorbed by a fallback. Loop conditions use pointer distance checks static_cast<size_t>(end_pos - pos) >= chunk_size.
  7. Scalar Tail Fix (all architectures):
    The scalar tail of countBytesInFilterWithNull used (*pos & ~*pos2) != 0, which overcounts whenever both bytes are non-zero but their bitwise combination is (for example 2 & ~1 == 2). It now reads (*pos != 0 && *pos2 == 0), matching the vectorized paths. This is a genuine correctness fix and affects x86-64 as well; it is pinned by the new stateless test 05189_count_bytes_in_filter_with_null.
  8. Direct NEON Header Inclusion:
    Added #include <arm_neon.h> under #if defined(__aarch64__) && defined(__ARM_NEON) directly in ColumnsCommon.cpp for IWYU compliance.

Benchmark Results (Apple Silicon M-series, 64 KiB Blocks)

Implementation Latency (64 KiB) Throughput (64 KiB) Speedup vs Baseline
Scalar Baseline 7,432 ns 8.21 GB/s 1.0x
PR #116173 (Bitmask Popcount) 1,090 ns 58.49 GB/s 6.7x
NEON In-Register Accumulator (This PR) 497 ns 122.79 GB/s 15.0x

For countBytesInFilterWithNull (dual-stream 64 KiB filt + 64 KiB null_map):

  • Latency: 980 ns
  • Filter Throughput: 62.27 GB/s
  • Aggregate Memory Read Bandwidth: 124.54 GB/s

Verification

  • Exhaustive Byte-Pair Testing: 100% pass across all 65,536 (filt_byte, null_byte) combinations across sizes {1, 63, 64, 65, 128}.
  • Boundary Sizes: Verified against scalar reference across sizes 0, 1, 15, 16, 63, 64, 65, 127, 128, 16319, 16320, 16321, 65536, and 10,000,000 bytes with random, boolean, all-0, all-255, and offset subranges.
  • Unaligned Memory Offsets: 100% pass across all 4,096 combinations of pointer alignment (filt 0..15 x null_map 0..15 x lengths).
  • Null and Inverted Range Safety: Verified nullptr inputs (both zero and non-zero ranges), inverted ranges (start > end), start == end, and !null_map paths under ASan and UBSan without error.
  • Overflow: Verified 100,000,000 consecutive 1s with zero lane overflow.

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

Version info

  • Merged into: 26.9.1.1404 (included in 26.9 and later)

…4 NEON

Accelerate countBytesInFilter and countBytesInFilterWithNull on AArch64
using direct NEON vector register accumulation:
- 64-byte unrolled processing loop using uint8x16_t registers.
- Non-zero normalization with vsubq_u8(acc, vcgtq_u8(v, zero)) exploiting
  modulo-256 arithmetic where - 0xFF == + 1.
- For countBytesInFilterWithNull, form boolean masks prior to combining:
  vandq_u8(vcgtq_u8(filt, zero), vceqzq_u8(null_map)) ensuring strict
  equivalence to (filt != 0) && (null == 0) for arbitrary non-boolean byte values.
- Periodic 16-bit widening via vpadalq_u8 every 255 iterations (16,320 bytes)
  preventing uint8 lane overflow, flushed via vaddlvq_u16 to 64-bit count.
- Fix scalar tail and fallback for countBytesInFilterWithNull to check
  (*pos != 0 && *pos2 == 0).
- Leaves x86 (SSE2) and generic fallback paths unaffected.

Performance on Apple Silicon (64 KiB blocks):
- countBytesInFilter: ~125 GB/s (latency ~485 ns, ~15x faster than scalar)
- countBytesInFilterWithNull: ~62 GB/s filter BW / ~124 GB/s total memory BW

Closes: ClickHouse#116073
@CLAassistant

CLAassistant commented Sep 11, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 11, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 12, 2026

@alexey-milovidov alexey-milovidov 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.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [24e2cd0]

Summary: ✅


AI Review

Summary

This PR replaces the AArch64 implementations of countBytesInFilter and countBytesInFilterWithNull with a direct NEON accumulation loop and adds a focused stateless regression test for the non-boolean countIf tail case. I did not find a remaining correctness or contract issue in the current diff; the earlier review comments about invalid-precondition fallbacks, missing regression coverage, and the unnecessary no-parallel tag are all addressed.

Missing context / blind spots
  • ⚠️ The AArch64 build jobs (Build (arm_asan_ubsan), Build (arm_binary), Build (arm_debug), Build (arm_msan), Build (arm_tsan)) were still pending when I reviewed this on 2026-09-12, so I could not validate the new NEON path on CI artifacts yet. Green ARM build/test results would close this gap.
Final Verdict

✅ No remaining review findings in the current diff. Merge should still wait for the pending AArch64 CI results because the changed hot path is __aarch64__-only.

LLVM Coverage Report

Measured on commit 24e2cd0.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 16/17 (94.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 12, 2026
Comment thread src/Columns/ColumnsCommon.cpp Resolved
Comment thread src/Columns/ColumnsCommon.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 24e2cd0da with master 43cd9eb7c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e3d6e2b04; 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.

Compile time of recompiled translation units

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

Job report

@JoshyDo

JoshyDo commented Sep 12, 2026

Copy link
Copy Markdown
Contributor Author

Addressed review feedback in dc5ea3308:

  1. Invalid preconditions: Replaced silent early returns with if (start == end) return 0; fast-path and loud chassert(start <= end) + pointer assertions when end > start.
  2. Stateless regression test: Added 05189_count_bytes_in_filter_with_null.sql pinning the cross-architecture countIf non-boolean UInt8 condition fix on Nullable columns across boundary block sizes (64, 65, 100, 129).

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status pass (2026-09-12), no public commits were needed.

  • Public CI is fully green: 0 failed tests across the whole PR workflow report (SQLLogic test was still in flight). Approved by @alexey-milovidov, AI Review verdict ✅ no findings, 0 unresolved review threads.
  • CH Inc sync was red for a reason unrelated to this pull request. It reported build failed, but the actual failing private job was Style check → ruff: ci/workflows/auto_releases.py:59:5: invalid-syntax: Duplicate keyword argument "engine" (plus create_release.py, nightly_cloud_api_docs.py, sync_silk.py, weekly_cfi.py). That is a bug in private master that was red on every private pull request; it has since been fixed there. The sync run for this pull request had simply started before the fix landed, so it used the broken merge base. I merged current private master into sync-upstream/pr/119555 (clean merge, new head 30de1bed); the sync branch still carries exactly the three-file public delta and private CI is re-running.
  • Branch is 581 commits behind master but was refreshed today and is green, so no master merge was done.
  • Updated the pull request description: turned the commented-out link placeholders into real Closes:/Related: lines, and corrected items 6 and 7, which still described the old silent if (!filt || start >= end) return 0; fallbacks instead of the chassert preconditions that replaced them, and understated the scalar-tail change — (*pos & ~*pos2) != 0 → (*pos != 0 && *pos2 == 0) is a cross-architecture correctness fix, not just a tail tidy-up.

Merge is a human's call.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 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: a8187840-22a4-49e4-9013-abfd5f737cd7
  • MIRAI run: dc4e8c79-3c0e-4d04-8d21-a07e82d4cc5f
  • PR check IDs:
    • clickbench_211932_1789240140
    • clickbench_211938_1789240140
    • clickbench_211945_1789240140
    • tpch_adapted_1_official_211956_1789240140
    • tpch_adapted_1_official_211965_1789240140
    • tpch_adapted_1_official_212003_1789240140

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit cf56cde Sep 13, 2026
174 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 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@JoshyDo @alexey-milovidov — changelog category: Performance Improvement → suggested Bug Fix (user-visible misbehavior in an official stable release).

Why: src/Columns/ColumnsCommon.cpp:243 rewrites the scalar tail of countBytesInFilterWithNull from (*pos & ~*pos2) != 0 to (*pos != 0 && *pos2 == 0), which changes query results on every architecture: SELECT countIfOrNull(if(number % 2, toUInt8(1), NULL), toUInt8(2)) FROM numbers(130) returns 130 on the 26.7.1.1 binary and 65 on this branch. Shipping that under an empty Performance Improvement entry leaves a wrong-result fix undocumented and unbackported. The perf claim itself also has no tests/performance/ benchmark.

Ignore if the current category is intentional.

@clickgapai

Copy link
Copy Markdown
Contributor

@JoshyDo @alexey-milovidov — title/description suggestions:

Description (currently incomplete):

  • Why: Item 5 presents the null-map normalisation as a property of the new NEON code ('This avoids incorrect matches on non-boolean filter bytes ... that raw byte-wise vbicq_u8 produced'), but the same commit also rewrites the shared scalar tail at src/Columns/ColumnsCommon.cpp:243, which changes results on x86_64 and on every non-NEON architecture, not just inside the new NEON block. The description does not mention that, and the regression test it adds does not exercise the changed line.

  • Suggested addition:

    The change to the scalar tail of countBytesInFilterWithNull is not NEON-specific -- it fixes a wrong result on all architectures:

    -- 26.7.1.1: 130   this branch: 65   (correct: 65)
    SELECT countIfOrNull(if(number % 2, toUInt8(1), NULL), toUInt8(2)) FROM numbers(130);

    On x86_64 the old expression only affected the last rows % 64 rows of each block; on AArch64 (no SIMD branch before this PR) it affected every row.

    Note that 05189_count_bytes_in_filter_with_null.sql does not reach the changed line: countIf(Nullable, cond) resolves to AggregateFunctionIfNullUnary, which merges the condition into the null map and calls addBatchSinglePlaceNotNull(..., -1) (src/AggregateFunctions/Combinators/AggregateFunctionIf.cpp:202), so it goes through countBytesInFilter, not countBytesInFilterWithNull. The four queries in that file return the committed reference output (32/50/32/64) on 26.7.1.1. The -OrNull/-OrDefault form above does reach it (AggregateFunctionOrFill.h:251 -> AggregateFunctionIf.h:199, which substitutes num_arguments - 1).

Ignore if intentional.

@clickgapai

Copy link
Copy Markdown
Contributor

@JoshyDo @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@Algunenano

Copy link
Copy Markdown
Member

I just stumbled into this PR when working on removing intrinsics and noticed 2 things:

  • NEON code has too many intrinsics. It'd be nice if we could do the same just guiding the compiler.
  • This approach of accumulating bytes is actually faster and we should adopt it for x86 (vs mask + popcount).

Having a look

@Algunenano

Copy link
Copy Markdown
Member

PR with this change (among others): #121403

@JoshyDo

JoshyDo commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Algunenano ! Really cool to see the accumulator pattern translate so well to x86, and I love how clean the generic vector implementation turned out in #121403. Awesome follow-up!

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
…ull-map-byte-is-a-predicate

Conflicts in `ColumnNullable.cpp`, `ColumnVariant.cpp` and `ColumnsCommon.cpp`, all resolved to
master's side. Master now reads those null maps as predicates itself: both `applyNullMapImpl`
negations were fixed in 990aba5 (ClickHouse#119785), and `countBytesInFilterWithNull` was rewritten
with a predicate-correct vector path and scalar tail (ClickHouse#119555 and the follow-up rework), so this
branch no longer changes those three sites or their comments.

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-data-types Type system & core datatypes used across query planning/execution. external Author is not a member of the ClickHouse organization 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.

countBytesInFilter counts filter bytes one at a time on aarch64 — its 64-byte bitmask path is gated on __SSE2__

6 participants