Skip to content

Preload the host's jemalloc into ThinLTO links - #130705

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:thinlto-link-jemalloc
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:thinlto-link-jemalloc

Conversation

@groeneai

@groeneai groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130064

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

ThinLTO builds link faster and with less memory when the build host has jemalloc: the linker runs with libjemalloc.so.2 preloaded, and the clickhouse/binary-builder image now installs libjemalloc2. The linked binary is unchanged. -DENABLE_THINLTO_LINK_JEMALLOC=0 turns it off.

Description

lld runs the ThinLTO backends (optimization and code generation of every module) inside the linker process, one thread per core, and those threads contend in glibc malloc.

In the ThinLTO + lld block of CMakeLists.txt, when a Linux host has libjemalloc.so.2 and no linker launcher is set, CMAKE_C_LINKER_LAUNCHER / CMAKE_CXX_LINKER_LAUNCHER become cmake -E env LD_PRELOAD=<lib>. The launcher wraps only the link command, never PRE_LINK or POST_BUILD, so the official builds' ./clickhouse hash-binary step runs without it. clickhouse/binary-builder installs libjemalloc2. A host without the library, a user-set launcher, or -DENABLE_THINLTO_LINK_JEMALLOC=0 leaves the build as it was. Affected CI builds: amd_release, arm_release (and their performance-reference builds), amd_cfi, and the BOLT build of OptimizeClickHouse.

Validation on x86 (Xeon 6975P), PR amd_release configuration, the clickhouse link pinned to the 32 physical cores of one NUMA node, 3 pairs run concurrently on two nodes, nodes swapped:

  • ld.lld-22 (what CI links with today): median 303.5 s -> 276.4 s (-8.9%), peak RSS 20.7 -> 14.8 GiB (-29%).
  • CI toolchain ld.lld (Use the linker and LLVM tools from the compiler's own toolchain #130659): 283.7 s -> 252.9 s (-10.9%), peak RSS 21.1 -> 15.1 GiB.
  • For each linker, the 6 outputs with and without the preload are byte-identical (same build ID). jemalloc is mapped in the linker process only with the preload.

Configured both on the host (cmake 3.28) and inside the CI image (cmake 4.4.5): only ThinLTO link rules carry the preload.

On Graviton3, where the contention is larger, the reporter measured -25% with the toolchain lld (peak memory 29.4 -> 17.0 GB) and -20% with apt lld for an arm_release-like link: #130064 (comment).


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

lld runs the ThinLTO backends (optimization and code generation of every
module) inside the linker process, one thread per core, and those threads
contend in glibc malloc. When the build host has `libjemalloc.so.2`, ThinLTO
links now run with it preloaded: a linker launcher
`cmake -E env LD_PRELOAD=<lib>` wraps only the link command (never PRE_LINK or
POST_BUILD, so the official builds' `clickhouse hash-binary` check runs
without it). The allocator of the linker does not change what lld computes,
so the linked output is the same.

`clickhouse/binary-builder` installs `libjemalloc2`. The option
`ENABLE_THINLTO_LINK_JEMALLOC` (default ON) turns it off; a linker launcher set
by the user (C or C++) is kept and disables the preload; a host without the
library is unaffected.

Measured on x86 (Xeon 6975P), PR amd_release configuration, the clickhouse
link pinned to the 32 physical cores of one NUMA node, 3 concurrent pairs:
apt ld.lld-22 median 303.5 s -> 276.4 s (-8.9%), peak RSS 20.7 -> 14.8 GiB;
CI toolchain lld 283.7 s -> 252.9 s (-10.9%), peak RSS 21.1 -> 15.1 GiB.
The outputs are byte-identical with and without the preload.

Patch and ARM numbers by @ snelheidai (-25% / -20% on Graviton3),
ClickHouse#130064 (comment)

Related: ClickHouse#130064
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ Show that the CI linker really uses jemalloc and that the output does not change DISAGREE Measured on x86: /proc/<lld>/maps maps jemalloc in every preloaded run and in none of the plain ones (also inside clickhouse/binary-builder); 6 timed pairs, both linkers; every output byte-identical (cmp, same build ID). ARM: the reporter's Graviton3 numbers, linked in the description; this PR's Build (arm_release) shows the CI number.
2 💡 The OptimizeClickHouse BOLT build is a ThinLTO build too AGREE Added to the list of affected builds in the description.
3 💡 cmake -E env replaces an existing LD_PRELOAD for link commands AGREE No change: nothing in CI sets one.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The same clickhouse link (the exact ninja command, PR amd_release objects) run with and without the preload, 32 physical cores each: 3/3 pairs faster and lower peak RSS with the preload.
b Root cause explained? lld runs the ThinLTO backends in one thread per core, and they contend in glibc malloc. A preloaded jemalloc replaces the allocator of the linker process only.
c Fix matches root cause? Yes. The linker launcher wraps only the link command (checked in rules.ninja with cmake 3.28 and with the CI image's cmake 4.4.5); compile, PRE_LINK and POST_BUILD steps are unchanged.
d Test intent preserved / new tests added? Build-system and CI-image change, so no test of the infrastructure itself; validated locally (configure matrix + link A/B).
e Both directions demonstrated? Yes. ld.lld-22: median 303.5 s -> 276.4 s, peak RSS 20.7 -> 14.8 GiB; toolchain lld: 283.7 s -> 252.9 s. jemalloc is mapped in the linker process only with the preload. On a host without the library the generated build files are identical to master's.
f Fix is general across code paths? Every ThinLTO executable link gets it (clickhouse, clickhouse-keeper, compressor, host tools). Non-ThinLTO, sanitizer and ENABLE_TESTS configurations, the native sub-build of cross builds, and Rust links are unaffected (configured).
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked: host with and without the library, the option off, a user-set C or C++ linker launcher (kept, no preload), PR and official flavors, CFI, aarch64 cross, both linkers.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format; -DENABLE_THINLTO_LINK_JEMALLOC=0 gives exactly the previous build files.
i Invariants and contracts preserved? The linked binary is byte-identical with and without the preload (same build ID, same PIE/RELRO/BIND_NOW), and the official builds' clickhouse hash-binary check runs without it.

Session id: cron:clickhouse-impl-slot-41:20261111-053900

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [855229b]

Summary: ✅


AI Review

Summary

PR #130705 preloads the host's libjemalloc.so.2 for eligible ThinLTO links and installs libjemalloc2 in the builder image. The supplied paired benchmarks and byte comparisons support the claimed improvement. No actionable findings in commit 855229bc610c4e1112706b8bb3c8282924910692.

Missing context / blind spots
  • ⚠️ Full-link validation was not repeated locally because CMake, Clang, and build artifacts are unavailable. The current CI report still lists amd_release and arm_release as pending; their completed results would close the remaining CI validation gap.
Final Verdict

Status: ✅ Approve. No required code changes.

@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement can be tested Allows running workflows for external contributors comp-build-system Build system (CMake, compilation, platform builds). labels Nov 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 855229bc6 with master 48f9d3b98 (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.59, programs/clickhouse-keeper ×0.61 (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.7 s 13.3 s +9.9 s (+296%)
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

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, can we instead build our toolchain with jemalloc? See the toolchain build GitHub Actions job. If we can, send another PR.

@alexey-milovidov alexey-milovidov self-assigned this Nov 12, 2026
@snelheidai

Copy link
Copy Markdown

@groeneai, data for @alexey-milovidov's question above: jemalloc in the toolchain's clang, not only in lld, also speeds up compiles. That covers every compile that misses the CI cache, and local builds that use utils/download-ci-toolchain.sh.

I built clickhouse from scratch at master 821d59d (default RelWithDebInfo, empty build directory, no compiler cache) with the CI toolchain's clang and lld 22.1.8 on two 16-core hosts: two builds per allocator, in the order glibc, jemalloc, jemalloc, glibc. jemalloc 5.3.0 (Ubuntu 24.04 libjemalloc2, default options, which never request transparent huge pages) was preloaded through CMake's compiler and linker launchers as a stand-in for a toolchain linked with it, so it ran in the clang and lld processes started by CMake and nowhere else.

Wall time of ninja clickhouse:

Host glibc malloc jemalloc Change
Graviton3, 16 cores, Rust off 3,182 / 3,220 s 2,995 / 3,028 s −190 s (−5.9%)
Xeon 8375C, 16 cores / 32 threads, Rust on 2,195 / 2,193 s 2,107 / 2,106 s −88 s (−4.0%)

On each host every jemalloc build was faster than every glibc build, and the clickhouse binary was byte-identical in all four builds. User CPU time fell 7.0% on Graviton3 and 4.6% on x86; system time rose 2-4% and page faults 8-9%. No build had a compaction stall or a huge-page fault, and the lowest available memory during a build was 1.8-2.4 GiB higher with jemalloc. These builds link clickhouse without ThinLTO in about 10 s, so for release builds the ThinLTO link gains measured in this PR come on top.

Commands
JE=/usr/lib/aarch64-linux-gnu/libjemalloc.so.2   # x86_64: /usr/lib/x86_64-linux-gnu/libjemalloc.so.2
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCOMPILER_CACHE=disabled \
  -DCMAKE_C_COMPILER=<toolchain>/bin/clang -DCMAKE_CXX_COMPILER=<toolchain>/bin/clang++ \
  -DCMAKE_C_COMPILER_LAUNCHER="env;LD_PRELOAD=$JE" -DCMAKE_CXX_COMPILER_LAUNCHER="env;LD_PRELOAD=$JE" \
  -DCMAKE_ASM_COMPILER_LAUNCHER="env;LD_PRELOAD=$JE" \
  -DCMAKE_C_LINKER_LAUNCHER="env;LD_PRELOAD=$JE" -DCMAKE_CXX_LINKER_LAUNCHER="env;LD_PRELOAD=$JE"
/usr/bin/time ninja -C build clickhouse

The glibc builds use the same commands without the five launcher options. The Graviton3 builds ran with -DENABLE_RUST=OFF.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, that's really great, let's do it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm investigating linking the toolchain's clang and lld with jemalloc in ci/jobs/build_toolchain.py; I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The toolchain PR is #131183: clang, lld and the other stage 2 executables now link Ubuntu's static jemalloc 5.3.0 (libjemalloc-dev in clickhouse/binary-builder). Locally on x86, a from-scratch ninja clickhouse was 4.7% faster and the ThinLTO link of clang 4.3% faster, with byte-identical outputs. Since #130659, CI links with the toolchain's lld, so once the rebuilt toolchain is pinned the preload in this PR is redundant in CI and would only help local builds with a distro lld. I'm leaving this PR open for you to close or keep.

@alexey-milovidov

Copy link
Copy Markdown
Member

Closing in favor of #131183

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-build-system Build system (CMake, compilation, platform builds). pr-build Pull request with build/testing/packaging improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants