Skip to content

Use LLVM-libc memory functions instead of glibc ones - #107566

Merged
thevar1able merged 11 commits into
masterfrom
llvmlibc-mem-functions
Jul 2, 2026
Merged

thevar1able merged 11 commits into
masterfrom
llvmlibc-mem-functions

Conversation

@thevar1able

@thevar1able thevar1able commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

Builds memcmp, memcpy, memmove, memset, bcmp and memmem from LLVM-libc into the existing libllvmlibc target (which already supplies the math functions), replacing the slow libc byte-loop versions with SIMD ones competitive with glibc's IFUNC-dispatched implementations. Relevant for musl; overrides glibc's via weak symbols.

The exported symbols are marked weak (via the LLVM_LIBC_FUNCTION_ATTR_<name> hook) so the existing strong memcpy keeps precedence and sanitizer interceptors can still override them. memmem is strong, so it is not linked under sanitizers to keep the interceptor in place. On x86_64, memcpy/memmove/memset/memmem use runtime AVX-512/AVX2 dispatch (a lazily-resolved pointer, glibc-IFUNC shape); on aarch64, a NEON memmove and memmem (memcpy/memset come from musl's Arm Optimized Routines). SIMD tiers are picked from X86_ARCH_LEVEL.

Split out of #97452 (Build musl from sources), where these functions live; this PR ports them to master independently.

Related: #97452

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Use SIMD memcmp/memcpy/memmove/memset/bcmp/memmem implementations from LLVM-libc.

Build `memcmp`, `memcpy`, `memmove`, `memset`, `bcmp` and `memmem` from
LLVM-libc into the existing `libllvmlibc` target (which already supplies the
math functions), replacing the previous hand-rolled `memcmp`.

The wrapper TU `contrib/libllvmlibc-cmake/string/mem_functions.cpp` includes
the LLVM-libc implementation files and marks each exported C symbol `weak`
via the `LLVM_LIBC_FUNCTION_ATTR_<name>` hook, so sanitizer interceptors can
override them and so the existing strong `memcpy` from
`base/glibc-compatibility/memcpy` keeps precedence. `memmem` is a strong
symbol.

On x86_64, `x86_64_mem_functions.cpp` provides `memcpy`/`memmove`/`memset`
with runtime AVX-512 dispatch (a lazily-resolved function pointer, the same
shape as a glibc IFUNC) plus an AVX-512/AVX2/scalar `memmem`. On aarch64,
`aarch64_mem_functions.cpp` adds a NEON `memmove` and `memmem`.

The library is built with `-ffreestanding -fno-builtin` so clang's loop-idiom
recognition does not rewrite the inner loops into calls to the very functions
being defined. SIMD tiers are selected from `X86_ARCH_LEVEL` (SSE2 / v3 /
v4 with `-mprefer-vector-width=512`).

Ported from the `use-musl` branch (PR #97452).

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

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [210594c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, parallel, 2/2) FAIL
02441_alter_delete_and_drop_column FAIL cidb, issue ISSUE CREATED
Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) FAIL
test_replicated_table_attach/test.py::test_startup_with_small_bg_pool_partitioned FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR removes the old amd64 memcpy compatibility archive, builds replacement mem* routines into libllvmlibc, and wires those symbols into non-sanitized Linux executables. The review is still at request changes: one new issue broadens the change surface into the existing libm codegen, the PR still lacks focused symbol-level correctness coverage, the performance evidence is not yet reconciled with the negative Cloud report, and the previously raised GLIBC_COMPATIBILITY=ON + ENABLE_LLVM_LIBC_MATH=OFF compatibility regression still exists.

Findings
  • ⚠️ Majors
  • [contrib/libllvmlibc-cmake/CMakeLists.txt:81] The new target-wide compile options are not scoped to the added memory sources. libllvmlibc still builds all of the existing math objects listed in SRCS (acos, exp, log, pow, ...), so -ffreestanding -fno-builtin here and -mprefer-vector-width=512 in the x86-64-v4 branch also retune libm codegen. That expands the PR from “swap in mem* implementations” to “change the whole math-library codegen” without focused validation. Split the memory sources into a separate target or apply the flags per source file.
  • [base/glibc-compatibility/CMakeLists.txt:44] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/107566#discussion_r3505830916] The amd64 GLIBC_COMPATIBILITY=ON + ENABLE_LLVM_LIBC_MATH=OFF configuration is still treated as supported (CMakeLists.txt:371-374 explicitly preserves the old-glibc math path), but after deleting MEMCPY_LIBRARY it has no non-versioned memcpy left. That means the build silently falls back to glibc's memcpy@GLIBC_2.14, breaking the portability contract for anyone disabling LLVM-libc math. Either keep the compatibility memcpy for that option combination or reject it at configure time.
Tests
  • ⚠️ Add a small unit or fuzz-style harness that calls the linked memcmp/memcpy/memmove/memset/memmem symbols directly across sizes, alignments, overlap directions, zero-length cases, and adversarial needles. The current diff still has no focused regression coverage for the interposed symbols.
  • ⚠️ Reconcile the negative Cloud Performance Report with a rerun or a focused benchmark/profile on the default wiring. The local microbench/flamegraph argument is useful, but it does not yet close the gap against the reported regressions on clickbench and tpch_adapted_1_official.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: scope the new compile options to the memory-function objects (or prove the broader libm codegen change is intentional and safe), add focused correctness coverage for the interposed mem* symbols, restore or reject the GLIBC_COMPATIBILITY=ON + ENABLE_LLVM_LIBC_MATH=OFF amd64 configuration, and reconcile the negative Cloud performance signal with updated evidence.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Jun 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 5 regressed, 1 improved out of 38 analysed

This PR replaces the custom memcpy with llvm-libc SIMD memory functions (memcpy/memmove/memset/memcmp/memmem) behind a runtime AVX-512 dispatch, so it touches a hot path every query runs. Five queries regress consistently (ClickBench Q30 +17%, Q31 +14%; TPC-H Q4 +206%, Q7 71->711ms, Q8 +33%) and one improves (TPC-H Q16 -49%, likely faster SIMD search/compare) — all confirmed by both tests and all on the rewritten copy path, so these are real, not noise. The large TPC-H regressions (Q4/Q7/Q8) are the priority: the new large-copy dispatch appears materially slower than the old inline path on data-movement-heavy joins. Worth checking whether the benchmark hardware exposes AVX-512, since without it the new baseline path, not the tuned ZMM path, is what ran.

clickbench

🔴 2 regressed

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 30 regression 240 280 +16.7% <0.0001 memory: PR swaps custom memcpy for llvm-libc SIMD mem* with runtime dispatch; universal copy path, regression is on-path
🔴 31 regression 308 352 +13.9% <0.0001 memory: Same mem* rewrite; indirect resolver call + new size-tier thresholds on hot copy path plausibly cost ~14%

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🔴 3 regressed · 🟢 1 improved

Flagged queries (4 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 4 regression 326 998 +206.0% <0.0001 memory: Large delta held by trust override; join/agg data movement hits the rewritten mem* path directly
🔴 7 regression 71 711 +901.4% <0.0001 memory: Base was very noisy but source is tight; 71->711ms is a clear real shift from the mem* rewrite
🔴 8 regression 168 224 +33.3% <0.0001 memory: Consistent +33% on a data-movement-heavy query, on the rewritten copy path; verdict stands
🟢 16 improvement 100 51 -49.0% <0.0001 memory: Faster SIMD memmem/memcmp/memcpy from the rewrite plausibly halves this; improvement is on-path

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: a054d1c0-4feb-4396-b2d8-c1dd66634012
  • MIRAI run: c88b0019-8ec8-4f3a-9418-ce01b1627c2d
  • PR check IDs:
    • clickbench_626869_1782916872
    • clickbench_626875_1782916872
    • clickbench_626885_1782916872
    • tpch_adapted_1_official_626893_1782916872
    • tpch_adapted_1_official_626905_1782916872
    • tpch_adapted_1_official_626915_1782916872

@thevar1able
thevar1able marked this pull request as ready for review June 18, 2026 15:45
Two follow-up fixes to the LLVM-libc memory functions port, plus comment
pruning and simplification.

memcpy precedence: marking `memcpy` `weak` does not by itself guarantee that
the strong `base/glibc-compatibility/memcpy` keeps precedence. lld resolves a
`memcpy` reference from whichever static archive it reaches first, weak or
strong, and CMake places `libllvmlibc` ahead of `libmemcpy` on the link line,
so the weak `memcpy` was winning. Splitting `memmem` out is not sufficient on
its own because `memcpy` is referenced directly. The strong `memcpy` is now
forced into every executable with `--whole-archive` (in `CMAKE_EXE_LINKER_FLAGS`,
the same mechanism as `compiler_rt_link.cmake`), so it is unconditionally
present and wins regardless of archive order. `memmem` is also moved to its own
translation unit so that a reference to the strong, always-pulled `memmem` no
longer drags the weak `memcpy` into the link.

memmem worst case: the SIMD two-byte filter verifies each candidate with
`memcmp`, which is O(needle) per candidate and degenerates to O(haystack*needle)
on low-selectivity needles such as "aa..aba" over an all-`a` haystack. Needles
of `TWO_WAY_THRESHOLD` (32) bytes or longer are now routed to a Two-Way
(Crochemore-Perrin) matcher ported from musl, which is linear with no
degenerate case. Below the threshold the per-candidate verification is bounded
by a small constant, so the filter stays linear in the haystack.

Verified by a controlled lld link experiment (strong `memcpy` wins in the
exact real-world archive order with `--whole-archive`, no duplicate symbols)
and by fuzzing `memmem` against a brute-force reference over 289k cases,
including the degenerate low-selectivity needles and all size edge cases.

The shared x86_64 runtime CPU detection now lives in `x86_cpu_dispatch.h`,
included by both `x86_64_mem_functions.cpp` and `memmem.cpp`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous commit started forcing the strong glibc-compatibility `memcpy`
into every executable with `-Wl,--whole-archive` so it wins over libllvmlibc's
weak `memcpy`. Under sanitizers this collides with `compiler_rt_link.cmake`,
which already force-links the sanitizer runtime's own `memcpy` interceptor with
`--whole-archive`. With two `--whole-archive` definitions the custom `memcpy`
defeats the interceptor, so the sanitizer's shadow-memory handling is bypassed
and writes land in the shadow-gap region — a `Segmentation fault` at server
start and in unit tests across all MSan jobs (the previous commit, which did not
force-link `memcpy`, let the interceptor win and had no such failures).

Gate the force-link on `NOT SANITIZE`. The binary's performance does not matter
under sanitizers, where the interceptor must take precedence; release builds are
unaffected and keep the custom `memcpy`.

CI: #107566

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thevar1able thevar1able changed the title Port LLVM-libc memory functions into libllvmlibc Use LLVM-libc memory functions instead of glibc ones Jun 29, 2026
# Memory functions: mem_functions.cpp provides the weak memcmp/memcpy/memmove/
# memset/bcmp; the strong memmem lives in memmem.cpp (added below).
set(SRCS
"${CMAKE_CURRENT_SOURCE_DIR}/string/mem_functions.cpp"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This target now globally interposes memcmp/memcpy/memmove/memset/bcmp and, outside sanitizers, memmem, but the PR does not add focused correctness coverage for the linked replacement symbols. Broad query tests can miss exactly the edge cases that are risky here: overlap direction and alignment around the 64/128/512-byte cutoffs, zero-length handling, and memmem short-needle SIMD vs. long-needle Two-Way paths on low-selectivity data.

Please add a small unit or fuzz-style test that calls the linked symbols and compares them with simple reference implementations across sizes, alignments, overlaps, and adversarial needles, so future changes cannot silently corrupt memory or string-search results.

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

A couple of questions:

  • I don't see any perf changes, which is both positive (we are comparing ourselves to the runtime glibc available in the machines) and negative (don't see any improvements either). I guess that it matters most in the musl builds. Not sure if you have metrics somewhere (not critical).
  • Should we consider dropping the memcpy glibc compat library in favor of this? And if not (because it's faster) then shouldn't we just discard this memcpy and use that one instead (always, move the code here)

Comment thread cmake/linux/default_libs.cmake Resolved
@thevar1able

Copy link
Copy Markdown
Member Author

Thanks for review, @Algunenano!

I guess that it matters most in the musl builds

Correct. Changes in this branch were split from #97452, here is a relevant CI run.

Should we consider dropping the memcpy glibc compat library in favor of this

That'd be nice, let me look into it.

@thevar1able thevar1able added the pr-build Pull request with build/testing/packaging improvement label Jul 1, 2026
@thevar1able
thevar1able added this pull request to the merge queue Jul 1, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@thevar1able, there are many regressions on TPC-H. Worth checking.

@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Jul 1, 2026
@thevar1able

thevar1able commented Jul 1, 2026 •

Copy link
Copy Markdown
Member Author

@alexey-milovidov please check edit history of this Cloud Performance Report.
@yurifedoseev FYI

@thevar1able
thevar1able added this pull request to the merge queue Jul 1, 2026
@thevar1able
thevar1able removed this pull request from the merge queue due to a manual request Jul 1, 2026
@@ -15,6 +19,10 @@ if (ENABLE_LLVM_LIBC_MATH)
link_directories("${CMAKE_BINARY_DIR}/contrib/libllvmlibc-cmake")
target_link_libraries(global-libs INTERFACE libllvmlibc)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Because target_link_libraries(global-libs INTERFACE libllvmlibc) here, together with the forced -u symbols below, makes these replacements active in every non-sanitized Linux executable, this is no longer just a musl-only optimization path. The PR's own Cloud Performance Report on that default wiring is currently negative (clickbench Q30/Q31 +17%/+14%, TPC-H Q4 +206%, Q7 71->711 ms, Q8 +33%), so we would be replacing a universal hot path with a measured regression. Please either scope the interposition to the configurations where it is actually faster, or rerun with threshold/implementation changes that remove those regressions before wiring libllvmlibc into global-libs.

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.

Benchmark complete. Here's the picture across all four arch levels, and it fully vindicates your disbelief.

View A — CPU-bound (L2-resident): where memcpy differences are real

Single thread (GB/s):

┌───────────┬────────────┬─────────┬──────┬──────┬──────┬────────────────┬───────┐
│ chunk avg │ sse2 (old) │ llvm v1 │  v2  │  v3  │  v4  │ llvm no-AVX512 │ glibc │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~8 B      │ 1.2        │ 1.2     │ 1.2  │ 1.2  │ 1.2  │ 1.2            │ 1.1   │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~32 B     │ 3.6        │ 4.8     │ 4.8  │ 4.8  │ 4.9  │ 4.9            │ 3.8   │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~128 B    │ 9.9        │ 16.3    │ 16.3 │ 16.3 │ 16.7 │ 16.7           │ 17.2  │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~2 KB     │ 85.8       │ 95      │ 97   │ 105  │ 102  │ 98             │ 86.5  │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~32 KB    │ 137        │ 135     │ 136  │ 141  │ 139  │ 137            │ 134   │
└───────────┴────────────┴─────────┴──────┴──────┴──────┴────────────────┴───────┘

At 32 threads (still cache-resident) the mid-size wins widen: <=256 → llvm ~350 vs sse2 232 (+50%).

LLVM-libc is faster than the old SSE2 at every level — up to +65% in the 32 B–2 KB range, tied elsewhere, never slower. v1/v2/v3/v4 are near-identical (large copies always dispatch to the AVX-512 clone; only the small tiers vary), and the no-AVX-512 baseline path tracks the AVX2 build — so even on cloud hardware without AVX-512, no regression. This directly refutes the report's hint.

View B — DRAM-resident: the bandwidth regime (production)

┌─────────────────────────┬──────┬─────────────┬───────────┬───────┐
│                         │ sse2 │ llvm v1..v4 │ no-AVX512 │ glibc │
├─────────────────────────┼──────┼─────────────┼───────────┼───────┤
│ 8 threads (256 MB > L3) │ ~20  │ ~20–23      │ ~20       │ ~21   │
├─────────────────────────┼──────┼─────────────┼───────────┼───────┤
│ 32 threads (1 GB)       │ 17.7 │ 17.7        │ 17.7      │ 17.7  │
└─────────────────────────┴──────┴─────────────┴───────────┴───────┘

At all-cores, every implementation, every size, every arch level pins to 17.7 GB/s — the DRAM ceiling. This is exactly Milovidov's thesis: once you saturate memory bandwidth, the memcpy implementation is irrelevant.

Verdict: the cloud regression is a false positive

TPC-H Q4/Q7/Q8 are multi-threaded, data-movement-heavy joins/aggregations — i.e. bandwidth-bound, the exact regime where the table above shows sse2, llvm-libc, and glibc are byte-for-byte identical (17.7 GB/s). A memcpy swap physically cannot change a bandwidth-bound query's runtime, let alone make Q7 go 71→711 ms (10×). Three independent lines of evidence now agree:

1. This bench: at production thread counts, all variants converge; where they diverge (CPU-bound small/mid copies) llvm-libc wins.
2. Flamegraphs (earlier): memcpy/memset were <1% of CPU in the flagged queries.
3. The presentation's own lesson: microbench/benchmark deltas don't transfer to production precisely because of this saturation — and the report is a benchmark harness, not a profile.

Honest caveats: the single-thread DRAM cells (View B1) are noisy — llvm_v3 read 25 GB/s there while v1/v2/v4 read 47–65 with the identical AVX-512 path, so that low value is measurement noise (few passes, best-of-2), not a real effect. It doesn't touch the conclusion. And this is Zen 5; on Graviton (where ClickHouse Cloud actually runs) the x86 paths don't even apply — aarch64 uses musl's memcpy, untouched by the dropped-glibc-memcpy commit.


# Without -fno-builtin, clang's loop-idiom pass rewrites the mem* inner loops
# into calls to the very functions being defined (infinite recursion).
target_compile_options(libllvmlibc PRIVATE -ffreestanding -fno-builtin)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

libllvmlibc is still the existing math library here, not a memory-only target: the SRCS list above still compiles acos, exp, log, pow, and the rest of the preexisting libm objects. Making the whole target -ffreestanding -fno-builtin here (and -mprefer-vector-width=512 in the x86-64-v4 branch below) therefore changes codegen for all of those math routines too, even though the PR contract is only "swap in mem* implementations".

That broadens the performance surface to every libllvmlibc math call without any focused evidence that those paths stayed neutral. Please either split the new mem* files into a separate target or scope these options to the memory-function sources only.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.70% +0.10%

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

Full report · Diff report

@thevar1able
thevar1able added this pull request to the merge queue Jul 2, 2026
Merged via the queue into master with commit 2c05673 Jul 2, 2026
173 of 176 checks passed
@thevar1able
thevar1able deleted the llvmlibc-mem-functions branch July 2, 2026 20:28
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
thevar1able added a commit that referenced this pull request Jul 2, 2026
- Revert CI job changes that switched release/fast-test builds to musl and
  rewrote the compatibility check: that is later "musl as main build" work.
- Revert LLVM-libc mem functions (split to PR #107566); keep musl's own
  mem*/bcmp, restoring the x86_64 asm memcpy/memmove/memset.
- Remove the llvm-tblgen -march pin and protoc DEPENDS additions that are
  not needed for this change.
- Restyle contrib/musl-cmake and cmake/musl.cmake closer to the usual
  contrib cmake style: drop the unused musl-Scrt1 target, banner comments
  and redundant arch detection; MUSL_ARCH now comes from the toolchain files.

Co-Authored-By: Claude Fable 5 <[email protected]>
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Jul 20, 2026
The x86_64 mem* dispatchers in contrib/libllvmlibc-cmake rely on `flatten`
to inline the whole LLVM-libc helper tree into the `target("arch=x86-64-v4")`
clones. At -O0 (Debug build with -DDEBUG_O_LEVEL=0) clang lowers `flatten`
as a single level of inlining, so the v4-attributed `memmove_overlap_avx512`
calls out-of-line baseline-target (x86-64-v3) helpers that pass 64-byte
vectors by value. That is an ABI mismatch - the v4 caller reads the return
value from zmm0 while the v3 callee returns it in ymm0:ymm1 - which silently
corrupts every overlapping `memmove` of more than 128 bytes on AVX-512
machines. Clang rejects this pattern with a hard error when the mismatched
call is visible in the source, but the inliner recreates it silently.

The corruption made llvm-tblgen crash (SIGSEGV in -gen-x86-fold-tables,
SmallVector `idx < size()` assertion in -gen-asm-matcher) during -O0 builds
on AVX-512 hardware. CI debug builds did not catch it: they run with the
default -Og, and CI machines have no AVX-512.

Fix it in the source so the code is correct at any optimization level:
upgrade LIBC_INLINE to `always_inline` for this TU (honored even at -O0),
and redeclare the generic `load`/`store`/`splat` - which lack LIBC_INLINE
upstream yet are exactly the functions passing vectors by value - with
`always_inline` as well. The helper tree then always collapses into the
exported functions and no cross-target call boundary survives.

Caused by: ClickHouse#107566

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`test_implicit_index_upgrade_alter_replay` creates a second replica `node2`
and asserts `SELECT count() FROM test_alter_replay` equals `10001` immediately
after `wait_for_active_replica`. But `wait_for_active_replica` only waits for
`is_readonly = 0`, not for the freshly-joined replica to finish fetching parts.

So `node2` can observe only the small `VALUES` part (1 row, `key = 99999`)
before the 10000-row part is fetched, and the assertion fails with
`assert '1' == '10001'`. This raced once each on several unrelated PRs over
the last 30 days (e.g. ClickHouse#108084, ClickHouse#99280, ClickHouse#107566, ClickHouse#107442).

Add `SYSTEM SYNC REPLICA test_alter_replay` after the replica becomes active,
which blocks until all parts are fetched, before checking the row count.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108770&sha=bb760616d54e3d8e5d20968022085506c31b5f37&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%201%2F4%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The previous commit started forcing the strong glibc-compatibility `memcpy`
into every executable with `-Wl,--whole-archive` so it wins over libllvmlibc's
weak `memcpy`. Under sanitizers this collides with `compiler_rt_link.cmake`,
which already force-links the sanitizer runtime's own `memcpy` interceptor with
`--whole-archive`. With two `--whole-archive` definitions the custom `memcpy`
defeats the interceptor, so the sanitizer's shadow-memory handling is bypassed
and writes land in the shadow-gap region — a `Segmentation fault` at server
start and in unit tests across all MSan jobs (the previous commit, which did not
force-link `memcpy`, let the interceptor win and had no such failures).

Gate the force-link on `NOT SANITIZE`. The binary's performance does not matter
under sanitizers, where the interceptor must take precedence; release builds are
unaffected and keep the custom `memcpy`.

CI: ClickHouse#107566

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ctions

Use LLVM-libc memory functions instead of glibc ones
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
- Revert CI job changes that switched release/fast-test builds to musl and
  rewrote the compatibility check: that is later "musl as main build" work.
- Revert LLVM-libc mem functions (split to PR ClickHouse#107566); keep musl's own
  mem*/bcmp, restoring the x86_64 asm memcpy/memmove/memset.
- Remove the llvm-tblgen -march pin and protoc DEPENDS additions that are
  not needed for this change.
- Restyle contrib/musl-cmake and cmake/musl.cmake closer to the usual
  contrib cmake style: drop the unused musl-Scrt1 target, banner comments
  and redundant arch detection; MUSL_ARCH now comes from the toolchain files.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The x86_64 mem* dispatchers in contrib/libllvmlibc-cmake rely on `flatten`
to inline the whole LLVM-libc helper tree into the `target("arch=x86-64-v4")`
clones. At -O0 (Debug build with -DDEBUG_O_LEVEL=0) clang lowers `flatten`
as a single level of inlining, so the v4-attributed `memmove_overlap_avx512`
calls out-of-line baseline-target (x86-64-v3) helpers that pass 64-byte
vectors by value. That is an ABI mismatch - the v4 caller reads the return
value from zmm0 while the v3 callee returns it in ymm0:ymm1 - which silently
corrupts every overlapping `memmove` of more than 128 bytes on AVX-512
machines. Clang rejects this pattern with a hard error when the mismatched
call is visible in the source, but the inliner recreates it silently.

The corruption made llvm-tblgen crash (SIGSEGV in -gen-x86-fold-tables,
SmallVector `idx < size()` assertion in -gen-asm-matcher) during -O0 builds
on AVX-512 hardware. CI debug builds did not catch it: they run with the
default -Og, and CI machines have no AVX-512.

Fix it in the source so the code is correct at any optimization level:
upgrade LIBC_INLINE to `always_inline` for this TU (honored even at -O0),
and redeclare the generic `load`/`store`/`splat` - which lack LIBC_INLINE
upstream yet are exactly the functions passing vectors by value - with
`always_inline` as well. The helper tree then always collapses into the
exported functions and no cross-target call boundary survives.

Caused by: ClickHouse#107566

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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