Skip to content

Enable -mbranch-protection=pac-ret on ARM - #119685

Merged
alexey-milovidov merged 45 commits into
masterfrom
enable-branch-protection-arm
Nov 15, 2026
Merged

alexey-milovidov merged 45 commits into
masterfrom
enable-branch-protection-arm

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

Nothing currently protects a saved return address. An overflow of a stack local that reaches far enough rewrites it and control transfers wherever the overflow data points - demonstrated in #119680, where a 2200-byte MySQL BIT value moved control to 0x4141414141414141.

With pac-ret the prologue signs the return address with paciasp and the epilogue authenticates it, so a return address rewritten through memory no longer validates. Both instructions sit in the NOP encoding space, so the same binary keeps running on cores without FEAT_PAuth - unprotected there, but not broken. Graviton3 and Graviton4 implement it (paca and pacg in /proc/cpuinfo).

Measured on Neoverse V2:

translation unit text size pac instructions
Parsers/ExpressionElementParsers +0.78% 408
Processors/Sources/MySQLSource +1.36% 415
shape baseline pac-ret delta
non-inlined call, four-instruction body 1.0908 ns/call 1.2936 ns/call +18.6%
same prologue, 65528 elements per call 0.17976 ns/elem 0.17964 ns/elem -0.07% (noise)

That is +0.20 ns per signed call. The microbenchmark signs leaf functions to measure them at all (pac-ret+leaf); the flag as proposed leaves leaves unsigned, which is the default and free, since they do not spill the return address - so the real blended cost is below what the table shows.

Three limits worth stating plainly:

  • This hardens only the ARM builds, and within them only the code the compiler generates from the C and C++ sources it is given, plus the assembly sources that opt in themselves through the feature macro it defines. Anything compiled with a flag set of its own, assembled without that opt-in, or built by another compiler keeps unsigned return addresses - see the three cases below. -mbranch-protection is aarch64-only; the x86-64 counterpart is -fcf-protection=return, which needs CET in both hardware and kernel, and is a separate question. The Rust objects the default aarch64 binary links - skim, delta-kernel, chdig, wasmtime - keep unsigned return addresses, because rustc treats -Zbranch-protection as ABI-affecting and refuses it outright while std comes precompiled without it:

    error: mixing `-Zbranch-protection` will cause an ABI mismatch in crate `lib`
      = note: `-Zbranch-protection=pac-ret` in this crate is incompatible with unset `-Zbranch-protection` in dependency `std`
    

    Signing them needs either std built from source with the same flag (non-sanitizer builds do not pass -Zbuild-std) or an explicit -Cunsafe-allow-abi-mismatch=branch-protection, so it wants its own change rather than riding along here.

    The raw .s inputs are not signed either, for a duller reason: -mbranch-protection is a code-generation option and says nothing about an input that is assembled rather than compiled. A .s file assembles to a byte-identical object with and without the flag (584 bytes either way, no paciasp in either), while a non-leaf C function in the same build gains paciasp/autiasp. So longjmp.s and syscall.s under base/glibc-compatibility/musl/aarch64 keep unsigned return addresses, as does every prebuilt library we link.

    Preprocessed .S sources are the one case that goes the other way, and they do it themselves rather than through code generation. COMPILER_FLAGS also feeds CMAKE_ASM_FLAGS, and the flag defines __ARM_FEATURE_PAC_DEFAULT, which is exactly what crypto/arm_arch.h keys AARCH64_SIGN_LINK_REGISTER and AARCH64_VALIDATE_LINK_REGISTER on. 13 of the 19 AArch64 OpenSSL sources this build assembles include that header, so they gain signed returns and the AArch64 PAC property note. clang -c on contrib/openssl-cmake/asm/crypto/chacha/chacha-armv8.S with the toolchain of this build:

    paciasp autiasp object size PAC property note
    without the flag 0 0 8616 absent
    with the flag 4 6 8752 present

    The boost::context switch trampolines (jump_arm64_aapcs_elf_gas.S, make_arm64_aapcs_elf_gas.S, ontop_arm64_aapcs_elf_gas.S) do not opt in: they key only BTI off the feature macros, save x30 into the suspended fiber's stack and resume through it with a plain ret, so stackful-coroutine continuations stay outside this protection. Signing them cannot reuse paciasp, because a continuation resumes on a different SP from the one it was saved on; that wants its own change.

    And the in-tree compiler-rt runtimes are not signed: contrib/compiler-rt-cmake filters the inherited flags down to an allowlist (_compiler_rt_keep_re) which drops the hardening ones. That filter is also why their unwinder does not strip the signature - sanitizer_ptrauth.h gates stripping on __ARM_FEATURE_PAC_DEFAULT, and clang -mbranch-protection=pac-ret -dM -E shows that is exactly the macro this flag defines. So adding -mbranch-protection to that allowlist would both sign those objects and make ASan and LSan reports readable under the flag, which is how the NOT SANITIZE exclusion above can be retired. Not done here: it rebuilds every ARM sanitizer runtime and wants its own round of validation.

  • bti is deliberately excluded. The linker keeps GNU_PROPERTY_AARCH64_FEATURE_1_BTI only when every input object carries it, including hand-written assembly and every contrib; otherwise it is dropped for the whole image and you pay the size for nothing. It measured a further 1.7 to 3.6 points of text, so it wants its own audit rather than riding along here.

  • Sanitizer builds are excluded (NOT SANITIZE), because a signed return address on the stack is only readable by an unwinder that strips the signature, and the sanitizer runtimes shipped with the toolchain do not. compiler-rt's frame-pointer unwinder BufferedStackTrace::UnwindFast collects the allocation and deallocation stacks behind every ASan and LSan report, and the STRIP_PAC_PC it applies to a saved return address expands to the identity unless compiler-rt itself was compiled with -mbranch-protection: sanitizer_ptrauth.h gates the xpaclri path on __ARM_FEATURE_PAC_DEFAULT. UnwindFast is byte-for-byte the same 87 instructions in the arm_asan_ubsan binaries of both this branch and master, and neither contains an xpaclri, so the signature travels into the report unchanged - it occupies the bits above the virtual address, and 17 of these 21 frames are gone:

    ==1423636==ERROR: AddressSanitizer: requested allocation size 0xde0b6b3a763ffff exceeds maximum supported size of 0x800000000 (thread T0)
        #0 0xb4c12b593bb8 in malloc
        #1 0xb4c14aec3ef0 in DB::SystemAllocatedMemoryHolder::Memory::Memory(unsigned long) src/Common/SystemAllocatedMemoryHolder.h:26:20
        #2 0xb4c14aec3ef0 in DB::SystemAllocatedMemoryHolder::alloc(unsigned long) src/Common/SystemAllocatedMemoryHolder.h:55:16
        #3 0x7bb4c14ae77dd4  (<unknown module>)
        #4 0x46b4c14ada1718  (<unknown module>)
        #5 0x19b4c14ad972bc  (<unknown module>)
        ... 12 more (<unknown module>)
        #16 0xb4c138b224f4 in mainEntryClickHouseLocal(int, char**) programs/local/LocalServer.cpp:2229:20
        #17 0x54b4c12b5d23b4  (<unknown module>)
    

    The same query against the arm_asan_ubsan binary of master d9049413 - same toolchain, same runtime, and UnwindFast disassembles to the same 87 instructions in both - prints the whole chain instead, all 26 frames from malloc through DB::InterpreterSystemQuery::execute down to main, with only the final frame-pointer-less libc frame missing.

    It is also a memory leak in disguise. paciasp mixes SP into the signature, so one call site yields a different value at every stack depth and each one takes a fresh entry in the stack depot, which is never freed. That is what killed Stateless tests (arm_asan_ubsan, azure, parallel) on db7f4493: both of its runs peaked at 80.8 and 81.9 GiB where 30 consecutive master runs of the same job peaked at 64 to 74 GiB, the server crossed the memory-pressure threshold of clickhouse-test 11 times, the worker pool drained from 12 workers to 1, and the job hit its 9000 s budget at 8955 of 13957 tests with every test OK and no FAIL line. The drain never reverses (issue clickhouse-test sheds parallel workers under memory pressure and never restores them, so a run that hovers at the threshold drains to one worker and is killed by the job timeout mid-suite #119791, fix Follow server memory in both directions when shedding test workers #119793), which is what turned the extra memory into a timeout rather than a slowdown.

    Our own unwinding is unaffected, which is why nothing else in CI noticed: StackTrace and jemalloc's profiler go through unw_backtrace, whose DWARF stepper follows DW_CFA_AARCH64_negate_ra_state, and the frame-pointer walk that StackTrace::tryCapture uses under TSan is abseil's, which strips the signature with xpaclri unconditionally.

Related: #119680
Related: #119684

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Build the C and C++ code of the ARM binaries with -mbranch-protection=pac-ret, which signs the return address so that overwriting it on the stack cannot redirect control flow; the AArch64 .S sources that key off __ARM_FEATURE_PAC_DEFAULT opt into the same signing. Sanitizer builds are excluded, because the sanitizer runtimes do not strip the signature when they unwind.


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

Version info

  • Merged into: 26.11.1.2333-master (included in 26.11 and later)

Nothing currently protects a saved return address. An overflow of a stack local
that reaches far enough rewrites it and control transfers wherever the overflow
data points - demonstrated in #119680, where a 2200-byte MySQL `BIT` value
moved control to `0x4141414141414141`.

With `pac-ret` the prologue signs the return address with `paciasp` and the
epilogue authenticates it, so a return address rewritten through memory no
longer validates. Both instructions are in the `NOP` encoding space, so the
same binary keeps running on cores without `FEAT_PAuth`, just unprotected
there; Graviton3 and Graviton4 implement it.

Measured on Neoverse V2: +0.78% and +1.36% of text on two translation units,
and +0.20 ns per signed call, which is +19% for a function whose body is four
instructions and unmeasurable (-0.07%) once a call processes a block of values.
Leaf functions stay unsigned by default, so the real fraction of instrumented
calls is lower than that microbenchmark suggests.

Note this hardens only the ARM builds. `-mbranch-protection` is aarch64-only;
the x86-64 counterpart is `-fcf-protection=return`, which needs CET support in
both the hardware and the kernel and is a separate question.

`bti` is deliberately not included here. The linker keeps the BTI property only
when every input object carries it, including hand-written assembly and every
contrib, and in my measurements it costs a further 1.7 to 3.6 points of text -
so it wants its own audit rather than riding along.

Draft: opened to get a performance comparison and a full CI run.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3c1fe49]

Summary: ✅


AI Review

Summary

Enables -mbranch-protection=pac-ret for Linux AArch64 builds without sanitizers, signing compiler-generated saved return addresses and activating assembly that explicitly opts in. Reviewed head 3c1fe4969eb20ff7f4a7591f59a03d0b402a8f98 and all prior discussion. No new actionable code defect was identified. Earlier coverage findings are addressed, but the latest ARM performance results are still needed before accepting the rollout.

Signed-frame consumers checked: C++ exception unwinding, StackTrace and query profiling authenticate through libunwind, including its cached-rule path; jemalloc uses unw_backtrace. Sanitizer builds remain excluded. OpenSSL assembly opts in through __ARM_FEATURE_PAC_DEFAULT; unsigned boost::context and compatibility assembly retain their existing calling conventions. The musl setjmp/longjmp implementation signs and authenticates using the restored stack pointer.

Missing context / blind spots
  • ⚠️ All eight ARM performance shards at the reviewed head are PENDING. The current CI report therefore cannot establish the residual overhead after the merged fixes. No local build or runtime tests were run; compiler tools and initialized dependency sources are absent from this checkout, so relevant dependency code was inspected at its pinned revision remotely.
Tests
Final Verdict

⚠️ Request changes — validation remains incomplete. Obtain the current ARM performance results; if significant regressions remain, reduce them or obtain explicit maintainer acceptance of those measured results. No new inline findings or thread replies were warranted, and existing resolved threads were left unchanged.

@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement comp-build-system Build system (CMake, compilation, platform builds). labels Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3c1fe4969 with master 5157e6d4e (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 828.85 MiB 828.92 MiB +69.67 KiB (+0.01%)

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.

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.86, programs/clickhouse-keeper ×0.66 (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.6 s 13.4 s +8.6 s (+181%)
Compile time of recompiled translation units

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

Job report

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review September 13, 2026 12:56

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

No real degradations.

alexey-milovidov and others added 3 commits September 14, 2026 18:16
A signed return address on the stack is only readable by an unwinder that strips the signature,
and the sanitizer runtimes shipped with the toolchain do not. `compiler-rt`'s frame-pointer
unwinder (`BufferedStackTrace::UnwindFast`) collects the allocation and deallocation stacks
behind every ASan and LSan report, and the `STRIP_PAC_PC` it applies to a saved return address
expands to the identity unless `compiler-rt` itself was compiled with `-mbranch-protection`
(`sanitizer_ptrauth.h` gates the `xpaclri` path on `__ARM_FEATURE_PAC_DEFAULT`). The runtime
linked into this pull request's own `arm_asan_ubsan` build has no `xpaclri` in `UnwindFast`, so
signed frames reach the reports verbatim: the signature sits in the bits above the virtual
address, and every frame past the innermost one symbolizes to `<unknown module>`.

It is also a memory leak in disguise. `paciasp` mixes `SP` into the signature, so one call site
yields a different value at every stack depth, and each one takes a fresh entry in the stack
depot, which is never freed. That is visible in CI: `Stateless tests (arm_asan_ubsan, azure,
parallel)` hit the 9000 s budget at 8955/13957 on both runs of `db7f4493` with every test `OK`,
having peaked at 80.8 and 81.9 GiB where 30 consecutive master runs of the same job peaked at
64 to 74 GiB and finished in ~4500 s. The server crossed the memory-pressure threshold of
`clickhouse-test` 11 times and the worker pool drained from 12 to 1 (that regulator only sheds
and never restores - issue #119791, fix #119793 - which turned the extra memory into a timeout
instead of a slowdown).

Our own unwinding is unaffected, which is why nothing else in CI noticed: `StackTrace` and
jemalloc's profiler go through `unw_backtrace`, whose DWARF stepper follows
`DW_CFA_AARCH64_negate_ra_state`, and the frame-pointer walk that `StackTrace::tryCapture` uses
under TSan is abseil's, which strips the signature with `xpaclri` unconditionally.

Related: #119791
Related: #119793

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Not every frame of the measured report lost its name: the saved return address in a frame is
signed only if the function that spilled it was compiled to sign, and the compiler leaves some
functions unsigned. 17 of 21 frames were lost, against 1 of 26 - the frame-pointer-less libc
entry - for the same report on master.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The one red job - Stateless tests (arm_asan_ubsan, azure, parallel), which hit its 9000 s budget at 8955 of 13957 tests with every test OK and no FAIL line - was caused by this change after all, not by the worker-shed ratchet alone, so the flag is now off for sanitizer builds (NOT SANITIZE).

compiler-rt's frame-pointer unwinder BufferedStackTrace::UnwindFast collects the allocation and deallocation stacks behind every ASan and LSan report, and the STRIP_PAC_PC it applies to a saved return address expands to the identity unless compiler-rt itself was compiled with -mbranch-protection (sanitizer_ptrauth.h gates the xpaclri path on __ARM_FEATURE_PAC_DEFAULT). The runtime in the toolchain was not: UnwindFast disassembles to the same 87 instructions in the arm_asan_ubsan binaries of this branch and of master, and neither contains an xpaclri. So the signature - which sits in the bits above the virtual address - travels into the report unchanged. The same SYSTEM ALLOCATE MEMORY 999999999999999999 report, produced by both CI binaries on a Graviton host:

arm_asan_ubsan binary frames lost to <unknown module>
this branch, db7f4493 17 of 21
master, d9049413 1 of 26 (the frame-pointer-less libc entry)

It is also a memory leak in disguise. paciasp mixes SP into the signature, so one call site produces a different value at every stack depth and each one takes a fresh entry in the stack depot, which is never freed. Both runs of db7f4493 peaked at 80.8 and 81.9 GiB where 30 consecutive master runs of the same job peaked at 64 to 74 GiB and finished in about 4500 s; the server crossed the memory-pressure threshold of clickhouse-test 11 times and the worker pool drained from 12 workers to 1. That drain never reverses, which is what turned the extra memory into a timeout rather than a slowdown:

Related: #119791
Related: #119793

Our own unwinding was never at risk, which is why nothing else in CI noticed: StackTrace and jemalloc's profiler go through unw_backtrace, whose DWARF stepper follows DW_CFA_AARCH64_negate_ra_state, and the frame-pointer walk that StackTrace::tryCapture uses under TSan is abseil's, which strips the signature with xpaclri unconditionally.

Comment thread CMakeLists.txt Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stateless tests (amd_debug, parallel) failure on this head is unrelated to this pull request: 05182_join_order_conflict_detector_cast_null_propagation reddens whenever clickhouse-test randomizes auto_statistics_types to a subset that leaves basic out, fleet-wide since master a88f878d7. Fix, with the measurements: #120084

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The sanitizer exclusion is confirmed by the job that caught the problem. Stateless tests (arm_asan_ubsan, azure, parallel) on 14dab327:

db7f4493 (signed) 14dab327 (excluded) master band
outcome killed at the 9000 s budget, 8955 of 13957 tests success, 13742 passed, 0 failed success
duration 9046 s and 9061 s 4375 s ~4400 to 5000 s
host memory peak 80.8 and 81.9 GiB 71.53 GiB 64 to 74 GiB
Server memory at shed events 11, pool drained 12 workers to 1 0, pool stayed at 12 0

Both remaining reds on this head are unrelated and accounted for: Stateless tests (amd_debug, parallel) is the auto_statistics_types randomization flake in 05182_join_order_conflict_detector_cast_null_propagation (fix: #120084), and Build profile diff is the CI logs cluster answering Code: 241 ... memory limit exceeded ... maximum: 212.40 GiB for 8.5 minutes, which exhausts the job's 8 retries and which ends that job in error on 3 to 6% of all runs fleet-wide. I will re-run both once the workflow finishes.

The default `aarch64` binary links `skim`, `delta-kernel`, `chdig` and `wasmtime`, and none of that
code is signed: `rustc` treats `-Zbranch-protection` as ABI-affecting and refuses it outright while
`std` comes precompiled without it - `error: mixing -Zbranch-protection will cause an ABI mismatch in
crate lib ... incompatible with unset -Zbranch-protection in dependency std` on the nightly this
build uses (1.96.0-nightly). Extending the mitigation there needs either `std` built from source with
the same flag - non-sanitizer builds do not pass `-Zbuild-std` - or an explicit
`-Cunsafe-allow-abi-mismatch=branch-protection`, which is a decision of its own and not something to
smuggle in here.

So the flag's promise is the C, C++ and assembly objects, and the comment, the pull request body and
the changelog entry now say that instead of "ARM binaries".

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread CMakeLists.txt Resolved
`-mbranch-protection` is a code-generation option, so it says nothing about an input that is
assembled rather than compiled: a `.s` file assembles to a byte-identical object with and without the
flag (`cmp` on the two, 584 bytes each, no `paciasp` in either), while a non-leaf C function in the
same build gains `paciasp` and `autiasp`. `longjmp.s` and `syscall.s` under
`base/glibc-compatibility/musl/aarch64` therefore keep unsigned return addresses, as does every
prebuilt library we link.

What the flag covers is what the compiler generates from the C and C++ sources, and the comment, the
pull request body and the changelog entry now say exactly that.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread CMakeLists.txt Resolved
Enumerating the carve-outs one at a time keeps missing one - this time the in-tree `compiler-rt`
runtimes, which `contrib/compiler-rt-cmake` builds after filtering the inherited flags down to an
allowlist (`_compiler_rt_keep_re`) that drops the hardening ones. So the comment now states the rule
instead: the flag covers the code the compiler generates from the sources it is given, and anything
compiled with a flag set of its own, assembled rather than compiled, or built by another compiler
keeps unsigned return addresses.

That filter is also the reason the sanitizer runtimes do not strip the signature when they unwind:
`sanitizer_ptrauth.h` gates stripping on `__ARM_FEATURE_PAC_DEFAULT`, and
`clang -mbranch-protection=pac-ret -dM -E` shows that is exactly the macro this flag defines. Adding
`-mbranch-protection` to that allowlist would therefore both sign those objects and make ASan and
LSan reports readable under the flag, which is the way to retire the `NOT SANITIZE` exclusion - noted
in the comment, not done here, because it rebuilds every ARM sanitizer runtime and wants its own
round of validation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread CMakeLists.txt Resolved
alexey-milovidov and others added 2 commits September 19, 2026 14:56
The coverage list said hand-written assembly stays unsigned, which is
only true of the raw `.s` inputs. `COMPILER_FLAGS` also feeds
`CMAKE_ASM_FLAGS`, and `-mbranch-protection=pac-ret` defines
`__ARM_FEATURE_PAC_DEFAULT`, which is what `crypto/arm_arch.h` keys
`AARCH64_SIGN_LINK_REGISTER` and `AARCH64_VALIDATE_LINK_REGISTER` on.
So the preprocessed OpenSSL `.S` sources that include it do get signed
returns. Measured with the toolchain of this build, `clang -c` on
`contrib/openssl-cmake/asm/crypto/chacha/chacha-armv8.S`:

| | `paciasp` | `autiasp` | object size | PAC property note |
| --- | --- | --- | --- | --- |
| without the flag | 0 | 0 | 8616 | absent |
| with the flag | 4 | 6 | 8752 | present |

13 of the 19 AArch64 OpenSSL sources the build assembles carry those
macros. The comment now says that, and separates it from the `.s`
inputs and the prebuilt libraries, which do stay unsigned.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The one red job, Build profile diff, is unrelated to this pull request and is not about the build: the job's own comparison query to the CI logs cluster failed - RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') ... - after exhausting its retries. The flag change cannot reach that query. It is tracked fleet-wide as #120462, and the fix that makes the job skip instead of erroring when the cluster read fails is open as #118708.

Master is merged in (clean, the branch was 2444 commits behind) and the remaining review thread is addressed in 3b31577, with the measurement in the thread: 13 of the 19 AArch64 OpenSSL .S sources the build assembles include crypto/arm_arch.h and therefore opt into paciasp/autiasp through __ARM_FEATURE_PAC_DEFAULT, which this flag defines. The CMake comment, the pull request body and the changelog entry now scope the unsigned set to the raw .s inputs and the prebuilt libraries and name that opt-in explicitly.

Comment thread CMakeLists.txt Resolved
Address review: the AArch64 `jump`/`make`/`ontop` trampolines of `boost::context`
are BTI-aware only, so the saved continuation of a stackful coroutine is not
signed by this change. Name them in the coverage list.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Sep 27, 2026
`clickhouse-test` shed one parallel worker every 30 s while the server's
RSS stayed above 80% of `max_server_memory_usage`, and nothing ever
started one again. The trigger is a level crossing, so a run whose memory
*hovers* at the threshold - not one that runs away - loses its whole pool
one worker at a time. On `Stateless tests (arm_asan_ubsan, azure,
parallel)` for ClickHouse#119685,
eleven sheds in 8 min 47 s took 12 workers down to 1, throughput fell
from 144.8 to 11.6 tests/min - 12.5x, exactly the pool ratio - and the
9000 s job timeout killed the run at 8970 of 13957 tests with every test
that ran reporting `OK` and no failing test anywhere. The fraction
printed 80% or 81% at every one of the eleven sheds and spent 3 min 36 s
below the threshold in between; and taking the pool from 12 workers to 4
did not move it by a printed point, because under ASan the server's RSS
is allocator state and caches that do not shrink when queries stop. The
mechanism was paying throughput for relief it was not getting.

Add the missing direction: at or below `MEMORY_RECOVERY_THRESHOLD` a
request no worker has claimed yet is withdrawn, or else one shed worker
is started again against the same shared queue. The gap to the shed
threshold is the hysteresis band that keeps a fraction sitting on the
threshold from draining the pool.

Give the pool a floor of `jobs // 2` where workers share a queue.
Halving concurrency is the largest cut whose worst case, paid from the
very first test, still fits a budget sized at about twice the median run;
dropping to one worker fits it from no point in the run, so it trades a
server that survived for a job killed mid-suite. Where each worker owns
its queue (`--no-self-parallel`, used only with `--flaky-check`) a shed
worker cannot be started again without re-running its own tests, and
those runs are bounded by a time limit rather than a test count, so the
pool may still drain to a single worker there, as before.

Compute the shed cap from `jobs + workers_restored - shed_requests`
instead of `len(processes) - workers_to_shed.value`. A worker claims a
request, and commits to stopping, by decrementing `workers_to_shed`, but
it stays in `processes` until it has actually exited, so the old cap lags
by that window and lets one extra request through - enough, in a streak,
to reach zero workers, which ends the parent loop and prints `All tests
have finished` with part of the suite never run.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119685&sha=db7f44938b24dba4e56b3ebf049784c7a65532d1&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29
Pull request: ClickHouse#119685

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master at f9e6c60e784 (now 63b6e09e227). The only conflict GitHub reported was the contrib/musl pointer. master already points at 64c3896e (ClickHouse/musl#8), which contains the merged ClickHouse/musl#7 commit 388a78b8 that this PR used. So the merge takes the master pointer, and the PR diff is now only CMakeLists.txt.

At 4019a836 the only red check was Performance Comparison (arm_release, master_head, 2/6). count_from_formats #6 (CustomSeparated) was +24.3%, and +22.1% again after a restart. That is the same per-call cost of pac-ret on call-heavy format-reading paths that was accepted in the 2026-10-29 review. All review threads are resolved. The remaining step is a maintainer's merge decision.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

But now there are more degradations. Let's investigate.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 I checked the ARM perf report at 63b6e09e2276 (9 slower queries in fetch_perf_report, 32 in the "Changes in Performance" tables). I reran all 32 locally on a Neoverse V2 host with PAuth, using the CI binaries (PR 63b6e09e vs. master f9e6c60e) and the perf.py from this commit:

  • Reproduced (2): hashed_dictionary_sharded #3 +17.4% (CI +20.6%) and hashed_dictionary_load_factor #3 +15.2% (CI +14.2%). Both are SYSTEM RELOAD DICTIONARY of a SPARSE_HASHED dictionary with 3M keys. Alternating clickhouse local runs give the same: median reload 0.38-0.42 s on master vs. 0.44-0.50 s with this PR.
  • Not reproduced (26), including the queries new on this head. numbers_with_step #0/#2 were +7.1%/+9.3% locally against thresholds of 20%/21% (CI +26%). hash_join_probe_continuation #0-#3 were +3.8% to +10.3% against 15-16% (CI +17% to +21%). numbers_with_step was also flagged at 887303aa and nowhere else on this PR. hash_join_probe_continuation and the dictionary queries were flagged for the first time on this head.
  • Not measured (3): count_from_formats #66, formats_columns_sampling #1 and countIf #2 need the hits datasets, which I did not download. The first two are the known CustomSeparated per-field call cost. formats_columns_sampling #1 has been slower on every one of the 17 heads of this PR.

Many of the not-reproduced queries are still a few percent slower locally, which fits the general per-call cost. Only the dictionary reload clears its threshold.

Why the dictionary reload is slower. This is a different mechanism from the one in the description:

  • perf stat on 15 reloads: user instructions +2.7% (16.08G -> 16.52G), but user cycles +20% (14.7G -> 17.8G). dTLB load misses (54.2M vs. 54.2M) and L2 refills (78.0M vs. 78.3M) are the same on both binaries.
  • 77-80% of user cycles are in the HashedDictionary::blockToAttributes row loop. Inside it, 86% of the samples are on the cset right after the cell load of the linear-probe loop (ldr x14, [x12, x9]; cmp x14, #0). That probe loop disassembles to the same instructions in both binaries. The only change in the whole function is the one paciasp in its prologue.
  • So the cache misses are the same, but each one costs more. The row loop also makes small non-inlined calls on every row: the virtual IColumn::get into a Field, Field::assign, Field::safeGet, and the PackedHashMapCell insert. With paciasp/autiasp on those calls, the core overlaps fewer of the outstanding probe misses.

A standalone microbenchmark shows the same effect (clang 21, -O2 vs. -O2 -mbranch-protection=pac-ret). It does random intHash64 probes into a 256 MiB table, with one non-inlined non-leaf call per row:

probe only probe + 1 call
baseline 10.0 ns/row 18.6 ns/row
pac-ret 9.9 ns/row 20.3 ns/row

That is about +1.8 ns per signed call when the call shares the loop with a cache-missing load. The description measured +0.20 ns for a cache-resident loop, so the cost is about 9 times higher here. The table in the description understates the cost for loops that are memory-latency-bound and call small non-inlined functions, such as hash-table builds, dictionary loads and probably joins. hash_join_probe_continuation (+4% to +10% locally) fits this pattern, but it stayed below its threshold.

Ways to reduce the dictionary case without dropping the flag: in HashedDictionary::blockToAttributes, read the attribute through the typed column instead of a per-row virtual IColumn::get into a Field, or exempt that hot path with __attribute__((target("branch-protection=none"))). Whether to accept the cost as it is remains a maintainer decision.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master at 485f00de566 (now f0318667382). The merge was clean and the diff is still only CMakeLists.txt. The only red checks at 63b6e09e were the three ARM Performance Comparison shards analysed in the previous comment. Of those slowdowns, only the SPARSE_HASHED dictionary reload reproduced locally. numbers_with_step #0/#2 was flagged in about 30 other PRs over the last 30 days, and hash_join_probe_continuation in 3 others. Whether to accept the per-signed-call cost on memory-bound loops, or to exempt HashedDictionary::blockToAttributes from branch protection, is still a maintainer decision.

groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
`HashedDictionary::blockToAttributes` read every attribute value through a
virtual `IColumn::get` into a `Field`, followed by `Field::safeGet`. When the
column has the attribute type, read the value directly from `ColumnVector`,
`ColumnDecimal` or `ColumnString` (with the null map of `ColumnNullable`).
Other columns (`Array`, `Map`, `Object`, or a source returning a different
type than the attribute) still go through `Field`.

Reloading a 3M-key simple-key dictionary takes 0.20 s instead of 0.34 s on
Neoverse V2, for both `HASHED` and `SPARSE_HASHED`. This also recovers the
`hashed_dictionary_sharded` and `hashed_dictionary_load_factor` regressions
of `-mbranch-protection=pac-ret` on ARM, which come from signing these
per-row calls in a loop bound by cache misses.

Related: ClickHouse#119685
Related: ClickHouse#119685 (comment)

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

Copy link
Copy Markdown
Member Author

🕵 CI at f0318667: the only red checks are Performance Comparison (arm_release, master_head, 3/8) and 4/8, with formats_columns_sampling #1 (CustomSeparatedWithNames, +23.8%, +24.6% after restart) and count_from_formats #37 (+25.2%, +26.7% after restart). The SPARSE_HASHED dictionary reloads were not flagged on this head. Their fix, #130965, was merged on 2026-11-12, after this head's master base.

I reproduced the CustomSeparated slowdown locally with the CI binaries (this PR vs. master 485f00de), single-threaded, on 100k rows of hits. SELECT WatchID from CustomSeparatedWithNames takes 25% more user cycles (2.96G -> 3.74G) for 4.5% more instructions. TabSeparatedWithNames on the same data changes by only 1%.

The cause is the skip path. Every skipped field goes through skipFieldByEscapingRule, a small out-of-line switch that reloads x30 and runs autiasp right before tail-calling readEscapedStringIntoImpl, which signs x30 again with paciasp. In this PR's binary, autiasp and the branch after it take 65% of that function's samples. The delimiter check assertString -> checkString adds more signed frames per field. TabSeparatedFormatReader::skipField calls the reader directly, so it avoids both.

Fix: #131462. It skips Escaped/Raw fields directly and checks one-character delimiters inline, the same way TabSeparated does. Behaviour is unchanged, and a new test covers skipping for all escaping rules. After it is merged, I will merge master here so the ARM perf shards run with both fixes.

harikrishnan94 pushed a commit to harikrishnan94/ClickHouse that referenced this pull request Nov 14, 2026
…tcher

Reading a few columns from a wide `CustomSeparatedWithNames` file spends
most of its time skipping fields. Each skipped field went through
`skipFieldDelimiter` -> `assertString` -> `checkString` and
`skipField` -> `skipFieldByEscapingRule` -> `readEscapedStringIntoImpl`.
`skipFieldByEscapingRule` is a small out-of-line switch that tail-calls the
reader, so with `-mbranch-protection=pac-ret` every field adds a serial
`autiasp` -> `paciasp` dependency on `x30`. On Neoverse V2 this made
`formats_columns_sampling` and `count_from_formats` on `CustomSeparated`
20-25% slower in ClickHouse#119685,
while `TabSeparatedWithNames`, whose `skipField` calls the reader directly,
changed by 1%.

Read `Escaped` and `Raw` fields directly, as `TabSeparatedFormatReader::skipField`
does, and check a one-character field delimiter with the inline `assertChar`.
Other escaping rules and multi-character delimiters keep the previous path.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master at 5157e6d4e02 (now 3c1fe4969eb). The merge was clean and the diff is still only CMakeLists.txt. This brings in both fixes for the ARM perf slowdowns this PR was blocked on:

The ARM Performance Comparison shards will now run with both fixes. All review threads are resolved. Whether to accept any per-call cost of pac-ret that remains is still a maintainer decision.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 ARM perf at 3c1fe4969eb2, which includes #131462 and #130965: the CustomSeparated and SPARSE_HASHED slowdowns are gone. By the compare.sh thresholds (fetch_perf_report.py), all 4558 ARM queries show no slower queries and one unstable one, min_max_index_with_cast #0. Two shards are still red because the dashboard check confirmed two regressions after a restart: logical_functions_medium #3 (or(x1,x2,x3), +19%) and logical_functions_small #9 (xor of two Nullable columns, +16%).

I don't think these come from pac-ret:

Each process stays in a fast or slow mode for all of its queries, and master does this too. So a server that lands in the slow mode gives a +15-20% that survives repeated runs, and a restart can land in it again. This PR adds no measurable cost to these queries. Merging is a maintainer decision.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 15, 2026
Merged via the queue into master with commit 46106b1 Nov 15, 2026
403 of 405 checks passed
@alexey-milovidov
alexey-milovidov deleted the enable-branch-protection-arm branch November 15, 2026 02:13
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 15, 2026
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 15, 2026
…ranch-protection-arm"

This reverts commit 46106b1, reversing
changes made to d88a8f1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 15, 2026
#119685 was reverted in #131765 because the `arm_release` binary died with
SIGILL on cores without `FEAT_PAuth` (Graviton2, Ampere Altra) on the first
SimSIMD call: SimSIMD compiles its CPU probe `_simsimd_capabilities_arm` and
five bf16 NEON kernels for ARMv8.3+, where clang folds `autiasp; ret` into
`retaa`, which is not in the `NOP` space.

Build `_simsimd` with `-mbranch-protection=none` (the same fix as #131762).
Compiled with the `arm_release` flags, `c/lib.c` goes from 7 `retaa` to 0.

Add a check to the `arm_release` compatibility check that scans the code
sections of the packaged binary for `retaa` and `retab` and names the
functions through `system.symbols`. A test run on Graviton3 would never notice
the next such case. On the `arm_release` package of #131745 (pac-ret on) it
reports exactly the 6 SimSIMD functions; on that of d88a8f1 (the master
commit before #119685) it passes.

Closes: #131748
Related: #131762
Related: #131765

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh Bot pushed a commit that referenced this pull request Nov 20, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 127836 124816 Revert "Avoid building stream names and substreams cache keys for every block in MergeTreeReaderWide"
Changelog-revert: 128706 116083 Revert "Fit the insert pipeline and merges into a small server's memory"
Changelog-revert: 128760 128658 Revert "Prewarm macOS code signature verification of the clickhouse binary after linking"
Changelog-revert: 128947 127422 Revert "[GPU] `GDeflate` compression codec on the CPU"
Changelog-revert: 129099 128947 Revert "Revert "[GPU] `GDeflate` compression codec on the CPU""
Changelog-revert: 129310 127149 Revert "Mark a query as cancelled in the process list when its TCP client cancels it"
Changelog-revert: 129311 129310 Revert "Revert "Mark a query as cancelled in the process list when its TCP client cancels it""
Changelog-revert: 129862 129425 Revert "Add 7 tests for coverage gaps in 5 components"
Changelog-revert: 129863 129862 Fix `GLOBAL IN` in projection `WHERE` with parallel replicas; restore coverage tests
Changelog-revert: 129986 122871 Revert "Search long integer slices in 512-byte chunks on AArch64 in `hasAll` and `hasAny`"
Changelog-revert: 130046 129986 Revert "Revert "Search long integer slices in 512-byte chunks on AArch64 in `hasAll` and `hasAny`""
Changelog-revert: 130368 114729 Revert "CI: run the full test suite only when review threads are resolved"
Changelog-revert: 130509 130368 Revert "Revert "CI: run the full test suite only when review threads are resolved""
Changelog-revert: 130531 114923 Revert "Make a table read by a scalar subquery in a CONSTRAINT a loading dependency"
Changelog-revert: 131043 129464 Revert "Sync shared files changed by the private `AmberMap` PR"
Changelog-revert: 131045 130793 Revert "Fix wrong ORDER BY ... LIMIT results on Delta Lake tables with column mapping"
Changelog-revert: 131270 128764 Re-enable the adaptive aggregator for queries generated from PromQL
Changelog-revert: 131424 122826 Revert "Forbid renaming the source of incremental refreshable views"
Changelog-revert: 131562 131454 Revert "Build the symbol index in the background at server startup"
Changelog-revert: 131638 131562 Revert "Revert "Build the symbol index in the background at server startup""
Changelog-revert: 131691 130864 Revert "Use one source instead of N for parallel_inserts of AzureQueue/S3Queue"
Changelog-revert: 131765 119685 Revert "Enable `-mbranch-protection=pac-ret` on ARM"
Changelog-deleted-entry: 116083 [Performance Improvement] [section] * Reduce memory use for `INSERT` and background merges on servers with a few GiB of RAM. Write buffers, insert squashing, the `Parquet` reader and merge selection now scale with `max_server_memory_usage`, avoiding `MEMORY_LIMIT_EXCEEDED` during wide-table inserts and merges that repeatedly fail without reducing the part count. New `MergeTree` settings `max_memory_ratio_to_activate_adaptive_write_buffer` and `merge_memory_estimate_per_source_part_column` control adaptive write buffers and merge selection, respectively; set either to `0` to disable that adjustment. [#116083](#116083) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 119685 [Build/Testing/Packaging Improvement] [raw] * Build the `C` and `C++` code of the ARM binaries with `-mbranch-protection=pac-ret`, which signs the return address so that overwriting it on the stack cannot redirect control flow; the AArch64 `.S` sources that key off `__ARM_FEATURE_PAC_DEFAULT` opt into the same signing. Sanitizer builds are excluded, because the sanitizer runtimes do not strip the signature when they unwind. [#119685](#119685) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 122826 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Forbid renaming the source of incremental refreshable views closes #[#120082](#120082). [#122826](#122826) ([Smita Kulkarni](https://github.com/SmitaRKulkarni)).
Changelog-deleted-entry: 128658 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Prewarm macOS code signature verification of the clickhouse binary after linking. [#128658](#128658) ([Azat Khuzhin](https://github.com/azat)).
Changelog-deleted-entry: 128764 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Disable the adaptive aggregator for queries generated from PromQL. [#128764](#128764) ([Vitaly Baranov](https://github.com/vitlibar)).
Changelog-deleted-entry: 129464 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Sync shared files changed by the private `AmberMap` PR. [#129464](#129464) ([Miсhael Stetsyuk](https://github.com/mstetsyuk)).
Changelog-deleted-entry: 130793 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed wrong results of `ORDER BY ... LIMIT` on a Delta Lake table with column mapping when a renamed column has the name that another column is stored under: the top-K dynamic filter (`use_top_k_dynamic_filtering`) compared the other column against the threshold and dropped rows of the true result. [#130793](#130793) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 130864 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Use one source instead of N for parallel_inserts of AzureQueue/S3Queue. [#130864](#130864) ([Azat Khuzhin](https://github.com/azat)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-build-system Build system (CMake, compilation, platform builds). pr-build Pull request with build/testing/packaging improvement pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants