Skip to content

Cherry pick #109490 to 26.5: Configurable per-CPU jemalloc arena pool for MergeTree metadata - #111667

Merged
robot-ch-test-poll4 merged 50 commits into
backport/26.5/109490from
cherrypick/26.5/109490
Jul 24, 2026
Merged

robot-ch-test-poll4 merged 50 commits into
backport/26.5/109490from
cherrypick/26.5/109490

Conversation

@robot-ch-test-poll3

Copy link
Copy Markdown
Contributor

Original pull-request #109490

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

Algunenano and others added 30 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]>
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]>
`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]>
…paths

`build()` self-scopes the part and its storage, but the `SingleDiskVolume`
created just before it (and held by the storage for the part's whole
lifetime) escaped to the default arenas on the two remaining
part-creation paths: `MergeTreeDataWriter::writeTempPartImpl` (INSERT) and
`MergeTreeData::createEmptyPart`.

Wrap the `createVolumeFromReservation` in a `ScopedJemallocThreadArena`
block on both, matching the merge / mutation / load / fetch paths, and
re-home `createEmptyPart`'s partition + minmax via
`moveMetadataToDedicatedArena`. A sibling scan of all part-creation
volume and metadata sites found no other genuine escapes (the rest are
transient: checksum-check parts, merge plans, temp index storage, freeze
backups).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The fixed `cpu_set_t` holds only `__CPU_SETSIZE` (1024) CPUs, so
`sched_getaffinity` failed with EINVAL once the mask covered a CPU id
>= 1024. The pool then fell back to a dense `[0, getNumCPUs())` set and
any `sched_getcpu() >= 1024` collapsed to arena 0 — a large reported
count while every allocation landed in one arena, exactly on the
many-CPU hosts the setting exists for.

Read the mask with a grow-and-retry dynamically-allocated set
(`CPU_ALLOC` / `CPU_ISSET_S`, freed via a unique_ptr deleter), and size
`slot_by_cpu` to the highest allowed CPU id instead of a fixed cap, so
every allowed CPU maps to a reachable arena regardless of count. Runs
once at startup.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The written part's in-memory primary index (`index_columns`, kept when
`save_primary_index_in_memory`) is allocated in `MergeTreeDataPartWriterOnDisk`
while writing and lives on the part until it is merged away — long-lived
metadata that was landing in the default arenas.

Enter `JemallocMergeTreeArena` in the two index-fill blocks (which already
disable the memory tracker for the same "allocated here, freed during
merge" reason), so the index is born in the dedicated arena with no copy.
Covers insert / merge / mutation (all use this writer).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`MergedBlockOutputStream::finalizePart` stores the part-lifetime
`checksums` and index granularity (the latter created and then replaced
by `optimize()` / `fixedFromRowsCount()` here) in the default arenas.
Re-home both into the dedicated MergeTree arena at the end of finalize:
`checksums` by a value copy, the granularity via a new `clone()`
(the pointer is polymorphic, so a plain copy would not deep-copy it).

This is the single chokepoint for insert / merge / mutation, and
projections re-home through their own part's finalize. The in-memory
primary index is already arena-built by the writer, so it is not copied
again here.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The per-column and per-secondary-index size maps built in
calculateColumnsAndSecondaryIndicesSizesOnDisk are cached on the part
for its whole lifetime, so allocate them in the dedicated MergeTree
arena instead of pinning pages in a general arena (small but long-lived
allocations still cause fragmentation). The write/merge/mutation
finalize path reaches this outside any arena scope; the load path
already runs inside one, where the scope nests harmlessly.

Enter the arena before acquiring the mutex so the thread.arena
switch and restore stay out of the critical section: declared
arena-first, the lock destructs first and releases the mutex, then
the arena scope restores.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The abbreviation style check requires CPU in all caps.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Re-homing the index granularity into the dedicated arena at finalize
(via clone) copies the marks_rows_partial_sums vector, which allocates
exactly its size, so a freshly written part no longer carries the spare
growth capacity left by appendMark. index_granularity_bytes_in_memory_allocated
now equals index_granularity_bytes_in_memory (88) for the adaptive part.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
CPU_ALLOC/CPU_FREE resolve to __sched_cpualloc/__sched_cpufree, which
are only available since GLIBC_2.7 and fail the release-binary
compatibility check (max allowed GLIBC 2.4). Allocate the affinity mask
as an aligned unsigned long array instead and keep only the macro
helpers CPU_ALLOC_SIZE and CPU_ISSET_S, which carry no such dependency.
This preserves support for hosts with more than 1024 CPUs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The pool now sizes to the process's allowed CPUs (which may exceed
1024), so compare the capped arena count against the container's CPU
count instead of hard-coding a 1024 upper bound.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The parent part keeps its projection map nodes (and copied projection
name keys) and, when column statistics are enabled, the cached estimates
map for its whole lifetime. Build both in the dedicated MergeTree arena
so freshly written parts do not pin pages in the default arenas.

addProjectionPart is scoped directly so every caller is covered
(insert, merge, projection merge, load). For estimates the transient
statistics load stays in the default arena; only the long-lived cached
map is built under the arena scope.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
clang-tidy's google-runtime-int rejects `unsigned long`. cpu_set_t is an
array of `unsigned long` (`__cpu_mask`), which is 64-bit on the supported
Linux platforms, so UInt64 is equivalent in size and alignment.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
calculateColumnsAndSecondaryIndicesSizesOnDisk resolves a stream name and
builds a sample column for every column and substream; that heavy,
short-lived work was churning the dedicated MergeTree arena. Run the
computation in the default arena and enter the arena only to deep-copy the
finished (small, part-lifetime) size maps, keeping the transient scratch out
of the shared arena while still re-homing the cached result.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a trace_log.arena column carrying the jemalloc arena the calling thread
is bound to at the moment a memory sample is taken (TraceType MemorySample /
JemallocSample), or -1 when unknown or not applicable. It is read via
thread.arena at the send site, which for these trace types runs in a normal
(non-signal) context where je_mallctl is safe. This makes it possible to
attribute sampled allocations to a specific arena, e.g. the dedicated
MergeTree metadata arena versus the per-CPU arenas.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The pool-sharding test asserted per-arena live ("active") bytes grew past a
fixed 1 MiB threshold, which only held while transient churn inflated the
arenas. Compare a per-arena nmalloc delta instead: it is monotonic and
independent of retention or background purge, so it reliably shows the
per-CPU pool routing metadata to several dedicated arenas.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Updates contrib/jemalloc to the ClickHouse jemalloc dev tip, which adds
the ability to resume automatic per-CPU arena selection after a thread
was temporarily bound to a manually managed arena. Under percpu_arena
that was previously rejected with EPERM, leaving the thread pinned to the
manual arena forever. The dedicated MergeTree metadata arena relies on
this to hand worker threads back to per-CPU allocation once a part's
metadata has been routed to the dedicated arena. Also includes the macOS
malloc_getcpu fixes already on dev.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Algunenano and others added 19 commits July 17, 2026 16:18
- Replace the one-line `{ auto v = x; x = std::move(v); }` re-home blocks with a
  reallocateByCopy(T &) helper in Common/Jemalloc.h. It re-allocates a value by
  copying and adopting the copy, so it lands in the thread's currently active
  arena; it does not select an arena itself (enter a ScopedJemallocThreadArena
  scope first). Generic, so the cache/JIT arenas can use it too.
- Warn through system.warnings when fewer dedicated jemalloc arenas could be
  created than intended (getIntendedArenaCount vs the created count), emitted
  from the server only so clickhouse-local output is unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The column carried the per-CPU jemalloc arena a trace sample was taken
under. It pushed the TraceSender pipe payload over PIPE_BUF on platforms
with the smaller 512-byte limit (Darwin/FreeBSD), tripping the
static_assert(buf_size <= PIPE_BUF). Drop it here and reintroduce it
separately with the payload accounted for.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
moveMetadataToDedicatedArena re-homed the MinMaxIndex too early: on the
merge and mutation paths the index is still empty at that point, and on
the zero-level virtual-column path it is reset to null afterwards and
lazily rebuilt. In all these cases the index (one of the larger
part-lifetime metadata structures) stayed in the default arenas.

Re-home it where each path actually populates it instead:
- setMinMaxIndex deep-copies into the arena (insert, mutation).
- the lazy getMinMaxIndex build is scoped into the arena (reloaded
  parts, zero-level virtual-column reload).
- the in-place merge/update sites in MergeTask are scoped into the arena.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…abled

Two follow-ups on the arena re-home paths:

- Column/secondary-index size maps: move the re-home into the common
  calculateColumnsAndSecondaryIndicesSizesOnDiskUnlocked so the lazy
  getters (getColumnSize, getColumnSizes, getSecondaryIndexSize, ...),
  which call it directly, re-home too instead of leaving the cached maps
  in the default arenas under the default lazy configuration. Move the
  eager calculateColumnsAndSecondaryIndicesSizesOnDisk call out of the
  dedicated-arena scope in loadColumnsChecksumsIndexes so the heavy
  sample-column computation runs in the default arenas and only the
  finished maps are re-homed.

- Short-circuit the pure re-home paths on !isEnabled so the opt-out
  (jemalloc_merge_tree_arenas = 0) really avoids the O(files + marks)
  copies rather than performing them into a no-op arena scope:
  moveMetadataToDedicatedArena and the MergedBlockOutputStream finalize
  block.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
index_granularity_bytes_in_memory_allocated is the reserved capacity of
the granularity structure. For a freshly written adaptive part it is
tightened to the exact size only when the dedicated MergeTree jemalloc
arena re-homes it at finalize; builds without jemalloc (sanitizers) keep
the spare growth capacity, so the exact byte count differs by build.

Assert the stable invariant (allocation reported and at least the
in-memory size) instead of the exact capacity, so the test passes on
both jemalloc and non-jemalloc builds.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
DataPartStorageOnDiskFull (and its root_path / part_dir strings) is a
part-lifetime object, but on the write paths it is created in
withPartStorageType/getProjection before MergeTreeDataPartBuilder::build
enters its arena scope, so ordinary inserts left it in the default arenas.

Scope the two storage-creation chokepoints instead of each call site, so
inserts, empty parts, reloads and projections all route the storage
object into the dedicated arena:
- MergeTreeDataPartBuilder::getPartStorageByType (main part storage)
- DataPartStorageOnDiskFull::getProjection (projection child storage)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nto the arena

The resident primary index is the largest part-lifetime metadata
structure but was landing in the default arenas on every write. The
writer builds it in the arena, but `releaseIndexColumns` reallocated the
surviving buffer via `shrinkToFit` outside any scope, and `setIndex` did
not self-scope its `Index` allocation. Scope the `shrinkToFit` (like the
reload path in `loadIndex`) and make `setIndex` self-scope, covering the
insert, merge and mutation paths in one place.

The hardlink / mutate-some-columns path (`finalizeMutatedPart`) also
re-homed nothing, unlike the full-rewrite path: its checksums (copied
from the source and grown) and index granularity stayed in the default
arenas. Re-home them there, mirroring `MergedBlockOutputStream::finalizePartAsync`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The settings-only and comment-only ALTER paths bypass setProperties (which
already scopes its metadata clone) and call setInMemoryMetadata directly,
cloning the table-lifetime StorageInMemoryMetadata into the default arenas.
Scope those calls so the per-table metadata snapshot lands in the dedicated
arena like the rest of the table metadata.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
DataPartStorageOnDiskBase::freeze, freezeRemote and clonePart allocate
the SingleDiskVolume and (via create) the DataPartStorageOnDiskFull for
the new part outside any arena scope. These feed the clone/freeze
part-creation flows (ATTACH PARTITION, REPLACE PARTITION, FREEZE, and
background moves via clonePart / makeCloneOnDisk), so those parts kept
their storage wrapper in the default arenas.

Scope the volume + create tail in all three methods so the part-lifetime
storage object lands in the dedicated arena, matching the builder-owned
storage path. The downstream builders (cloneAndLoadDataPart, the parts
mover) receive the already-arena-homed storage.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
MergeTreeData::getPatchPartMetadata caches the patch part
StorageInMemoryMetadata per partition in patch_parts_metadata_cache for
the table's lifetime, but built it outside any arena scope, leaving that
per-table metadata in the default arenas. Build it in the dedicated arena
like the rest of the per-table metadata.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rrow-scope

# Conflicts:
#	src/Storages/StorageMergeTree.cpp
#	src/Storages/StorageReplicatedMergeTree.cpp
The per-part load callers (loadDataPart, loadPartRestoredFromBackup, the
ATTACH rename loop, and the replicated detached-part attach) entered a
ScopedJemallocThreadArena that spanned the whole part load, including
loadColumnsChecksumsIndexes. That pinned the transient reload scratch
(loadColumns parsing, calculateColumnsAndSecondaryIndicesSizesOnDisk
sample columns, checkConsistency, loadDefaultCompressionCodec) to the
single shared arena, bringing back the churn / lock contention the
narrowing was meant to avoid.

Shrink those outer scopes to cover only the part-lifetime SingleDiskVolume
and storage clone. build() and loadColumnsChecksumsIndexes now run in the
default per-CPU arenas; the persistent metadata they cache is still routed
into the dedicated arena by the self-scoping setters and the inner scope.

Projection loading is moved out of the parent's inner scope and no longer
takes its own broad scope, so each projection sub-part's own
loadColumnsChecksumsIndexes runs in the default arenas too; only the
metadata-only checksums load is scoped.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The ALTER fast paths already route their StorageInMemoryMetadata clone
into the dedicated MergeTree arena, but the replicated startup paths did
not: ReplicatedMergeTreeRestartingThread stores a withMetadataVersion
clone from the restarting thread (outside the constructor's arena scope),
and the replicated constructor's store was only implicitly covered by the
distant registerStorageMergeTree factory scope. Both keep a full
table-lifetime metadata snapshot, so every replicated table pinned one in
the default arenas after create/restart.

Scope both explicitly so replicated startup converges with the ALTER
paths. A tree-wide sweep of every setInMemoryMetadata / withMetadataVersion
caller confirms all MergeTree table-metadata stores are now arena-routed
(the per-table patch / columns-description / serialization-hint caches
were already covered).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review-driven cleanups keeping every long-lived allocation in the
dedicated arena while transient scratch stays on the default arenas:

- loadDataPart: drop the eager DataPartStorageOnDiskFull clone (the
  builder creates the real, arena-routed storage); the duplicate-part
  log uses the part's own storage.
- getProjection / loadChecksums no longer pin the arena themselves:
  most callers are transient probes (CHECK TABLE, mutation hardlinks,
  existence checks). The part-lifetime projection storage is created
  under the arena in getProjectionPartBuilder, and real checksum loads
  run inside their callers' scopes.
- Mutation prepare scopes only the part-lifetime SingleDiskVolume;
  build() self-scopes, partition/ttl_infos are re-homed via
  moveMetadataToDedicatedArena, and mutation planning scratch stays on
  the default arenas.
- changeRootPath builds the replacement root_path under the arena, so
  projection storage paths do not escape on parent-part commit.
- ttl_infos is re-homed at both finalize chokepoints: TTLTransform
  rebuilds it from scratch during the write, discarding the copy
  re-homed at prepare time.
- The finalize checksums copy happens once, directly under the arena,
  instead of assigning and re-homing with a second copy.
- The primary index stays in the MergeTree arena even when owned by
  PrimaryIndexCache: re-homing at the cache boundary could fail after
  the part is already committed, so one arena is the safe choice
  (documented on the loadIndex scope).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Initialize the pool after the ZooKeeper-include config reload, so a
  `jemalloc_merge_tree_arenas` value supplied via `from_zk` is honored
  (still well before any parts are loaded).
- On an affinity-read failure, fail closed to a single arena (reachable
  from any CPU) with a warning instead of fabricating [0, getNumCPUs())
  and leaving arenas unreachable under a restrictive mask.
- Publish the pool's pactive/pdirty metrics only when every arena was
  read successfully; a partial prefix would look like a plausible total.
- Correct the degraded-pool diagnostics: partial creation runs with the
  created arenas; only zero created arenas fall back to the default.
- Documentation: `PrimaryIndexCacheBytes` / `mergetree_arena.active_bytes`
  state the deliberate MergeTree-arena placement of cache-owned primary
  indexes (qualified by the pool being enabled), and the Darwin per-CPU
  comment names the pre-macOS-12 `TPIDRRO_EL0` layout (bounded to
  degraded sharding, verified against Apple's `_os_cpu_number`).

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]>
Configurable per-CPU jemalloc arena pool for MergeTree metadata
@robot-ch-test-poll3 robot-ch-test-poll3 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Jul 23, 2026
…cherrypick-26.5-109490

# Conflicts:
#	contrib/jemalloc
#	programs/local/LocalServer.cpp
#	src/Common/AsynchronousMetrics.cpp
#	src/Common/JemallocMergeTreeArena.h
#	src/Common/PerCPU.cpp
#	src/Common/PerCPU.h
#	src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp
#	src/Storages/MergeTree/MergeTreeDataWriter.cpp
#	src/Storages/MergeTree/MergedBlockOutputStream.cpp
#	src/Storages/MergeTree/ReplicatedMergeTreeRestartingThread.cpp
#	src/Storages/StorageMergeTree.cpp
#	src/Storages/StorageReplicatedMergeTree.cpp
@robot-ch-test-poll4
robot-ch-test-poll4 merged commit e1fc4bf into backport/26.5/109490 Jul 24, 2026
1 check passed
@robot-ch-test-poll4
robot-ch-test-poll4 deleted the cherrypick/26.5/109490 branch July 24, 2026 09:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants