Skip to content

Optimize zero-padded byte equality on x86 - #130445

Closed
qoega wants to merge 14 commits into
ClickHouse:masterfrom
qoega:codex/padded-memory-arm-x86-2026-11-10
Closed

qoega wants to merge 14 commits into
ClickHouse:masterfrom
qoega:codex/padded-memory-arm-x86-2026-11-10

Conversation

@qoega

@qoega qoega commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

🫧 Add an equality-only UInt8 specialization on x86-64 using compiler vectors and a byte mismatch mask. It avoids reloading and ordering mismatched bytes, and avoids the scalar 128-bit tail shifts from the previous revision. No new SIMD intrinsics or AVX-512 dispatch is added.

ARM and other targets retain their existing implementations. The experimental ARM copy loop and ARM equality specialization were withdrawn because no application gain was established and the earlier ARM comparison had a confirmed window-query slowdown. The next ARM comparison is a control with no ARM runtime optimization enabled by this patch.

The seven direct equality tests at f5439ede34c observed x86 medians from 7.3% less time to 1.3% more. For example, unequal FixedString(12)/FixedString(13) took 42.7 → 39.6 ms, while String/FixedString(32) took 46.8 → 47.5 ms. All seven were classified unchanged by the raw CI gate; these observations do not establish a statistically significant application-level gain. The x86 standalone wrapper remains byte-identical after narrowing the target guard. Current full-build CI is pending.

Release and ASan/UBSan checks on x86-64 via Rosetta pass 112,056,399 assertions each, plus 69,120 long-input assertions through 1 MiB. The focused retained test checks exact padding, guard pages at both edges, runtime zero length and live-byte mismatches. POWER8/POWER9 cross-compiles pass; ARM/PPC wrapper objects match master byte-for-byte. No native x86 timing or full-program proof is inferred from these correctness checks.

A separate client session_timezone race is being investigated independently; see the PR discussion. It is outside the changed equality helper.

Changelog category (leave one):

  • Performance Improvement

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

Optimize zero-padded String/FixedString equality comparisons on x86-64.


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

Use direct SIMD mismatch masks for zero-padded `UInt8` equality and peel
the first 16 bytes before the paired NEON copy loop. Preserve the existing
padding, zero-length and signed comparison contracts.

Port the measured two-file change to current master without unrelated
SQuaLity commits. Prior measurements show about 1.1-1.4% lower aggregate
real x86 method time and 8.7-9.4% lower Apple ARM copy entry time.
Validation includes release, ASan/UBSan, x86 MSan, guard-page and alignment
checks, long equality inputs and scoped actual-object proof checks.
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [72848b6]

Summary: ✅


AI Review

Summary

Adds an x86-64 UInt8 specialization for zero-padded equality using compiler vectors, a focused guard-page test, and seven direct SQL performance benchmarks. No actionable findings remain. The earlier boundary-coverage concern has retained coverage; the performance-evidence concern now has measurements for the current x86 logic; the ARM runtime changes behind the earlier regression finding have been withdrawn. The measured x86 differences are modest and all remain below CI's change threshold.

Missing context / blind spots
  • ⚠️ Full-build, sanitizer, and performance results for head 72848b6eb6d are still pending in Praktika. The completed comparison at f5439ede34c covers the same x86 logic and passed debug, ASan/UBSan, TSan, and MSan unit jobs. Completed head CI will close the remaining validation gap. No local C++ tests were run: this checkout has neither a compiler nor a ClickHouse binary.
Final Verdict

✅ Approve. No new inline findings; existing threads require no replies or resolution changes.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 10, 2026
Comment thread base/base/memcmpSmall.h Resolved
@Algunenano Algunenano self-assigned this Nov 10, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Nov 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 72848b6eb with master 816b8458e (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

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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.62, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 12.8 s +9.2 s (+256%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 8.2 s +6.1 s (+284%)
Compile time of recompiled translation units

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

Job report

Comment thread src/Common/memcpySmall.h Resolved
Replace the added `UInt8` equality intrinsics and explicit AVX-512 branch
with unsigned 128-bit loads, XOR and a byte-order-aware partial-word mask.
Use fixed-size `__builtin_memcpy` operations for the peeled ARM copy loop.
The compiler selects instructions for the configured target.

Preserve the common-prefix/zero-suffix semantics and strict 15-byte padding
bounds. Release and ASan/UBSan guard/property checks pass, along with long
inputs through 1 MiB and a two-byte-order mask equivalence check. The new
standalone ARM copy object passes induction; equality object validation is
limited by the proof decoder's unsupported `ccmp` instruction.

ClickHouse#130445 (comment)
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130445&sha=4f92b4ce648af4a87e03f9f5f7bb6e84bc2e9fd5&name_0=PR
ClickHouse#130445
@qoega qoega changed the title Optimize zero-padded string equality and short ARM copies Use portable operations for padded string equality and ARM copies Nov 10, 2026
Cover zero length, independent alignments and lengths around 16/32/48
with allocations containing exactly 15 trailing bytes. Exercise `UInt8`
zero-padded equality with differing padding and zero/nonzero longer tails.
Add guard pages at both edges, including unreadable zero-length pointers,
and poison source padding in MSan builds.

The existing `unit_tests_dbms` recursive gtest discovery includes these
cases. Local release and ASan/UBSan runs pass. Throwaway wrong-bound and
wrong-mask variants demonstrate that the tests detect an overread and a
padding-dependent result.

ClickHouse#130445 (comment)
ClickHouse#130445
Comment thread base/base/memcmpSmall.h Resolved
@clickhouse-gh clickhouse-gh Bot added comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 10, 2026
`poisonPadding` does not modify the pointed-to bytes. The MSan API also
accepts a const pointer, so use `const UInt8 *` and satisfy the
`readability-non-const-parameter` check that blocked the public and sync
`arm_tidy` builds.

The focused tidy check reproduces the old diagnostic and passes after the
repair. The MSan API syntax check and release/ASan/UBSan boundary tests pass.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130445&sha=f53c2251840f8d66151cc0c9cb1f334707abbb5a&name_0=PR&name_1=Build%20%28arm_tidy%2C%204%2F4%29
ClickHouse#130445

@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 tested the PR On x86 (Intel Xeon Platinum 8488C from AWS) I found no perf improvements. In fact, some microbenchmarks show it being slower. I'll share an agent analysis in a comment.

@Algunenano

Copy link
Copy Markdown
Member

🕵 I measured this PR on x86 (Intel Xeon Platinum 8488C, -march=x86-64-v3, the CI default). The portable rewrite is slower than master for most String/FixedString zero-padded equality cases. I could not measure the ARM memcpySmall change.

End-to-end (CI amd_release binaries, PR build vs master merge base da9125b5eb3d, 20M rows, Memory table, max_threads = 1, median of 21 runs):

Query master ms PR ms Change
FixedString(12) = FixedString(13) 62 63 +1.6%
FixedString(31) = FixedString(32) 128 130 +1.6%
String = FixedString(32) 113 116 +2.7%
FixedString(8) = 'abcdefg' 35 39 +11.4%
String = toFixedString(..., 12) 58 62 +6.9%

Why it is slower. On any nonzero XOR, the new code reloads both words as four 64-bit loads and clips them with a 128-bit shift in general-purpose registers (shld, shlx, test cl, 0x40, two cmov). For widths below 16 this path runs on almost every row. The bytes after the row end (the next row or padding) differ between a and b, so the XOR is nonzero even when the values are equal. The hot loop also keeps an extra counter for the shift amount.

Variants. I compiled each one with the equals.cpp flags and ran it in the same loops as the StringEqualsImpl callers. Every variant returns the same results as master on all inputs. Each value is the change vs master, from three pinned runs; results agree within about 1 to 3 points.

Variant FixedString N ≤ 16 N 17 to 48 N ≥ 64 String vs FixedString
This PR +9% to +15% up to +19% ±3% +8% to +33%
32-byte AVX2 loads, then a clipped tail (several shapes) mixed, up to +44% up to +30% on equal values ±3% +4% to +27%
Branchless clip of every 16-byte chunk (bzhi) 0% to −27% up to +9% up to +7% up to +15%
XOR, index-vector clip, vptest +9% to +29% up to +47% up to +27% up to +8%
G: master's movemask loop, equality only −20% to −27% −2% to −18% −6% to +1% +0.2% to +3%

32-byte loads do not pay off. With 15 bytes of overread allowed, a 32-byte load is legal only when at least 17 bytes remain, so the code always needs a clipped 16-byte tail too. That adds branches. Widths of 64 and up gain only 0% to 3%.

Recommendation. Use G for the UInt8 overload. It keeps master's compare, bitmask and tzcnt loop. It only drops the byte reload and ordering in detail::cmp, which equality does not need. One function covers x86 and NEON with clang vector extensions. Only the two lines that build the mismatch bitmask differ per architecture:

using u8x16 = UInt8 __attribute__((ext_vector_type(16)));
using u8x8 = UInt8 __attribute__((ext_vector_type(8)));
using u16x8 = UInt16 __attribute__((ext_vector_type(8)));
using b16 = bool __attribute__((ext_vector_type(16)));

for (size_t offset = 0; offset < min_size; offset += 16)
{
    u8x16 x;
    u8x16 y;
    __builtin_memcpy(&x, a + offset, 16);
    __builtin_memcpy(&y, b + offset, 16);
    auto ne = x != y;
#if defined(__aarch64__)
    /// NEON has no movemask: narrow to 4 bits per byte (`shrn`).
    const UInt64 mask = std::bit_cast<UInt64>(__builtin_convertvector(std::bit_cast<u16x8>(ne) >> 4, u8x8));
    constexpr size_t bits_per_byte = 4;
#else
    const UInt32 mask = std::bit_cast<UInt16>(__builtin_convertvector(ne, b16));
    constexpr size_t bits_per_byte = 1;
#endif
    if (mask)
    {
        if (offset + std::countr_zero(mask) / bits_per_byte < min_size)
            return false;
        break;
    }
}
/// Then the existing zero-suffix check of the longer side.

The loop compiles to exactly the expected instructions:

  • x86 (x86-64-v3): vpcmpeqb, vpmovmskb, xor 0xFFFF, tzcnt. This is the same as master's loop.
  • aarch64 (armv8.2-a): cmeq, mvn, shrn #4, fmov, rbit/clz, lsr #2.

Do not use the generic bool-vector bitmask on NEON. On aarch64 it lowers to cmeq, bic with a weight table, ext, zip1 and addv. The same function passes a brute-force check against a scalar reference on both architectures (516,000 random cases, sizes 0 to 128, differences also placed in the padding; aarch64 run under qemu). I did not time anything on ARM.

Bigger win in the caller. For FixedString vs FixedString (fixed_string_vector_fixed_string_vector, fixed_string_vector_constant), both widths are the same for every row. When both are ≤ 16, the clip masks can be computed once, and each row then needs no branches:

c[i] = !((neq16(a + i * a_n, b + i * b_n) & min_mask) | (nonzero16(longest + i * long_n + min_n) & tail_mask));

This gives −40% to −53% on equal values and mismatches, and −86% on a random 50/50 mix, because it removes branch mispredictions. The String paths cannot do this, because their lengths change per row.

These rows cost only 1.5 to 2 ns (5 to 7 cycles), so small differences depend on how clang unswitches the outer row loop. The 2% to 5% numbers for G should be confirmed with a full build. I have not built ClickHouse with G or the caller change.

@qoega

qoega commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Let's figure out why window functions are faster? maybe we can fix it in the window function code instead.
It was optimized for arm only so expected no improvement for amd for now

Replace the 128-bit tail shift in `memequalSmallLikeZeroPaddedAllowOverflow15`
with a byte mismatch mask, so x86 can use its normal compare/movemask loop
without scalar word reloads or ordering mismatches. Express both x86 and
NEON paths with compiler vector operations; add no AVX-512 intrinsics.
Keep the exact padding and zero-length contracts and brace nested test loops.

Release and ASan/UBSan gates pass on Apple ARM and x86-64 via Rosetta.
The exact standalone ARM equality object passes bounded proofs through
64 bytes and rejects six deliberate object mutations. Native x86 timing
is not part of these local correctness checks.

Related: ClickHouse#130445
Review measurements: ClickHouse#130445 (comment)
Keep the critical boundary test for the 15-byte padding and zero-length
contracts. Remove the large alignment grids from the permanent gtests;
those remain covered by the standalone validation and bounded proofs.
The remaining multi-line nested loop uses explicit braces.

Related: ClickHouse#130445 (comment)
@qoega qoega changed the title Use portable operations for padded string equality and ARM copies Optimize padded equality on x86 and ARM using compiler vectors Nov 11, 2026
@Algunenano

Copy link
Copy Markdown
Member

Let's figure out why window functions are faster? maybe we can fix it in the window function code instead.
It was optimized for arm only so expected no improvement for amd for now

Please go ahead and "figure out why window functions are faster" and please optimize for arm and amd both

Add stored-data cases for unequal `FixedString` widths and `String` versus
`FixedString`, including vector and constant inputs. Independent hash bits
produce mixed matches and mismatches without timing data generation.
Run with one thread to expose changes in the short comparison loops.

The existing ordering and equal-width 16-byte cases do not exercise the
changed zero-padded helper. The seven queries are parsed by the current
`perf.py`; execution and final full-build timings remain pending CI.

Related: ClickHouse#130445
PowerPC builds define `__SSE2__` for the intrinsic emulation layer. Do not
select the x86 boolean-vector mask implementation solely from that macro;
its vector comparison triggers `-Wdeprecated-altivec-src-compat` on PPC.
Retain the existing comparison template on PowerPC.

Both POWER8 and POWER9 reproduce the original diagnostic and compile with
the fixed guard. ARM, SSE2 and AVX2 wrapper objects are byte-identical to
the validated previous versions. No warning is suppressed.

Related: ClickHouse#130445
CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130445&sha=f5439ede34c44107959c68017dfe1f3caedafbf0&name_0=PR&name_1=Build%20%28ppc64le%29

qoega commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

🫧 The PowerPC build failure is fixed by 14f9f60e993, now on head f89428c5d69. PowerPC deliberately defines __SSE2__ for emulation; the new mask specialization now also requires actual x86-64. Original POWER8/POWER9 failures reproduce, both fixed builds pass, and ARM/SSE2/AVX2 objects are byte-identical to the previous validated objects.

@groeneai, please investigate and fix the separate client timezone race from the exact TSan report in a separate PR. Offline symbolization matched build ID 2e22b346c33c44f30ab9e7650236bc97c6e80678: the async INSERT reader calls DateLUT::instance at DateLUT.cpp:209, reading the query context's session_timezone; the main thread writes it through ClientBase::onTimezoneUpdate while sendDataFromPipe is active. This is the query-context branch, not the global-context fallback. The relevant source is identical in this PR and its master base. Historical reports #58315 and #67109 were closed as duplicates of #49156; the old fix #82444 is already present, but does not prevent this overlap.

The ARM window_transform query 8 slowdown remains unresolved: +23.4% initially and +17.5% after restart. It is not dismissed as noise. Existing profiles put most additional samples in result delivery/waits, with no reported changed-file coverage overlap. The refreshed-base CI run is pending.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the client session_timezone data race (DateLUT::instance on the async INSERT reader thread vs ClientBase::onTimezoneUpdate on the main thread during sendDataFromPipe); I'll follow up here with a separate PR (or my findings) shortly.

Comment thread src/Common/memcpySmall.h Resolved
@clickhouse-gh clickhouse-gh Bot added comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... and removed comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... labels Nov 12, 2026
Withdraw the experimental ARM copy loop and retain the existing ARM
equality implementation. The ARM copy change lacks final timing evidence,
and the completed comparison has an unresolved window-query slowdown.
Keep these runtime changes out of the patch rather than claiming a gain.

The x86 byte-mask implementation is unchanged. Its SSE2/AVX2 wrapper
objects match the previously validated objects exactly. ARM and PowerPC
wrappers now match master exactly. Release/ASan/UBSan and long-input
x86 checks pass, and the retained guard-page test focuses on equality.

Related: ClickHouse#130445
CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130445&sha=f5439ede34c44107959c68017dfe1f3caedafbf0&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F8%29
@qoega qoega changed the title Optimize padded equality on x86 and ARM using compiler vectors Optimize zero-padded byte equality on x86 Nov 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The separate fix for the client session_timezone data race is #131177.

The server sends TimezoneUpdate right after the input-schema Data for input() and RETURNING, but receiveSampleBlock returned at the schema, so onTimezoneUpdate ran while the parsing pipeline thread was already reading the setting. The client now reads on to that packet before it starts sending data. The same ordering also parsed part or all of the rows in the client's time zone instead of the session one; the PR covers both.

@qoega qoega closed this Nov 13, 2026
shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Nov 13, 2026
…data

The server sends `TimezoneUpdate` right after the input-schema `Data` of the
`input` initializer (also used by `INSERT ... RETURNING` with client data), and
the protocol defines it as applying to the rows the client is about to send.
`receiveSampleBlock` returned at the schema, so the update was read by
`receiveLogsAndProfileEvents` only after `sendDataFromPipe` had started the
parsing pipeline, and `onTimezoneUpdate` wrote `session_timezone` of
`client_context` while the pipeline thread read it in `DateLUT::instance`:
a data race, and, when the server's `session_timezone` differs from the
client's (a profile `session_timezone` with `apply_settings_from_server = 0`),
the first rows of the INSERT parsed in the client's time zone.

For an INSERT whose data the server reads through `input` (an `input` SELECT
or `RETURNING`), over a remote connection to a server new enough to send the
update, `receiveSampleBlock` now reads on to the `TimezoneUpdate`, so it is
applied on the main thread before any parsing thread exists. A server that
sends it before the schema is handled by the existing case; `LocalConnection`
sends no update and is excluded.

Reported by La Casa Del Dolor (amd_tsan):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130445&sha=f5439ede34c44107959c68017dfe1f3caedafbf0&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29
ClickHouse#130445
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=4951f241cfaff37833813a18a5544f0ab312ca64&name_0=MasterCI&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29

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

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants