Repository navigation
Route LLVM JIT allocations to a dedicated jemalloc arena - #104113
Conversation
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]>
|
Workflow [PR], commit [bf11f1e] Summary: ❌
AI ReviewSummaryThis PR routes Missing context / blind spots
Findings
Final VerdictStatus: Minimum required action: fix the |
…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
`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
…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]>
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
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`.") \ |
There was a problem hiding this comment.
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."?
LLVM Coverage Report
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 |
2eca119
LLVM allocates through global
operator new, so its bookkeeping (TargetMachine, target-specificSubtarget, IR modules, optimization-pass analyses, RuntimeDyld relocation tables, and the executable/data page blocks reserved byJITModuleMemoryManagerviaposix_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 existingJemallocCacheArena) and routes LLVM-touching code paths inCHJIT(constructor + bothcompileModuleoverloads +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
LLVMContextinterns types and constants for its lifetime, this also givesSYSTEM DROP COMPILED EXPRESSION CACHEa way to fully reclaim that state. The static singletons inAggregator.cppandExpressionJIT.cppare nowshared_ptr<CHJIT>. Each in-flight compile and each cache holder retains its own handle, and the newreset*JITInstancecalls 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_bytesanddirty_bytes(async) — LLVM heap state in the dedicated arena, including the page-block reservations counted byCompiledExpressionCacheBytes(the two overlap;CompiledExpressionCacheBytesis a subset, sinceposix_memalignis intercepted intoje_posix_memalignand routed to the JIT arena while the linker block runs inside the scope).CompiledExpressionCacheBytesMaxandCompiledExpressionCacheCountMax(async) — configured cache limits, paired with the existingCompiledExpressionCache{Bytes,Count}CurrentMetrics so callers can compute headroom.CompiledExpressionCacheBytesdescription has been clarified to spell out that it countsPageArenareserved capacity (page-rounded with a 2× over-provisioning factor in our custom allocator), not actual machine-code bytes.SYSTEM DROP COMPILED EXPRESSION CACHEnow 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):
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, andCompiledExpressionCacheCountMaxfor observability.SYSTEM DROP COMPILED EXPRESSION CACHEnow also drops the underlying CHJIT instances and purges the JIT arena.Documentation entry for user-facing changes
Version info
26.6.1.224