Repository navigation
Configurable per-CPU jemalloc arena pool for MergeTree metadata - #109490
Conversation
The dedicated MergeTree jemalloc arena (`JemallocMergeTreeArena`) was entered with function-wide scopes that dragged large volumes of short-lived allocations into a single arena. On many-core boxes with constant merges this serializes on that arena's mutexes (`malloc_mutex_lock_slow`), roughly doubling merge durations. Narrow the scopes so only allocations that survive for the part lifetime are routed into the arena: - `IMergeTreeDataPart::loadColumnsChecksumsIndexes`: wrap only the middle load sequence (`loadColumnsSubstreams` .. `loadProjections`). `loadColumns` runs outside (its persistent output is arena-scoped inside `setColumns`; its file read and text/JSON parsing are short-lived scratch). `checkConsistency` (pure file-existence/size verification, allocates nothing persistent) and the tiny tail (`loadDefaultCompressionCodec` / `loadSourcePartsSet`) also run outside. - `MergeTask::ExecuteAndFinalizeHorizontalPart::prepare`: drop the scope entirely. The persistent part metadata it produces is already arena-scoped where it is created (`MergeTreeDataPartBuilder::build` and `IMergeTreeDataPart::setColumns`); the rest of `prepare` is merge-lifetime scratch. Measured on a 60-column table under a constant insert+OPTIMIZE FINAL workload: allocation churn concentrated on the single arena drops from ~98.9% to ~81.1% of all arena churn, diverting the short-lived traffic (file-existence checks, metadata parsing, pipeline setup) back to the default per-CPU arenas. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The dedicated MergeTree metadata arena was a single arena for the whole
server. On many-core machines with constant merges, all metadata
allocations serialize on that one arena's mutexes.
Add the `jemalloc_merge_tree_arenas` server setting (default 1, current
behavior):
- 0 -> disabled (metadata uses the default per-CPU arenas),
- 1 -> a single shared arena,
- N -> a pool of N arenas, routing each allocation to `cpu_id % N`
(capped at the CPU core count, since routing is per-CPU).
`getArenaIndex` resolves the arena from the current CPU per call rather
than caching it per thread, so a thread that migrates CPUs follows its
CPU's arena instead of pinning a foreign one. The lookup is on the
per-scope path (once per part load / merge prepare), not per allocation.
Expose `jemalloc.mergetree_arena.count` and sum the existing
`pactive` / `pdirty` / `active_bytes` / `dirty_bytes` metrics across the
pool; update their descriptions accordingly.
Add an integration test asserting the setting drives the arena count
(disabled / single / pool / capped) and routing.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`PerCPU::getCurrentCPU` previously returned -1 off Linux, so the
per-CPU MergeTree arena pool (and ProfileEvents sharding) collapsed to a
single shard on macOS.
Implement both cheaply, keeping the always-inline hot path syscall-free:
- getCurrentCPU on Apple Silicon reads the CPU number from
`TPIDRRO_EL0` (the source libplatform's `_os_cpu_number` reads);
on x86_64 macOS it uses `rdtscp` (its aux register is CPU-correlated;
where the platform does not encode it there, callers collapse to one
shard). `cpuid` would give the exact APIC id but is serializing and
too costly for the per-event call site.
- getNumCPUs falls back to `sysconf(_SC_NPROCESSORS_ONLN)` off Linux.
The returned id is not guaranteed dense; callers already bound it
(`cpu % N`, or `cpu < N ? cpu : 0`).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [b4ee1ea] Summary: ✅
AI ReviewSummaryThis PR narrows Findings
Final Verdict |
Fixes the clang-tidy `google-runtime-int` failure on the bare `long` in `getNumCPUs` and switches the surrounding CPU-count / CPU-id code to the project's `UInt32` / `Int32` / `Int64` types. Raw types are kept only where they match an external API (`unsigned` jemalloc arena indices, `unsigned int` for `__builtin_ia32_rdtscp`, `size_t` for container sizing). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The first Darwin implementation read `TPIDRRO_EL0 & 0x7`, distinguishing only 8 CPUs, so a per-CPU pool larger than 8 reported/created arenas that `cpu % N` could never reach on Apple Silicon. Mirror libsyscall's `_os_cpu_number` instead: `TPIDR_EL0 & 0xfff` on AArch64 and the per-CPU IDT base via `sidt` on x86_64, both decoding 12 bits (up to 4096 CPUs). Capping the pool at the CPU count is then accurate on any real machine, so the arena count is honest again. Reference pinned to the exact source revision. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Updating the branch to fix the |
`clickhouse-local` loads `ServerSettings` but never called `JemallocMergeTreeArena::initialize`, so `jemalloc_merge_tree_arenas` was silently ignored there and every MergeTree path got arena 0 — regressing even the default (a single dedicated arena) outside `clickhouse-server`. Initialize the pool from `LocalServer` right after the jemalloc setup, before any parts are loaded, mirroring the server. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`initialize` logged an Information-level line on every startup. Now that `clickhouse-local` also initializes the pool, that line polluted its stderr and broke the many fast tests that match exact client/local output. The original single-arena code (and the cache/JIT arena helpers) log nothing here; only the failure path keeps its LOG_ERROR. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`getNumCPUs` used `sysconf(_SC_NPROCESSORS_ONLN)` on every non-Linux target, but `getCurrentCPU` only has Linux and Darwin paths and returns -1 elsewhere. On FreeBSD/other BSD that made callers size per-CPU structures for N CPUs while every lookup fell back to slot/row 0: `ProfileEvents` regressed from one row to N-row scans, and the arena pool created and reported N arenas with no actual sharding. Report the real count only where `getCurrentCPU` can route (Linux, Darwin) and 1 otherwise, so unsupported platforms keep the previous single-shard behavior instead of allocating unreachable shards. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`cpu_id % N` with `N = get_nprocs_conf()` overstated the pool and left arenas unreachable under a restrictive CPU affinity: cpuset-limited deployments created more arenas than any `cpu_id` could reach, and sparse/offset masks (e.g. 0,2,4,6) aliased several CPUs onto the same slot. Size the pool by the CPUs the process may actually run on (its affinity mask on Linux, `[0, getNumCPUs())` elsewhere) and build a dense CPU->slot map at startup, so every created arena is reachable and `jemalloc.mergetree_arena.count` reflects arenas that really receive allocations. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`loadSourcePartsSet` rebuilds `min_max_versions_by_part` / `source_parts_by_version`, which live for the whole patch-part lifetime, so it is long-lived metadata rather than scratch. Scope it into the dedicated arena like the other loaders instead of leaving it on the default arenas. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous check (aggregate active_bytes > 0) would pass even if every allocation were routed to arena 0. Add a check that, after a merge-heavy multi-part workload, live metadata lands in at least two distinct dedicated arenas (per-arena `active` from malloc_stats_print), skipped when the pool collapses to a single arena. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`MergeTask::prepare` dropped its arena scope entirely, but `build()` only scopes the `IMergeTreeDataPart` object. The `SingleDiskVolume` and the `DataPartStorageOnDiskFull` (from `getProjection` / `withPartStorageType`) constructed before it are stored on the merged part and live for its whole lifetime, yet escaped to the default arenas on the hot merge path. Wrap just the volume/storage/`build()` construction in a `ScopedJemallocThreadArena` block, matching `MergeTreeData::loadDataPart` and `DataPartsExchange`; the broad merge-setup scratch stays outside. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`MergeTask::prepare` populates `partition`, `ttl_infos`, the minmax index, `expired_columns` and (for patch parts) `source_parts_set` after `build()`, interleaved with merge-only scratch, so they were allocated in the default arenas — leaving long-lived part metadata outside the dedicated arena on TTL/patch merges and understating `jemalloc.mergetree_arena.*`. Re-home these small, part-lifetime members into the arena in one scoped block after `setColumns` (a cheap copy of small objects), instead of scattering scopes through the interleaved merge logic. The transient merge scratch stays in the default per-CPU arenas. Matches the per-part metadata `MutateTask` already keeps arena-scoped. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The zero-level write path (`MergeTreeDataWriter::writeTempPartImpl`) built `partition`, `ttl_infos`, the minmax index and patch `source_parts_set` outside any dedicated-arena scope, so ordinary INSERT-created parts kept that long-lived metadata in the default arenas and understated `jemalloc.mergetree_arena.*`. Factor the re-home logic that `MergeTask` used into a reusable `IMergeTreeDataPart::moveMetadataToDedicatedArena` and call it from both the merge and write paths, so all part-creation paths converge on the dedicated arena. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- The sharding test now proves pool sharding: the cache arena is disabled on that node and the inserts disable expression compilation, so the MergeTree pool arenas are the only manually-created arenas and unrelated cache/JIT growth cannot satisfy the assertion. OPTIMIZE errors propagate instead of being suppressed. - 03268 asserts the exact allowed granularity capacities per build (tight on jemalloc builds where finalize re-homes via a tight copy, the untightened 128-byte growth capacity otherwise) instead of a one-sided bound that would accept arbitrary over-reporting. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 443/490 (90.41%) · Uncovered code |
|
📊 Cloud Performance Report 🟢 AI verdict: The change bumps jemalloc and restructures MergeTree metadata arena allocation, but the default (a single dedicated arena) matches prior behavior, so any real query-time effect comes mainly from the allocator upgrade — which fits the cluster of modest 12-25% improvements on memory-heavy queries (Q25, Q30 clearly drop below master's normal band). Two headline speedups were downgraded: Q28's ×6.4 faster rides an anomalous base run that sits far above master's band while the source is squarely inside it, and Q23's ×2.4 faster is variance — both medians fall within master's band and the source runs were very noisy. The suppressed Q4 checks out: both medians sit inside the normal band, so its -13.7% is envelope variance. Net read: a plausible small across-the-board allocator improvement, no regressions, and no evidence of the outsized wins being real. clickbench🟢 4 improved · Flagged queries (8 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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
|
Backport #109490 to 26.7: Configurable per-CPU jemalloc arena pool for MergeTree metadata
Cherry pick #109490 to 26.6: Configurable per-CPU jemalloc arena pool for MergeTree metadata
…r MergeTree metadata
Cherry pick #109490 to 26.5: Configurable per-CPU jemalloc arena pool for MergeTree metadata
…r MergeTree metadata
Backport #109490 to 26.5: Configurable per-CPU jemalloc arena pool for MergeTree metadata
Backport #109490 to 26.6: Configurable per-CPU jemalloc arena pool for MergeTree metadata
…narrow-scope Configurable per-CPU jemalloc arena pool for MergeTree metadata
The dedicated jemalloc arena for long-lived
MergeTreemetadata is a single arena for the whole server. On many-core machines under constant merges, all per-part / per-table metadata allocations serialize on that one arena's mutexes, which shows up as increased time inmalloc_mutex_lock_slowand roughly doubled merge durations.This reduces that contention in several ways:
Narrow the arena scopes to the allocations that actually live for the part / table lifetime. Short-lived work (file-existence / size checks in
checkConsistency, text / JSON parsing inloadColumns, merge-setup scratch inMergeTask::prepare) no longer routes into the arena and stays in the default per-CPU arenas. Measured on a 60-column table under constant insert +OPTIMIZE FINAL, this drops the share of allocation churn concentrated on the single arena from ~99% to ~81%.Re-home the long-lived metadata of freshly written parts into the dedicated arena, so parts produced by insert, merge and mutation match reloaded parts instead of pinning pages in the default arenas for their whole lifetime. This covers the checksums, the in-memory index granularity and primary index, the per-column and per-secondary-index size maps, projection map nodes, and (when column statistics are enabled) the cached estimates.
Make the arena configurable via a new
jemalloc_merge_tree_arenasserver setting:0disables the dedicated arena (metadata uses the default per-CPU arenas),1keeps a single shared arena (the default, current behavior), andN > 1creates a pool of up toNarenas, capped at the number of CPUs the server may run on. Each allowed CPU is mapped to a pool arena (honoring the affinity mask / cpuset, and hosts with more than 1024 CPUs), and the arena is resolved from the current CPU per scope-entry (once per part load / merge prepare, not per allocation), not cached per thread, so a thread that migrates CPUs follows its CPU's arena. Setting it to the core count gives one arena per CPU, so no single mutex serializes.Aggregate the existing arena byte metrics across the pool and add
jemalloc.mergetree_arena.count.PerCPU::getCurrentCPU/getNumCPUsare also implemented on Darwin (Apple Silicon reads the CPU number from the low bits ofTPIDR_EL0, x86_64 from the per-CPU IDT base viasidt), so the pool shards on macOS instead of collapsing to a single arena.The default (
1) preserves current behavior; operators opt into sharding on many-core systems. An integration test covers the setting values (disabled / single / pool / capped) and routing.Related: #109467
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the
jemalloc_merge_tree_arenasserver setting controlling the dedicated jemalloc arena(s) used forMergeTreepart and table metadata:0disables it,1uses a single arena (default), andNcreates a per-CPU pool. On many-core servers a pool reduces memory-allocator lock contention between concurrent merges. The dedicated arena was also narrowed to hold only long-lived metadata.Version info
26.7.2.13,26.6.2.118,26.5.6.73