Skip to content

Enable the 64-byte filter counting path on AArch64 - #116173

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:aarch64-count-bytes-in-filter-wide-path
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:aarch64-count-bytes-in-filter-wide-path

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Enable the 64-byte filter counting path on AArch64

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 countIfOrNull over a Nullable argument returning a count that depended on the block size when the condition was a UInt8 value other than 0 or 1. Also sped up filter row counting on AArch64: countBytesInFilter and countBytesInFilterWithNull reduce a filter 64 bytes at a time using a bitmask and popcount, but that loop was gated on __SSE2__, so AArch64 builds counted one byte per iteration. Closes #116073.

Description

Both wide loops in src/Columns/ColumnsCommon.cpp, and the private toBits64 they call, sat behind
a bare #if defined(__SSE2__): an x86-64 baseline feature, not runtime dispatch, so x86 always
compiled the fast path and AArch64 never did. The guards now also admit
defined(__aarch64__) && defined(__ARM_NEON), with an #elif arm defining toBits64 via
bytes64MaskToBits64Mask from this module's header, which already has a NEON tier. NEON is
unconditional at the AArch64 baseline, and this file already calls that helper in
filterArraysImplGeneric and filterArraysImplInPlace. On x86 the guard is inert.

One correctness fix rides along, and it does change x86. An -If condition column is forwarded as
a raw UInt8, so bytes outside 0/1 reach these loops, and countBytesInFilterWithNull's scalar
tail counted (*pos & ~*pos2) != 0 while its wide loop counts filter != 0 && null == 0. These
differ on a NULL row whose condition byte keeps a set bit outside the null byte: of the 65536
(filter, null) pairs the tail disagrees on 58720, always over-counting, never where the wide loop
errs. countIfOrNull(if(number % 2 = 0, NULL, 1), toUInt8(2)) over 100 rows returns 68 or 100
today depending on where the 64-byte boundary falls, against a true 50. The tail now uses the wide
loop's predicate, removing the block-size dependence everywhere. This is the correction
031132038b1e89e applied to the > 0 comparisons here; countBytesInFilter's tail already used
!= 0.

AArch64 mask equivalence for 0/1 filters was checked exhaustively under qemu-aarch64-static
against the pre-change build: 0 mismatches, mutation-controlled. The new test covers the non-binary
UInt8 condition, pinning block lengths via max_block_size; all five of its cases fail without the
tail fix (100/68/68/63/65 against 50/50/50/31/64).

The ARM Performance Comparison at 8088404f measures it: rewrite_sumIf 575 ms to 374 ms on
arm_release (1.54x) against 227/227 ms on the amd_release control. 27 arm queries were flagged
faster, 0 slower; on amd, 0 either way.


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

countBytesInFilter and countBytesInFilterWithNull reduce a filter 64 bytes at
a time with a bitmask and popcount, then count the residue byte by byte. Both
wide loops, and the private toBits64 helper they call, were guarded by a bare
'#if defined(__SSE2__)'.

__SSE2__ is an x86-64 baseline feature, so this was never runtime dispatch:
x86 always compiled the wide loop and AArch64 never did, counting the whole
filter one byte per iteration.

Widen both guards to also admit __aarch64__ && __ARM_NEON, and add an #elif
arm defining toBits64 via bytes64MaskToBits64Mask from this module's header,
which already has a NEON tier. No feature detection is needed because NEON is
unconditional at ClickHouse's AArch64 baseline, verified on both the modern
armv8.2-a profile and the NO_ARMV81_OR_HIGHER compat profile. This is not a
new ARM SIMD surface either: ColumnsCommon.cpp already calls that helper
unconditionally in filterArraysImplGeneric and filterArraysImplInPlace.

x86 is unaffected by construction, since __SSE2__ is defined at all four x86
levels and the new #elif is therefore unreachable. Measured: compiling the
file before and after at -march=x86-64-v3 and at -march=x86-64 yields a
byte-identical preprocessed translation unit, identical disassembly, and a
byte-identical object once DWARF line data is excluded.

A miscount would silently change result cardinality, so equivalence was tested
exhaustively rather than sampled: lengths 0..300 crossed with start offsets
0..7 and 7 byte patterns, the block boundary lengths, and randomised 1 MiB
buffers, for both functions, cross-compiled and run under qemu-aarch64-static
against the pre-change scalar-only build as oracle. Zero mismatches on both
AArch64 profiles under gcc-13 and clang-22, and a digest over the results is
identical on AArch64 and x86-64, so the wide path returns the same answers on
both. Dropping a single NEON instruction reddens every check, so those are
measurements rather than blind comparisons.

The new stateless test pins block boundary lengths through max_block_size and
uses partial selectivity, because an all-pass filter cannot distinguish a
correct block mask from a broken one. It cannot fail on x86, where behaviour is
unchanged; its purpose is to exercise the new path in the AArch64 CI jobs. It
was checked in both directions against a build with a deliberately corrupted
mask.

Closes ClickHouse#116073
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change cold. Verdicts below; every disagreement is backed by a
measurement, not an argument.

❌ countBytesInFilterWithNull: the wide path and the scalar tail disagree for non-binary
UInt8 conditions, so change the tail to boolean predicates.
Disagreed on the remedy. The
factual half is right, and raw bytes do reach this function through the -If / -OrNull
aggregate path, which does not normalise the condition column. But over all 65536
(filter_byte, null_byte) pairs on a 64-byte block, against ground truth
filter != 0 && null == 0: the wide path is wrong in 0 cases, the tail in 58720, and
there are 0 pairs where the tail is right and the wide is wrong. Per row the tail only ever
over-counts (0 violations of tail >= truth). So the wide path is the correct arm and the tail is
a pre-existing inconsistency, identically on x86 today. For filter=2, null=1 at length 100:
truth 0, x86 today 36, AArch64 before 100, AArch64 after 36. This change moves AArch64 towards
truth and onto the exact x86 answer, which the cross-architecture digest confirms bit-for-bit over
the whole raw-byte sweep. Editing the tail would change x86 behaviour and falsify the
byte-identical no-op claim, so it is a separate change.

⚠️ The new test can be bypassed by randomized aggregate JIT. Agreed on the mechanism,
disagreed that it applies here, after measuring it. A compiled aggregate does skip
addBatchSinglePlace (Aggregator.cpp:2002-2005), which is the only route to
countBytesInFilter, and tests/clickhouse-test does randomize
compile_aggregate_expressions. But executeWithoutKeyImpl has exactly one call site
(Aggregator.cpp:2270) and it passes a literal false for that flag, under a
/// TODO: Enable compilation after investigation left by the revert of #53757. Every query
here is without-key, so the setting cannot reach that continue. All four randomizer draws of
compile_aggregate_expressions x min_count_to_compile_aggregate_expression were measured with
instrumentation counters and reach the changed code identically: the wide loop runs 0 / 1 / 2
times at lengths 63 / 64 / 128 on both functions, with a no-filter negative control at 0. The
JIT-on arm was confirmed armed rather than merely silent (CompileFunction = 1 and a
Compile expression countIf()(UInt8) trace line, both absent when the setting is 0), and
patching that hardcoded false under an env gate does zero the counters, so the instrument can
read a bypass. No setting is pinned: pinning one would protect nothing, and if that TODO is
ever resolved a pin would hide the coverage regression it was meant to catch, since the test
would keep passing while no longer exercising the path.

⚠️ No measured AArch64 performance evidence. Agreed as a fact, not as a blocker. I have no
AArch64 host; emulation gives correctness parity and no timings, so publishing a number here
would be publishing something I did not measure. tests/performance/countIf.xml already
benchmarks this path and the performance profile disables JIT, so this PR's own AArch64
Performance Comparison run is the arbiter. Every figure quoted in the description is the
reporter's, attributed. If that run shows no improvement, I will say so.

💡 Add a condition = 2 boundary case. Declined: it would pin behaviour the function
documents as out of contract, and encode the tail's inconsistency at sub-64 lengths.

💡 Add a path-discriminating oracle to the stateless test. Declined: the change is
compile-time only and result-preserving, so no query can distinguish the two paths by value, and
a timing assertion in the parallel suite is unsatisfiable. What the test does detect is a broken
64-byte mask, checked in both directions against a deliberately corrupted build.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Gate Answer
a Deterministic repro? Yes, as a compile-time predicate rather than a runtime failure: clang -dM -E shows __SSE2__ defined at all four x86 levels and undefined on both AArch64 profiles, so the wide loop is provably compiled out on ARM. The consequence is measured by instrumenting the loop: on x86 a 65-row filter runs 1 wide iteration, 63 rows runs 0, 128 rows runs 2.
b Root cause explained? The 64-byte bitmask + popcount loops in countBytesInFilter / countBytesInFilterWithNull, and the toBits64 they call, are guarded by #if defined(__SSE2__). __SSE2__ is an x86-64 baseline feature, so this is not runtime dispatch: the guard admits no ARM target and AArch64 falls through to the byte-at-a-time tail for the whole filter.
c Fix matches root cause? Yes. The guards are widened to admit __aarch64__ && __ARM_NEON, and an #elif arm defines toBits64 via bytes64MaskToBits64Mask, the NEON-capable helper in this module's own header. No masking, no widened bound, no defensive check. Both loop bodies and both scalar tails are untouched.
d Test intent preserved / new tests added? New stateless test 04946_count_bytes_in_filter_block_boundary, no test weakened or removed. It pins the filter length to block boundaries via max_block_size and uses partial selectivity (number % 3 = 1), since an all-pass filter cannot distinguish a correct block mask from a broken one.
e Demonstrated in BOTH directions? Yes, twice. (1) The SQL test passes on this change and FAILS on a build with a deliberately corrupted x86 mask, where length 63 correctly stays at 21 (scalar tail) while every length >= 64 changes. (2) The AArch64 equivalence harness reports 0 mismatches, and dropping one NEON instruction reddens all four of its oracles (20286 fatal mismatches).
f Fix general across CODE paths? Both functions with a wide loop are fixed, not just the one named in the issue; the countBytesInFilter(const IColumn::Filter &) forwarder inherits it. toBits64 is static and has exactly 3 references in the tree, all in this file. 8 sibling files carry an __SSE2__ guard with no __aarch64__ arm and are deliberately left alone: different mechanisms, one PR each.
g Fix generalizes across INPUTS? Lengths 0..300 x start offsets 0..7 (every alignment, every tail residue mod 64) x 7 byte patterns (all-zero, all-one, alternating, one set byte per block, random 0/1, random full-range, random high-bit-set), plus explicit 0/1/2/63/64/65/127/128/129/191/192/193/255/256/257 and randomised 1 MiB buffers. Both AArch64 build profiles, gcc-13 and clang-22.
h Backward compatible? Yes. No setting, no serialization format, no on-disk change, so no SettingsChangesHistory.cpp entry applies. The change is a preprocessor guard: x86 output is byte-identical (identical preprocessed TU and disassembly at both -march=x86-64-v3 and -march=x86-64), and non-x86 non-ARM targets keep today's scalar behaviour.
i Invariants and contracts preserved? The invariant is that popcount of the 64-bit mask equals the number of non-zero bytes in the block, with the tail counting the residue identically. bytes64MaskToBits64Mask returns the same mask as the SSE2 toBits64 (bit i set iff byte i is non-zero), verified exhaustively against an independent truth function. A cross-architecture digest over the wide path's results is identical on AArch64 and x86-64, so ARM now returns the shipped x86 answers, including for filter bytes outside the documented 0/1 domain. No allocation, no lifetime, no locking, no error path involved.

50 randomized runs of the new test at -j 8: 50 passed, 0 failed. No no-parallel tag needed.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8088404]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: 'key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0' (STID: 2508-5166) FAIL cidb
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

This PR enables the existing 64-byte mask-plus-popcount filter-counting path on AArch64 and fixes the scalar tail of countBytesInFilterWithNull so it matches the wide-path predicate for non-binary UInt8 conditions. I checked the current diff, the linked ARM measurements in #116073, and the existing discussion thread; the new stateless test covers the user-visible correctness bug, and I did not find any remaining correctness, compatibility, or performance issues in the patched paths.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 19/19 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @Avogar, could you review this? The 64-byte bitmask and popcount loops in countBytesInFilter and countBytesInFilterWithNull sat behind a bare #if defined(__SSE2__), which is an x86-64 baseline feature, so AArch64 never compiled them and counted the whole filter one byte per iteration; the guards now also admit __aarch64__ && __ARM_NEON and reuse the NEON tier this module header already has.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8088404fc with master 583fc5270 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 710.09 MiB 707.05 MiB -3.04 MiB (-0.43%)

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.

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 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=22 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 621ed6ae-1906-424c-adc5-a618f486f1ed
  • MIRAI run: fd93dd81-fb80-45fe-ab6e-50be9661624b
  • PR check IDs:
    • clickbench_361581_1787687510
    • clickbench_361587_1787687511
    • clickbench_361598_1787687510
    • tpch_adapted_1_official_361605_1787687510
    • tpch_adapted_1_official_361622_1787687511
    • tpch_adapted_1_official_361651_1787687509

countBytesInFilterWithNull reduces 64 bytes at a time with a bitmask that sets
bit i iff filter byte i is non-zero, then counts mask & ~null_mask, i.e.
filter != 0 && null == 0. Its byte-at-a-time tail instead counted
(*pos & ~*pos2) != 0.

Those differ on a NULL row whose filter byte keeps a set bit outside the null
byte. An -If condition column is forwarded as a raw UInt8, so such bytes are
reachable: countIfOrNull(if(number % 2 = 0, NULL, 1), toUInt8(2)) over 100 rows
returned 68 or 100 depending on where the 64-byte boundary fell, against a true
answer of 50. Of the 65536 (filter, null) byte pairs the tail disagreed with the
wide loop on 58720, always by over-counting, and never on a pair where the wide
loop is wrong.

The tail now uses the wide loop's predicate, so the result no longer depends on
block size. This is the correction 0311320 made to the > 0 comparisons
in this file; countBytesInFilter's tail already used != 0.

Plain countIf over a Nullable argument is unaffected: AggregateFunctionIfNullUnary
folds the null map into the condition and reaches countBytesInFilter instead.

The two NOTE blocks were stale in every clause: they described a > 0 comparison
neither function has used since 0311320, and claimed != 0 precludes SSE2
when the SSE2 loop that commit introduced implements exactly != 0.

Reported by the AI review on ClickHouse#116173.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Adopted the second suggested fix in b250f97: the
countBytesInFilterWithNull tail is now (*pos != 0) && (*pos2 == 0), and the test pins
max_block_size at 63 / 64 / 100 over non-binary UInt8 conditions.

One correction to the finding, which does not change the outcome. The trace is not introduced by
this PR: 68 / 68 / 100 / 100 for bs = 100 / 64 / 63 / 10 reproduces on a pristine master build
that contains none of this branch, because countBytesInFilterWithNull is compiled with the wide
loop on x86 today. So the block-size dependence is pre-existing and x86-visible, not new and
ARM-only. That makes it worth fixing here rather than deferring, which is why I took the tail
rather than normalizing the caller: normalizing if flags would leave the same split for every
other caller of the helper, and the tail change makes both paths agree with the truth instead of
merely agreeing with each other.

Verified in both directions on x86 at equal max_block_size, with the pre-change binary kept as a
control: the tail fix moves the trace to 50 / 50 / 50 / 50 against a true 50, the new test cells
fail on the pre-change binary (100/68/68/63/65 against 50/50/50/31/64) and pass 50/50 randomized
runs after it. Plain countIf over a Nullable argument is unaffected and measures identically on
both binaries, since AggregateFunctionIfNullUnary folds the null map into the condition and
reaches countBytesInFilter instead; the changelog entry now says countIfOrNull only.

This is the same correction 031132038b1e89e made to the > 0 comparisons in this file. The two
stale NOTE blocks it left behind are also gone: they described a > 0 comparison neither function
has used since, and claimed != 0 precludes SSE2 when that commit's own SSE2 loop implements
exactly != 0.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 24, 2026
@@ -0,0 +1,54 @@
-- A filter is counted 64 bytes at a time with a byte-at-a-time tail, so a count must not

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.

@groeneai Remove this test. The functionality is already covered by existing tests.

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.

Trimmed it to the 5 cases that actually catch the bug, in 8088404 (54 -> 8 lines).

You were right about most of it. The block-size sweep over 0/1 filters asserted nothing this PR affects: countBytesInFilter's tail already compared != 0 before this change, so those rows passed on master. I removed all 26 of them.

The 5 remaining rows are not covered, though, and I did not want to drop them silently. This PR also fixes a correctness bug: countBytesInFilterWithNull's tail counted (filter & ~null) != 0 while its wide loop counts filter != 0 && null == 0, so countIfOrNull with a UInt8 condition outside 0/1 returned a block-size-dependent count. Both per-arch Bugfix validation jobs on the previous commit ran this test against master HEAD and it failed on exactly these 5 rows (amd64 100/68/68/63/65, aarch64 100/100/100/63/129, against 50/50/50/31/64), which is why those jobs report OK.

Removing them entirely also trips the merge gate: new_tests_check.py requires a pr-bugfix PR to carry a test that reproduces on master.

Happy to drop these too if you would rather change the changelog category to a CI/performance one and let the correctness half go untested. Your call.

Only the non-binary UInt8 condition cases fail without the fix. The block-size
sweep over 0/1 filters passed on master already, so it asserted nothing this
change affects: countBytesInFilter's tail compared != 0 before this PR too, and
the AArch64 mask equivalence for 0/1 filters is checked exhaustively out of tree.

Both per-arch Bugfix validation jobs on b250f97 confirm which cases
discriminate: they ran this test against master HEAD and it failed on exactly
these five rows, amd64 reporting 100/68/68/63/65 and aarch64 100/100/100/63/129
against 50/50/50/31/64.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8088404

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will
be posted here when it opens.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0 (STID 2508-5166) pre-existing trunk assert on the lightweight-update key-prefix path; carrier is the fuzzed t_lwu_key_prefix__fuzz_35 table from 04509_lwu_sorting_key_common_prefix.sql, assert site src/Storages/MergeTree/KeyCondition.cpp:5033. Not reachable from this diff a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Stress test (amd_tsan) / Hung check failed, possible deadlock found a single already-cancelled scalar subquery parked 464s in PullingAsyncPipelineExecutor::cancel() under evaluateScalarSubqueryIfNeeded.cpp:310; trunk-wide (1294 hits / 570 PRs / 165 master rows in 30 days). Distinct from the ThreadFuzzer log-mutex convoy: this log has 0 pthread_mutex_lock frames and one stuck query a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

Neither failure is reachable from this diff. On amd_debug and amd_tsan the __SSE2__ branch is
selected and is byte-identical to master, so the new __aarch64__ && __ARM_NEON branch is not
compiled at all; and countBytesInFilter counts set bytes in a filter mask, with no involvement in
MergeTree primary-key boundary tuples or in analyzer scalar-subquery evaluation.

Session id: cron:our-pr-ci-monitor:20260825-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (amd_tsan) hung check row above: #116455.

The parked cancel was a symptom, not the defect. Ordering two nested Array/Tuple/Map/Object
values was exponential in nesting depth, because this repository builds C++23 and Field has no
operator<=>, so std::__synth_three_way asked each equal element both t < u and u < t and both
probes recursed to full depth. The fuzzed 30-level argument in that query therefore sat inside one
uninterruptible add, which is also why max_execution_time never fired. Reproduced and fixed on the
official 25.8.33.6 and 26.8.1.2008 builds as well as master.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted, old_compatibility) / key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0 (STID 2508-5166) row above: #116473. It refuses an ALTER TABLE ... MODIFY ORDER BY that flips a sorting key column's sort direction, which is the state the fuzzer reached and which left the part index physically descending while the new metadata reported all-ascending.

@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 4, 2026
@JoshyDo

JoshyDo commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Nice work on enabling the 64-byte path for AArch64!

However, constructing a 64-bit mask on NEON using a vpaddq_u8 tree to mimic x86 pmovmskb introduces noticeable latency and instruction overhead just to immediately feed std::popcount.

On AArch64, an in-register vector accumulator using:

  • vsubq_u8(acc, vcgtq_u8(v, 0)) (which subtracts 0xFF, equivalent to +1 in uint8 modulo-256 arithmetic)
  • periodic 16-bit widening via vpadalq_u8 every 255 iterations (16,320 bytes)
  • a single horizontal finish vaddlvq_u16

outperforms the bitmask + std::popcount approach significantly on standard ClickHouse block sizes (64 KiB / L1-L2 resident):

Implementation Latency (64 KiB Block) Throughput vs PR #116173
Master (Scalar) 8,862 ns 6.89 GB/s Baseline
PR #116173 (Bitmask + popcount) 965 ns 63.19 GB/s 1.00x
NEON In-Register Accumulator 627 ns 97.20 GB/s +54% faster

(Tested on Apple Silicon / Clang -O3 across 20,000 iterations).

This also simplifies countBytesInFilterWithNull by applying vbicq_u8(filt, null_map) (filt & ~null_map) before the comparison in a single instruction.

Happy to provide a patch or push a commit if you'd like to integrate this into your PR!

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the detailed numbers. Two things here, and they land differently.

vbicq_u8(filt, null_map) is the predicate this PR removes as wrong. filt & ~null_map is a byte-level and-not, and the correctness half of this PR exists because it disagrees with filter != 0 && null == 0 once the condition byte is not 0 or 1, which is what -If/-OrNull deliver: filter byte 2, null byte 1 gives 2 & ~1 = 2, so a NULL row gets counted. Over all 65536 (filter, null) byte pairs the two predicates differ on 58720, always over-counting. The existing wide loop is correct precisely because it reduces each byte to one bit before the and-not (toBits64(pos) & ~toBits64(pos2)); folding the raw bytes with vbicq_u8 restores the shape that 04946_count_bytes_in_filter_block_boundary.sql now catches. The order has to stay, e.g. vandq_u8(vcgtq_u8(filt, vdupq_n_u8(0)), vceqzq_u8(null)).

The accumulator has a length ceiling that a 64 KiB block never reaches. vpadalq_u8 adds at most 510 per u16 lane per flush, so the 16-bit stage saturates after 128 flushes: 0.5 to 2 MiB per call, depending on how many accumulators you keep. countBytesInFilter is not bounded that way, since most callers hand it a whole per-block filter and max_block_size is a user setting, and today's loop accumulates into a size_t, so it is length-independent. Your shape needs a third accumulation level, or a bounded outer chunk loop.

On the timings. I have no ARM host, so I cannot reproduce 627 ns against 965 ns. The arbiter this PR named has run since, though: arm_release Performance Comparison at head 8088404f. rewrite_sumIf (SELECT sumIf(1, 1) FROM numbers(1000000000), rewritten to countIf, so countBytesInFilter is the hot loop) went 575 ms to 374 ms, 1.54x, while the amd_release control, where this diff compiles byte-identically to master, sits at 227 ms to 227 ms. Suite-wide the harness flagged 27 queries faster and none slower on arm, and none in either direction on amd.

So the bitmask path is already measurable on the CI runner, and your accumulator is a further, separate step. I would rather not carry an unmeasured kernel through a bugfix PR, and I cannot take a commit onto this branch, so I am keeping this one as it is. It adds no SIMD kernel of its own: it reuses bytes64MaskToBits64Mask, which already has a NEON tier and ten call sites, whereas a count-specific accumulator would be a new one. Opened as its own PR, that same arm_release job measures it against master on the same hardware, which is a stronger claim than a standalone microbenchmark.

@JoshyDo

JoshyDo commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Opened the follow-up PR here as discussed: #119555

Includes the strict boolean pre-normalization for countBytesInFilterWithNull (vandq_u8(vcgtq_u8(filt, zero), vceqzq_u8(null))), defensive pointer/range checks, and 100% pass across all 65k byte-pair edge cases. Thanks for the thorough review and guidance!

@JoshyDo

JoshyDo commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Quick clarification regarding the accumulator length ceiling:

The 16-bit accumulator is not preserved across flushes—it is declared inside the chunk loop and flushed via vaddlvq_u16 into the 64-bit size_t count every 255 iterations (16,320 bytes).

Each uint16 lane only ever accumulates up to 4 * 510 = 2,040 (well within the 65,535 limit) before being re-zeroed, so the algorithm is fully length-independent and does not saturate on large filters (tested up to 100M+ elements without overflow).

@groeneai

Copy link
Copy Markdown
Collaborator Author

Point 2 was wrong about your PR, so I retract it. I read the pushed code at 3306e622 rather than the description this time: acc16 is declared inside each chunk body, the four vpadalq_u8 put at most 2040 into a u16 lane, and vaddlvq_u16 widens to u32 (16320 max) before it lands in the size_t count, so the kernel is length-independent exactly as you say. My ceiling came from reading the 15:32Z sketch as one accumulator widened every 255 iterations with no re-zero, which is not what you wrote.

The predicate landed right: vandq_u8(vcgtq_u8(filt, zero), vceqzq_u8(null)) in both the chunk and the remainder loop of both functions, and no vbicq_u8. Reading that diff, the NEON semantics agree with the x86 path in both functions, including the non-0/1 filter bytes this PR is about.

One overlap is worth flagging for whoever reviews the two together. #119555 also changes the countBytesInFilterWithNull scalar tail from (*pos & ~*pos2) != 0 to (*pos != 0 && *pos2 == 0), which is this PR's correctness fix and is user-visible on x86 too, and its body says Closes: #116073. Its only file is src/Columns/ColumnsCommon.cpp, so that half would land with no regression test. I am keeping #116173 as it stands: the tail fix, the five rows this test was trimmed to, and the enable of the existing bytes64MaskToBits64Mask NEON tier that the arm_release job measured at 1.54x on rewrite_sumIf. Whichever of the two lands first, the other rebases onto it; if yours is the one that closes #116073, it should carry that regression test and a bug fix changelog entry next to the performance one.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #119555, which merged on 2026-09-13 (merge commit cf56cdec3bc13fb4978dd803f61c196993d8df2d); #116073 was closed with it.

Measured against master b884355cf7d5612a, nothing in this branch is left to merge:

  • The AArch64 wide path is on master, as a dedicated NEON kernel (vcgtq_u8/vsubq_u8 accumulator, vpadalq_u8, vaddlvq_u16) in both countBytesInFilter and countBytesInFilterWithNull. That is what the __SSE2__ gate change here was for, in a faster shape than the bytes64MaskToBits64Mask + std::popcount one I used.
  • The scalar tail fix is on master as the identical expression: count += (*pos != 0 && *pos2 == 0); there against count += (*pos != 0) && (*pos2 == 0); here.
  • The regression coverage is on master too, in 05189_count_bytes_in_filter_with_null. Running the 5 rows of this PR's test file against a master binary at 8ec7c5beabbf386a9a13d120a6b1573e4ab07ad4, which has that merge as an ancestor, gives 50 50 50 31 64 and so matches its own reference; those rows failed on master before the merge in both the amd64 and the aarch64 Bugfix validation runs (amd64 returned 100 68 68 63 65). Keeping the trimmed test would therefore duplicate a test that now exists, which answers the question I left open on 2026-08-25: it should not be kept.

The one line of substance left here is the correction of the stale comment above both loops, since master still says the condition > 0 on signed bytes is used while the vectorized path tests each byte for equality with zero. That correction, with the rest of the null-map-byte-as-a-predicate work, is in #119729, so nothing here needs a rebase.

This branch conflicts with master in src/Columns/ColumnsCommon.cpp only, and I am not resolving the conflict, because resolving it would mean putting the old dispatch back over the merged kernel. I have no objection to this PR being closed, and I am leaving that decision to a maintainer.

@JoshyDo

JoshyDo commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Thanks a lot for the thorough and constructive reviews, and especially for catching the subtle non-boolean null-map edge cases early on,! your feedback made the final patch significantly stronger! Really enjoyed collaborating with you on this.

@rschu1ze

Copy link
Copy Markdown
Member

Looks superseded by #119555

@rschu1ze rschu1ze closed this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, it is. I checked master before answering: both halves of this PR are on it now. The AArch64 wide path is #119555's NEON kernel, and the scalar tail uses the same predicate as the wide loop in both functions (*pos != 0 in countBytesInFilter, *pos != 0 && *pos2 == 0 in countBytesInFilterWithNull), so the block-size-dependent countIf count this PR fixed is gone on master as well. The five rows of my test pass unmodified against master 688ee332, and #119555 carries equivalent coverage in 05189_count_bytes_in_filter_with_null. Nothing is left here.

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. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-performance Pull request with some performance improvements

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__

3 participants