Skip to content

Configurable per-CPU jemalloc arena pool for MergeTree metadata - #109490

Merged
Algunenano merged 48 commits into
ClickHouse:masterfrom
Algunenano:mergetree-arena-narrow-scope
Jul 23, 2026
Merged

Algunenano merged 48 commits into
ClickHouse:masterfrom
Algunenano:mergetree-arena-narrow-scope

Conversation

@Algunenano

@Algunenano Algunenano commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

The dedicated jemalloc arena for long-lived MergeTree metadata 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 in malloc_mutex_lock_slow and 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 in loadColumns, merge-setup scratch in MergeTask::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_arenas server setting: 0 disables the dedicated arena (metadata uses the default per-CPU arenas), 1 keeps a single shared arena (the default, current behavior), and N > 1 creates a pool of up to N arenas, 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 / getNumCPUs are also implemented on Darwin (Apple Silicon reads the CPU number from the low bits of TPIDR_EL0, x86_64 from the per-CPU IDT base via sidt), 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):

  • Improvement

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

Added the jemalloc_merge_tree_arenas server setting controlling the dedicated jemalloc arena(s) used for MergeTree part and table metadata: 0 disables it, 1 uses a single arena (default), and N creates 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

  • Backported to: 26.7.2.13, 26.6.2.118, 26.5.6.73

Algunenano and others added 3 commits July 6, 2026 13:29
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b4ee1ea]

Summary: ✅


AI Review

Summary

This PR narrows JemallocMergeTreeArena scopes, adds the jemalloc_merge_tree_arenas startup setting, and routes more long-lived MergeTree metadata into dedicated jemalloc arena(s). Most of the earlier review points are addressed in the current code, and CI is green, but one platform-specific contract break remains on Darwin arm64.

Findings

⚠️ Majors

  • [src/Common/PerCPU.h:32] [dismissed by author -- https://github.com/Configurable per-CPU jemalloc arena pool for MergeTree metadata #109490#discussion_r3623452555] The new Darwin/AArch64 getCurrentCPU path still uses TPIDR_EL0 & 0xfff even though the code comment now explicitly acknowledges that macOS 11 keeps _os_cpu_number in TPIDRRO_EL0 instead. I still consider this real because docs/en/development/build-osx.md:15 still advertises Apple Silicon builds on macOS 10.15+, so on supported macOS 11 arm64 builds getNumCPUs reports the real core count while getCurrentCPU misroutes or collapses both ProfileEvents sharding and jemalloc_merge_tree_arenas. That makes the new setting semantics and jemalloc.mergetree_arena.count wrong again on that platform. Suggested fix: add a runtime/version-aware fallback for pre-macOS-12 arm64, or clamp Darwin arm64 to a single shard below macOS 12 and document the limitation explicitly.
Final Verdict

⚠️ One major Darwin arm64 compatibility issue remains, so this is not ready to approve as-is.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 6, 2026
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]>
@azat azat self-assigned this Jul 6, 2026
Comment thread src/Common/JemallocMergeTreeArena.cpp Resolved
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]>
Comment thread src/Common/JemallocMergeTreeArena.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Updating the branch to fix the 04001_join_reorder_through_expression and 03532_window_function_and_null_source_max_threads tests, which were broken today in master.

Comment thread src/Common/PerCPU.h Resolved
Comment thread programs/server/Server.cpp Resolved
`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]>
Comment thread src/Common/PerCPU.h Resolved
`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]>
Comment thread src/Common/PerCPU.cpp Resolved
`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]>
Algunenano and others added 3 commits July 8, 2026 12:56
`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]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
`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]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
`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]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 443/490 (90.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 4 query(s) improved out of 27 analysed

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 · ⚠️ 4 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 10 improvement 176 147 -16.5% <0.0001 memory: Modest -16.5%, plausibly from the jemalloc upgrade, but both medians land inside master's band [146, 176] (source at the floor, base at the ceiling), so treat it as borderline.
🟢 25 improvement 154 130 -15.6% <0.0001 memory: Source (130ms) drops just below master's band floor [135, 151] with stable runs, a clean modest -15.6%; consistent with the jemalloc upgrade trimming allocator overhead.
🟢 30 improvement 318 240 -24.5% <0.0001 memory: Source (240ms) drops below master's band floor [262, 326], a genuine -24.5%; the jemalloc upgrade plausibly reduces allocator overhead here.
🟢 31 improvement 393 344 -12.5% <0.0001 memory: Modest -12.5%, but both medians sit inside master's band [335, 414], so read it as borderline rather than a firm win.
⚠️ 18 not_sure 1330 1248 -6.2% <0.0001 memory: Borderline -6.2% with mixed signals from the two tests; not_sure is the right call and there is no clear tie to the allocator change.
⚠️ 23 not_sure 169 71 ×2.4 faster <0.0001 io: Downgraded: both medians sit inside master's band [69, 169] and the source runs were very noisy, so the ×2.4 faster reading is run-to-run variance on this scan, not the allocator change.
⚠️ 28 not_sure 6646 1040 ×6.4 faster <0.0001 cpu: Downgraded: base (6646ms) sits far above master's band [1015, 4435] while source (1039ms) is inside it, so ×6.4 faster reflects an anomalous baseline, not this change on a regex-heavy query.
⚠️ 32 not_sure 1368 1242 -9.2% <0.0001 memory: Borderline -9.2% with mixed signals from the two tests; not_sure is correct and there is no strong tie to the allocator change.

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
  • StressHouse run: 0ecad95d-2d29-42c6-a35a-3f0dd971e9d1
  • MIRAI run: 32341ab7-8fb8-471b-b255-6bb841bb6a7a
  • PR check IDs:
    • clickbench_13203_1784807772
    • clickbench_13214_1784807772
    • clickbench_13222_1784807772
    • tpch_adapted_1_official_13233_1784807772
    • tpch_adapted_1_official_13245_1784807772
    • tpch_adapted_1_official_13270_1784807772

@Algunenano
Algunenano added this pull request to the merge queue Jul 23, 2026
Merged via the queue into ClickHouse:master with commit 866ac18 Jul 23, 2026
179 checks passed
@Algunenano
Algunenano deleted the mergetree-arena-narrow-scope branch July 23, 2026 18:02
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 23, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 23, 2026
Algunenano added a commit that referenced this pull request Jul 24, 2026
Backport #109490 to 26.7: Configurable per-CPU jemalloc arena pool for MergeTree metadata
robot-clickhouse added a commit that referenced this pull request Jul 24, 2026
Cherry pick #109490 to 26.6: Configurable per-CPU jemalloc arena pool for MergeTree metadata
robot-clickhouse added a commit that referenced this pull request Jul 24, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Jul 24, 2026
Cherry pick #109490 to 26.5: Configurable per-CPU jemalloc arena pool for MergeTree metadata
robot-clickhouse added a commit that referenced this pull request Jul 24, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 24, 2026
Algunenano added a commit that referenced this pull request Jul 24, 2026
Backport #109490 to 26.5: Configurable per-CPU jemalloc arena pool for MergeTree metadata
@fm4v fm4v linked an issue Jul 26, 2026 that may be closed by this pull request
Algunenano added a commit that referenced this pull request Jul 27, 2026
Backport #109490 to 26.6: Configurable per-CPU jemalloc arena pool for MergeTree metadata
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…narrow-scope

Configurable per-CPU jemalloc arena pool for MergeTree metadata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR. v26.5-must-backport v26.6-must-backport v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: 03443_projection_sparse

6 participants