Skip to content

Route LLVM JIT allocations to a dedicated jemalloc arena - #104113

Merged
Algunenano merged 15 commits into
ClickHouse:masterfrom
Algunenano:jit-arena-routing
May 28, 2026
Merged

Algunenano merged 15 commits into
ClickHouse:masterfrom
Algunenano:jit-arena-routing

Conversation

@Algunenano

@Algunenano Algunenano commented May 5, 2026 •

Copy link
Copy Markdown
Member

LLVM allocates through global operator new, so its bookkeeping (TargetMachine, target-specific Subtarget, IR modules, optimization-pass analyses, RuntimeDyld relocation tables, and the executable/data page blocks reserved by JITModuleMemoryManager via posix_memalign) lands in the default jemalloc arena. There it interleaves with short-lived query-processing allocations and pins those pages alive, contributing to RSS fragmentation that doesn't shrink even after compiled modules are evicted.

This change adds a dedicated jemalloc arena (JemallocJITArena, mirroring the existing JemallocCacheArena) and routes LLVM-touching code paths in CHJIT (constructor + both compileModule overloads + deleteCompiledModule) through a thread-scoped arena guard (mallctl("thread.arena", ...)). Frees auto-route via jemalloc's per-extent metadata, so only allocation paths need scoping.

Because LLVMContext interns types and constants for its lifetime, this also gives SYSTEM DROP COMPILED EXPRESSION CACHE a way to fully reclaim that state. The static singletons in Aggregator.cpp and ExpressionJIT.cpp are now shared_ptr<CHJIT>. Each in-flight compile and each cache holder retains its own handle, and the new reset*JITInstance calls drop only the static slot — the instance itself dies once every user has released its handle, so concurrent compilations can never use a destroyed instance.

New observability:

  • jemalloc.jit_arena.active_bytes and dirty_bytes (async) — LLVM heap state in the dedicated arena, including the page-block reservations counted by CompiledExpressionCacheBytes (the two overlap; CompiledExpressionCacheBytes is a subset, since posix_memalign is intercepted into je_posix_memalign and routed to the JIT arena while the linker block runs inside the scope).
  • CompiledExpressionCacheBytesMax and CompiledExpressionCacheCountMax (async) — configured cache limits, paired with the existing CompiledExpressionCache{Bytes,Count} CurrentMetrics so callers can compute headroom.
  • The CompiledExpressionCacheBytes description has been clarified to spell out that it counts PageArena reserved capacity (page-rounded with a 2× over-provisioning factor in our custom allocator), not actual machine-code bytes.

SYSTEM DROP COMPILED EXPRESSION CACHE now also resets both CHJIT singletons and purges the JIT arena, returning freed pages to the OS without waiting on the decay timer.

Concurrency was verified with TSan: 60 s stress with 8 JIT-compile workers and 2 cache-drop threads against the patched server, zero data-race / deadlock reports.

Changelog category (leave one):

  • Improvement

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

Route LLVM/JIT allocations to a dedicated jemalloc arena. Reduces RSS fragmentation caused by interleaving long-lived JIT bookkeeping with short-lived query allocations. Adds new asynchronous metrics jemalloc.jit_arena.active_bytes, jemalloc.jit_arena.dirty_bytes, CompiledExpressionCacheBytesMax, and CompiledExpressionCacheCountMax for observability. SYSTEM DROP COMPILED EXPRESSION CACHE now also drops the underlying CHJIT instances and purges the JIT arena.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.224

LLVM allocates through global `operator new`, so its bookkeeping (TargetMachine,
Subtarget, IR modules, optimization-pass analyses, RuntimeDyld relocation
tables, and the executable/data page blocks reserved by JITModuleMemoryManager
via posix_memalign) lands in the default jemalloc arena. There it interleaves
with short-lived query-processing allocations and pins those pages alive,
contributing to RSS fragmentation that doesn't shrink even after compiled
modules are evicted.

This change creates a dedicated jemalloc arena for JIT allocations and routes
them via a thread-scoped guard around each LLVM-internal block in CHJIT
(constructor and compileModule), using `mallctl("thread.arena", ...)`. Frees
auto-route through jemalloc's per-extent metadata, so only allocation paths
need scoping. Because LLVMContext interns types/constants for the lifetime of
the context, this also gives `SYSTEM DROP COMPILED EXPRESSION CACHE` a way to
fully reclaim that state: each in-flight compile and each cache holder retains
a `shared_ptr<CHJIT>`, and the `reset*JITInstance` calls drop only the static
slot, so concurrent operations are not interrupted - the actual instance dies
once every user has released its handle.

New metrics:
- `jemalloc.jit_arena.active_bytes` and `dirty_bytes` (async) - LLVM heap state
  in the dedicated arena, including the page-block reservations counted by
  `CompiledExpressionCacheBytes` (the two overlap, the relationship is
  documented).
- `CompiledExpressionCacheBytesMax` and `CountMax` (async) - configured cache
  limits, paired with the existing `CompiledExpressionCache{Bytes,Count}`
  CurrentMetrics so callers can compute headroom.

`SYSTEM DROP COMPILED EXPRESSION CACHE` now also resets both CHJIT singletons
and purges the JIT arena, returning freed pages to the OS without waiting on
the decay timer.

Tests:
- `04202_jemalloc_jit_arena_metrics.sql` - portable across build variants;
  asserts metric exposure matches the build options it depends on.
- `04203_jit_arena_drop_compiled.sh` - end-to-end: trigger a JIT compile, drop
  the cache, assert the cache count returns to zero. Documents why it does not
  assert on `active_bytes` (background system queries can pin the old CHJIT
  instance via late-arriving cache holders).

Concurrency verified with TSan: 60 s stress with 8 JIT-compile workers and 2
cache-drop threads, zero data-race / deadlock reports.

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

clickhouse-gh Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bf11f1e]

Summary: ❌


AI Review

Summary

This PR routes CHJIT allocation-heavy paths through a dedicated jemalloc arena, adds async metrics for that arena and compiled-expression cache limits, and extends SYSTEM DROP COMPILED EXPRESSION CACHE to reset the JIT singletons before purging the arena. The core ownership changes now look consistent with the drop path, but one user-visible metric description is still incorrect for supported non-jemalloc / disabled-arena builds.

Missing context / blind spots
  • ⚠️ The current Praktika report linked from the PR comment for bf11f1e93c390309b5da3e4657fa7fe6d01ee7ad returned 0 test results, so I could not use it as evidence that the new stateless tests passed. A populated CI report would close this.
Findings

⚠️ Majors

  • [src/Common/CurrentMetrics.cpp:374] CompiledExpressionCacheBytes is exposed independently of whether the dedicated JIT arena is actually enabled, but the description unconditionally says the allocation is intercepted into jemalloc and is a subset of jemalloc.jit_arena.active_bytes. On builds without jemalloc, or when JemallocJITArena::isEnabled is false because arena creation failed, that async metric is absent and the statement is false. Please qualify that part, for example: "When jemalloc and the dedicated JIT arena are enabled, this is also accounted within jemalloc.jit_arena.active_bytes."
Final Verdict

Status: ⚠️ Request changes

Minimum required action: fix the CompiledExpressionCacheBytes description so it remains true when the dedicated jemalloc JIT arena is unavailable.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 5, 2026
@Algunenano Algunenano added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label May 5, 2026
…mpiled

The flaky check observed `cache_count_after_drop 1` instead of 0
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104113&sha=03eaaae057fa81761e03abfabcec564bc82914b0&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29).

The race is pre-existing, not introduced by this PR: the static
`min_count_to_compile_*` counters in `Aggregator.cpp` and `ExpressionJIT.cpp`
are not reset by `SYSTEM DROP COMPILED EXPRESSION CACHE`. Any aggregation
whose description has crossed the threshold before the drop will JIT-compile
and re-populate the just-cleared cache on first reuse — including from
server-internal queries running between our drop and our subsequent metric
read. Resetting the counters on drop would dramatically reduce the chance of
flake but not fully eliminate it (a background query could still cross the
default threshold of 3 during the read window), and that would be a
behavioral change to drop semantics that's out of scope for this PR.

The two surviving assertions — `arena_active_after_compile` and
`cache_count_after_compile` — still cover the new behavior the PR adds. The
drop itself is still issued so the JIT arena gets purged before the test
exits.

PR: ClickHouse#104113
Comment thread src/Interpreters/JIT/CHJIT.cpp Resolved
Comment thread src/Interpreters/JIT/CHJIT.cpp Resolved
Algunenano and others added 4 commits May 6, 2026 09:50
`createArena` previously threw `CANNOT_ALLOCATE_MEMORY` when
`mallctl("arenas.create", ...)` failed. Because `getArenaIndex` is
called unconditionally on every JIT compile path and is implemented as
a Meyers singleton, a transient allocator failure or any environment
that disallows extra arenas turned every JIT compilation into a hard
exception.

This is inconsistent with `ScopedJemallocThreadArena`, which already
deliberately silently degrades to default-arena behavior when the
thread switch fails — the comment in `Jemalloc.cpp` is explicit that
"the cost is fragmentation, not correctness". The arena-creation side
should match that contract.

Log an error and return arena 0 on failure. Passing 0 to
`ScopedJemallocThreadArena` is already a documented no-op, so JIT code
allocates from the default arena and the fragmentation reduction is
disabled — but correctness is preserved and the failure is visible in
the log. `isEnabled` now reflects the actual arena state (still gated
on `USE_EMBEDDED_COMPILER`) and `purge` no-ops when the arena is not
available.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`jemalloc.jit_arena.{active,dirty}_bytes` were derived by multiplying
jemalloc's `pactive`/`pdirty` (page counts) by `getPageSize()` (the OS
page size). On platforms where jemalloc is compiled with `LG_PAGE=16`
(64 KiB — aarch64, ppc64le, riscv64) but the kernel runs 4 KiB pages,
those two differ and the byte metrics under-reported by 16×. Read
jemalloc's own `arenas.page` once via `MibCache<size_t>` instead, the
same pattern `MemoryWorker.h` uses.

x86_64 numbers are unaffected (OS page = jemalloc page = 4 KiB there).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts:
#	src/Common/AsynchronousMetrics.cpp
#	src/Common/Jemalloc.h
Algunenano and others added 2 commits May 13, 2026 11:06
…SSION CACHE

The previous commit migrated the expression and aggregator `CHJIT`
singletons to `shared_ptr` ownership so `SYSTEM DROP COMPILED EXPRESSION
CACHE` can reclaim their persistent LLVM state. `SortDescription` had a
third `static CHJIT` held by value that was not covered, so workloads
using `compile_sort_description` kept `TargetMachine` / `LLVMContext`
state alive in the dedicated JIT arena after the command.

Convert it to the same `shared_ptr<CHJIT>` pattern (holder captures its
own `jit_owner`) and call `resetSortDescriptionJITInstance` alongside
the other two in the SYSTEM DROP path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Core/SortDescription.cpp Resolved
Algunenano and others added 3 commits May 20, 2026 14:11
1. Make `CompiledSortDescriptionFunctionHolder` destructor exception-safe
   by wrapping `deleteCompiledModule` in `try/catch + tryLogCurrentException`,
   matching the pattern already used by `CompiledFunctionHolder` and
   `CompiledAggregateFunctionsHolder`. The destructor is implicitly
   `noexcept`, so an uncaught throw from a divergent-state assertion in
   `deleteCompiledModule` would terminate the process.

2. Add a deterministic post-drop assertion to `04203_jit_arena_drop_compiled`:
   `SYSTEM DROP COMPILED EXPRESSION CACHE` unconditionally calls
   `JemallocJITArena::purge`, which increments the cumulative
   `MemoryAllocatorPurge` ProfileEvent by 1. Compare before/after the drop and
   assert strict increase. Concurrent cache-arena purges from elsewhere can
   only push the delta higher, never lower, so the assertion is race-free.

PR: ClickHouse#104113
@ahmadov ahmadov self-assigned this May 21, 2026
@Algunenano
Algunenano requested a review from ahmadov May 26, 2026 07:51

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

LGTM 👍

Comment thread src/Common/JemallocJITArena.h Resolved
Comment thread src/Interpreters/JIT/CHJIT.cpp Resolved
Algunenano and others added 2 commits May 28, 2026 12:52
1. Move `#include "config.h"` from `JemallocJITArena.h` to its `.cpp`.
   The header has only function declarations and no conditional
   compilation, so it does not need `config.h`.

2. Add a static `JITAllocationScope::run(F &&)` helper that wraps the
   `[] { JITAllocationScope scope; ...; }()` IIFE pattern used in
   `CHJIT::CHJIT` member initializers and inside `CHJIT::compileModule`.
   The two remaining explicit `{ JITAllocationScope scope; ... }` blocks
   (which do not return a value) are left as-is.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
M(QueryConditionCacheEntries, "Total number of entries in the query condition cache") \
M(CompiledExpressionCacheBytes, "Total bytes used for the cache of JIT-compiled code") \
M(CompiledExpressionCacheCount, "Total entries in the cache of JIT-compiled code") \
M(CompiledExpressionCacheBytes, "Reserved page-block capacity (rounded up to whole pages with a 2x over-provisioning factor) held by `JITModuleMemoryManager` for executable/data sections of cached JIT-compiled functions. NOT the actual bytes of machine code in use (that's smaller). Allocated via `posix_memalign`, which is intercepted into jemalloc, so this is accounted within the dedicated JIT arena and is a subset of `jemalloc.jit_arena.active_bytes`.") \

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.

CompiledExpressionCacheBytes is still exposed on builds with USE_EMBEDDED_COMPILER even when jemalloc is disabled, and JemallocJITArena::isEnabled can also be false if the dedicated arena could not be created. In those cases this user-visible description says the bytes are intercepted into jemalloc and are a subset of jemalloc.jit_arena.active_bytes, but that metric is absent and the statement is false.

Can we qualify the last sentence, e.g. "When jemalloc and the dedicated JIT arena are enabled, this is also accounted within jemalloc.jit_arena.active_bytes."?

@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 171/187 (91.44%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@Algunenano
Algunenano enabled auto-merge May 28, 2026 17:01
@Algunenano
Algunenano added this pull request to the merge queue May 28, 2026
Merged via the queue into ClickHouse:master with commit 2eca119 May 28, 2026
164 of 166 checks passed
@Algunenano
Algunenano deleted the jit-arena-routing branch May 28, 2026 17:23
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants