Repository navigation
Description
Changes proposed
Summary
Mounting an empty 64 GiB memory segment in Mooncake Store immediately commits 2 GiB of anonymous virtual memory inside OffsetAllocator before a single KV object is stored; a 100-segment (6.25 TiB) cluster commits 200 GiB of metadata address space up front. This inflates VmSize / Committed_AS, breaks vm.overcommit_memory=2 deployments, never returns memory to the OS after eviction drain, and makes raising fixed node caps costly (as discussed in #5272, Fixed OffsetAllocator node limits can underutilize large SSD caches with small KV pages).
Scope note: Paged tables change when metadata memory is committed and allow reclaiming it when a segment empties. At worst-case saturation (64 Mi live nodes in a single segment), peak metadata memory remains 2 GiB (32 bytes/node plus an 8 KiB chunk directory).
This RFC proposes a focused, behavior-preserving storage upgrade to offset_allocator::__Allocator:
- Unified 2-Level Paged Chunk Table (
64Kslots =2 MiBper full chunk):- Replace contiguous
m_nodesandm_freeNodesstd::vectors (which callreserve(m_max_capacity)) with a dynamically growing directory of2 MiBchunks (65,536slots =1.75 MiBNode+256 KiBNodeIndex), allocated via standard::operator newand lazily initialized one slot at a time asm_current_capacitygrows. - Each chunk is capped at
min(65536, m_max_capacity - chunk_base)so tiny allocators (e.g., small DFS shards) allocate only their exact slot count, while2 MiBchunks keep VMA counts low (safe under Linux's defaultvm.max_map_count = 65,530), keep the max 64 Mi directory at 8 KiB (L1d-resident), and work seamlessly with both jemalloc and glibc.
- Replace contiguous
- Hysteresis
noexceptEmpty-Segment Shrink:- When a segment becomes completely empty and holds excess chunks beyond a hysteresis threshold, detach tail chunks into an intrusive retired list with zero heap allocations (
noexcept) and free them after releasingm_mutex.
- When a segment becomes completely empty and holds excess chunks beyond a hysteresis threshold, detach tail chunks into an intrusive retired list with zero heap allocations (
- 100% Wire-Compatible Serialization & Safe Deserialization:
- Keep
sizeof(Node) == 28and streamNodes thenNodeIndexes in two passes so existing persisted checkpoints remain byte-for-byte compatible (kOffsetAllocatorPersistVersionunchanged). - Add
SerializerReader::remaining()pre-allocation validation, rejectm_current_capacity == 0, raise the hardcoded1 << 24m_max_capacitysanity cap to1 << 26(covering 64 Mi DRAM segments), and rethrowstd::bad_allocso transient OOM is not misclassified as checkpoint corruption (kCorrupt).
- Keep
Non-goals:
- Does not change
OffsetAllocatorSmallFloat binning, allocation/free return semantics,StorageReportsemantics, or publicOffsetAllocator/AllocatedBufferAPIs. - Does not change
OffsetAllocatorStorageBackendkey indexing, on-disk checkpoint format, or node-budget policy (separate follow-ups can safely raise node budgets once upfront reservation is eliminated). - Does not implement arbitrary middle-chunk compaction/reclamation (see Section 2.2).
1. Motivation & Quantified Problem
In offset_allocator::__Allocator::reset() (mooncake-store/src/offset_allocator.cpp), both internal vectors unconditionally reserve up to m_max_capacity:
m_nodes.reserve(m_max_capacity);
m_freeNodes.reserve(m_max_capacity);
m_nodes.resize(m_current_capacity);
m_freeNodes.resize(m_current_capacity);On 64-bit platforms (x86_64 / arm64), sizeof(Node) == 28 bytes (alignof(Node) == 4) and sizeof(NodeIndex) == 4 bytes, totaling 32 bytes per node slot.
Across Mooncake Store, OffsetAllocator is used by:
OffsetBufferAllocator(mooncake-store/src/allocator.cpp, DRAM and NVMe-oF SSD segments):init = clamp(size/4096, 1K, 64K),max = clamp(size/1024, 1Mi, 64Mi).ClientBufferAllocator(mooncake-store/src/client_buffer.cpp): defaultinit = 128K,max = 1Mi.OffsetAllocatorStorageBackend(local SSD offload backend,mooncake-store/src/storage_backend.cpp):init = 128K,max = clamp(capacity/256, 1Mi, ~9.59M).ShardAllocator(distributed filesystem shard backend,mooncake-store/src/storage/distributed/shard_allocator.cpp):init = clamp(cap/4096, 1, 64K),max = clamp(cap/1024, init, 64Mi).
Because large std::vector::reserve requests are backed by anonymous mmap without MAP_NORESERVE, the kernel charges the full reservation against Committed_AS at mount time:
| Workload / Caller | init_capacity |
max_capacity |
Current VmSize / Committed_AS |
Current Initial VmRSS |
Proposed Initial VmSize / VmRSS |
|---|---|---|---|---|---|
4 KiB DFS shard (ShardAllocator) |
1 | 4 | 128 B | 32 B (heap) | 128 B heap (+96 B; capped at max * 32 B) |
| 16 MiB DRAM segment | 4,096 | 1 Mi |
32 MiB (200% of data) | 128 KiB | 2 MiB VmSize (-93.8%) / 128 KiB VmRSS |
16 MiB client buffer (real_client) |
131,072 | 1 Mi |
32 MiB (200% of data) | 4 MiB | 4 MiB / 4 MiB (-87.5% VmSize) |
| 1 GiB DRAM segment | 65,536 | 1 Mi |
32 MiB | 2 MiB | 2 MiB / 2 MiB (-93.8% VmSize) |
| 64 GiB DRAM / NVMe-oF segment | 65,536 | 64 Mi |
2 GiB (1.75 GiB + 256 MiB) | 2 MiB | 2 MiB / 2 MiB (-99.9% VmSize) |
| 100 × 64 GiB cluster (6.25 TiB) | 100 × 64K | 100 × 64 Mi |
200 GiB | 200 MiB | 200 MiB / 200 MiB (-99.9% VmSize) |
| Local SSD backend (1.28 GiB–2 TiB) | 131,072 | up to 9.59M | 32 MiB – 293 MiB | 4 MiB | 4 MiB / 4 MiB |
Operational impact today:
vm.overcommit_memory=2mount failures: Mounting 100 × 64 GiB segments fails withENOMEM/std::bad_allocifCommitLimitcannot absorb 200 GiB of unused metadata reservation.- No reclamation after drain/eviction: Neither
free()norreset()shrinks the vectors; memory is returned only on segment unmount (~__Allocator()). - Blocks [Usage]: Fixed OffsetAllocator node limits can underutilize large SSD caches with small KV pages #5272: Raising
max_capacityfor small-object workloads multiplies upfrontCommitted_ASacross every segment/shard even when larger objects are stored. - Deserialization pitfalls:
__Allocatordeserialization currently callsreserve(m_max_capacity), rejectsm_max_capacity > 2^24(already below DRAM's 64 Mi), allowsm_current_capacity == 0, and swallowsstd::bad_allocintostd::runtime_error/nullptr(serializer.h), causing the SSD backend'scatch (const std::bad_alloc&)to be unreachable and misclassifying transient OOM askCorrupt.
2. Architecture & Design
2.1 Unified 2-Level Paged Chunk Table (64K Slots = 2 MiB / Full Chunk)
Replace m_nodes and m_freeNodes with a single dynamically growing directory (std::vector<std::unique_ptr<ChunkControl>> chunks_) indexed by a compile-time bit-shift:
kChunkShift = 16,kChunkSize = 65,536(1 << 16),kChunkMask = 0xFFFF.- Per-chunk slot count:
uint32_t chunkSlotCount(uint32_t chunk_index) const { return std::min<uint32_t>(kChunkSize, m_max_capacity - chunk_index * kChunkSize); }
- Chunk layout & allocation:
- A full chunk (
65,536slots) allocates a single2 MiBraw block (65,536 × 28 B = 1.75 MiBforNode[], followed immediately by65,536 × 4 B = 256 KiBforNodeIndex[], both 4-byte aligned) using standard::operator new(bytes)/::operator delete(ptr, bytes). - Each chunk is owned by a small
ChunkControlstruct (std::unique_ptr<ChunkControl> next_retired; void* mem; size_t bytes; uint32_t slots;).ChunkControlis allocated before::operator new(bytes)inside an RAII guard sostd::bad_allocnever leaks memory or leaveschunks_/m_current_capacitypartially updated. - Why
::operator new+ lazy per-slot initialization instead ofnew Node[65536]():Nodehas default member initializers (NSDMI), sonew Node[65536]()(and even C++20make_unique_for_overwrite<Node[]>(65536)) would touch all1.75 MiBimmediately on chunk creation—causing RSS regressions for small segments (init = 4096) and a multi-microsecond fault burst insidem_mutex.- Allocating raw storage via
::operator new(bytes)leaves unexposed tail slots untouched (no page faults on Linux until accessed, keeping 16 MiB segment RSS at128 KiB). Wheneverm_current_capacityexposes sloti, we explicitly initialize both arrays for sloti:std::memset(&nodeAt(i), 0, sizeof(Node)); std::construct_at(&nodeAt(i)); freeNodeAt(i) = i;(matching legacyreset()andm_freeNodes.push_back(m_current_capacity)). This guarantees zero uninitialized bytes anywhere in[0, m_current_capacity)(deterministic checkpoints, zero heap leakage, includingNode's 3-byte trailing padding) and safevisit_used_nodes()scans. __Allocatorremains move-only (explicitly declaring= deletecopy constructor/assignment and movingchunks_in O(1) in__Allocator(__Allocator&&)).- Using standard
::operator new/::operator deleteis 100% portable across Linux and macOS and cooperates cleanly with both jemalloc (which manages2 MiBextents without inflating Linux VMA counts and purges dirty pages viamadvise(MADV_DONTNEED)) and glibc (2 MiBexceeds glibc's128 KiBmmap_threshold, while keeping VMA count 16× lower than128 KiBchunks—well below Linux's defaultvm.max_map_count = 65,530).
- A full chunk (
- Directory footprint:
- At
init = 64K(1 chunk):8 B. - At
max = 64 Mi(1,024 chunks):8 KiBtotal (fits in L1d cache).
- At
- Compile-time invariants:
static_assert(sizeof(Node) == 28); static_assert(alignof(Node) == 4); static_assert(std::is_trivially_copyable_v<Node>); static_assert(sizeof(NodeIndex) == 4);
Before vs. After Memory Commitment
flowchart TB
subgraph before ["Current: Contiguous std::vector::reserve(64 Mi)"]
B1["m_nodes: 1.75 GiB upfront mmap"]
B2["m_freeNodes: 256 MiB upfront mmap"]
B3["2 GiB Committed_AS at mount<br/>independent of live object count"]
B1 --- B2 --- B3
end
subgraph after ["Proposed: 2-Level Paged Chunks (64K slots = 2 MiB)"]
A0["chunks_ directory (grows dynamically)<br/>8 B per chunk; max 8 KiB at 64 Mi nodes"]
A1["Chunk 0 (allocated at init)<br/>2 MiB VmSize; only exposed slots faulted into RSS"]
A2["Next chunk (2 MiB)<br/>allocated when m_current_capacity crosses next 64K boundary"]
A3["Unallocated tail chunks<br/>0 bytes data + 0 bytes directory until grown"]
A0 --> A1
A0 --> A2
A0 --> A3
end
before -.->|"Same 2 GiB peak at 64 Mi live nodes<br/>committed on demand instead of at mount"| after
O(1) Bit-Split Indexing
flowchart LR
IDX["NodeIndex idx<br/>(e.g. 1,000,000)"] --> SPLIT["Bit split (shift 16)"]
SPLIT --> HI["Chunk index: idx >> 16<br/>(= 15)"]
SPLIT --> LO["Slot offset: idx & 0xFFFF<br/>(= 16,960)"]
HI --> DIR["chunks_[15]<br/>load chunk base pointer"]
DIR --> CH["Chunk 15 (2 MiB raw block)<br/>nodes[65536] + free_nodes[65536]"]
CH --> NODE["nodeAt(idx) = nodes + 16,960<br/>freeNodeAt(idx) = free_nodes + 16,960"]
LO --> NODE
2.2 Growth, Hysteresis noexcept Shrink, and Lock Boundaries
- Decoupled logical capacity & check-bin-before-grow:
- Logical
m_current_capacitycontinues to increment by +1 only when a new node slot is actually required (preserving exactm_current_capacitysemantics for existing tests such asSerializationOneElementAllocatorand keeping checkpoints minimal). - In
allocate(), find a fitting bin and confirm a split remainder is needed before growingm_current_capacity, so failing allocations never allocate a new chunk. - A new
2 MiBchunk is allocated only whenm_current_capacitycrosses a65,536-slot boundary (reducing chunk-allocation frequency and kernelmmap_lockcontention by 16× compared to4Kchunks).
- Logical
- Provably zero-allocation (
noexcept) empty-segment shrink with hysteresis:- Because
OffsetAllocationHandle::~OffsetAllocationHandle()and move-assignment arenoexcept,free()must never allocate memory. - Hysteresis: Trigger shrink only when
m_freeStorage == m_size(segment completely empty) andchunks_.size() > 1 + kShrinkHysteresisChunks(e.g.,kShrinkHysteresisChunks = 2, i.e., > 4 MiB beyond chunk 0), avoidingmmap/munmapthrashing and TLB shootdown storms when a segment oscillates between empty and lightly populated. __Allocator::shrinkToInitial(std::unique_ptr<ChunkControl>& retired_head) noexcept(O(chunks)insidem_mutex, ~1 µs worst-case):- Keeps
chunks_[0]in place (zero allocation), moves tail chunkschunks_[1..](at most 1,023 pointer moves at 64 Mi nodes) onto the intrusiveretired_headsingly-linked list (novector::push_back), shrinkschunks_size to1, and resets logicalm_current_capacity = 1so only slot0and the 256 bin heads (~1 KiB) are rewritten insidem_mutex:m_current_capacity = 1; m_freeOffset = 0; m_freeStorage = 0; resetBins(); std::memset(&nodeAt(0), 0, sizeof(Node)); std::construct_at(&nodeAt(0)); freeNodeAt(0) = 0; insertNodeIntoBin(m_size, 0); // Post-conditions: m_freeOffset == 1, m_freeStorage == m_size, // root bin holds node 0; chunks_[0] remains allocated so the next // 65,535 slot growths require zero heap allocation.
- Because
chunks_[0]stays mapped while logicalm_current_capacityresets to1, shrinking touches only ~1 KiB insidem_mutex(avoiding a 2–4 MiB lock-held memset burst), subsequent allocations lazily re-initialize one 32 B slot at a time without allocating a chunk until slot65,536, andserialize_to()on an empty drained allocator writes only 32 B. OffsetAllocator::freeAllocation()unlocksm_mutexbefore destroyingretired_headiteratively (while (retired_head) { auto next = std::move(retired_head->next_retired); retired_head = std::move(next); }), preventing stack overflow on long chains and keeping all deallocation syscalls outside the lock.
- Keeps
- Why not middle-chunk reclamation: Both
m_freeNodesand bin doubly-linked lists store rawNodeIndexvalues; reclaiming arbitrary middle chunks would require per-chunk live counts and freelist partitioning on everyallocate()/free(). Whole-segment-empty shrink handles drained/evicted segments with a single predicted-not-taken branch (m_freeStorage == m_size) and zero hot-path overhead.
- Because
2.3 Wire-Format Compatibility & Safe Deserialization
Keeping sizeof(Node) == 28 with zeroed trailing padding allows serialize_to and deserialize_from (mooncake-store/include/offset_allocator/offset_allocator.h) to remain 100% byte-for-byte compatible with existing checkpoints (kOffsetAllocatorPersistVersion unchanged):
SerializeWriter/serialize_to():- Reject if
m_current_capacity == 0and verify allceil(m_current_capacity / kChunkSize)chunks exist. - Stream in two separate passes matching the legacy contiguous layout: Pass 1 writes
count = std::min(kChunkSize, m_current_capacity - chunk_base)Nodeelements per chunk in ascending chunk order (m_current_capacity * 28bytes total); Pass 2 writescountNodeIndexelements per chunk in ascending chunk order (m_current_capacity * 4bytes total).
- Reject if
SerializerReader/deserialize_from():- Add
size_t remaining() const { return size_ - offset_; }toSerializerReader(mooncake-store/include/serializer.h, documented as an optional deserializer capability). - In
__Allocator::__Allocator(T& serializer):- Reject
m_size == 0 || m_max_capacity == 0 || m_current_capacity == 0 || m_current_capacity > m_max_capacity || m_freeOffset > m_current_capacity. - Raise the explicit
m_max_capacitysanity cap from1u << 24(16.7 Mi) to1u << 26(64 Mi) so DRAM segments can be serialized/deserialized while still guarding against corrupt4Gheaders. - Verify
static_cast<uint64_t>(m_current_capacity) * (sizeof(Node) + sizeof(NodeIndex)) <= serializer.remaining()before allocating any chunk, preventing corrupt-checkpoint OOM DoS. - Allocate chunks for
m_current_capacityand read in two matching passes (Pass 1: allNodechunks; Pass 2: allNodeIndexchunks) with partial-last-chunk handling, preserving non-chunk-multiple capacities (1,2,1000,65537) verbatim.
- Reject
- Explicitly rethrow
std::bad_alloc(catch (const std::bad_alloc&) { throw; }) in all three layers—__Allocator::__Allocator(T&),OffsetAllocator::OffsetAllocator(T&), andmooncake::deserialize_from<T>(serializer.h)—so transient OOM reachesstorage_backend.cpp'scatch (const std::bad_alloc&)askTransientErrorinstead ofkCorrupt.
- Add
2.4 Alternatives Considered
| Option | Committed_AS (overcommit=2) |
VmSize / RLIMIT_AS |
vm.max_map_count |
Hot-Path & Growth Cost | Wire-Format Compat | Verdict |
|---|---|---|---|---|---|---|
A. Current std::vector::reserve(max) |
200 GiB (100 segs) | 200 GiB | Low | Contiguous array | Baseline | Fails overcommit_memory=2; blocks #5272 |
B. Simply delete reserve() on std::vector |
200 MiB | 200 MiB | Low | Severe: 32Mi → 64Mi doubling copies 1 GiB inside m_mutex (hundreds of ms stall + 3 GiB spike) |
Yes | Unacceptable lock stall & memory spike |
C. std::deque<Node> |
200 MiB | 200 MiB | Low | On libstdc++, 512 B blocks hold 18 Nodes → 3.7M allocations + ~30 MiB map at 64 Mi nodes |
Yes (chunked) | Excessive block fragmentation |
D. mmap(PROT_NONE) + on-demand mprotect(RW) |
200 MiB | 200 GiB (unchanged) | Lowest | 0% hot-path overhead; POSIX-only; cannot grow past initial virtual span | Yes | Leaves VmSize/RLIMIT_AS at 200 GiB |
E. 4K (128 KiB) raw mmap chunks |
200 MiB | 200 MiB | High risk (16,384 VMAs/full seg; 4 full segs exceed 65,530) | 128 KiB directory (L2); 16× more mmap_lock & TLB shootdowns |
Yes | Risky at 100-segment cluster scale |
F. 64K (2 MiB) unified chunks via ::operator new + lazy per-slot init |
200 MiB (-99.9%) | 200 MiB (-99.9%) | Low (1,024 chunks max/seg; jemalloc-friendly) | 8 KiB directory (L1d); zero copy; portable C++; noexcept hysteresis shrink |
100% byte-for-byte compatible | Selected |
3. Compatibility, Performance & Verification Plan
- Hot-path overhead: Each
nodeAt()andfreeNodeAt()adds one load from the8 KiBL1d-residentchunks_directory plus bit-shift/mask (idx >> 16,idx & 0xFFFF). Actual P50/P99 latency delta on bothallocate()andfree()will be benchmarked withallocator_benchandoffset_allocator_concurrency_bench(Release build, Linux x86_64) before merge. - HA Standby Recovery (
ImportOffsetBufferAllocator) & CXL:ImportOffsetBufferAllocatorreplays live allocations viaallocate()and transparently drops the 2 GiB upfrontmmapper restored segment during failover.- CXL uses
CachelibBufferAllocatorand is unaffected.
- Verification & Acceptance Criteria (Single Focused PR):
- Memory & overcommit: Mounting 100 × 64 GiB segments drops
VmSize/Committed_ASfrom 200 GiB → 200 MiB (-99.9%) and succeeds under strictRLIMIT_AS/vm.overcommit_memory=2. - Small allocators: 16 MiB segment (
init = 4096) stays at128 KiBVmRSS; 4 KiB DFS shard (max = 4) stays at128 Bheap. - Hysteresis shrink: Fill past
1 + kShrinkHysteresisChunkschunks then drain: deterministically assertchunks_.size() == 1,m_current_capacity == 1, and zero allocations insidefree()(via allocation-failure injection andnoexceptchecks). Separately verify OS memory return (VmSize/VmRSS) immediately under default glibcM_MMAP_THRESHOLD, and afterdirty_decay_msexpiry or explicitmallctl("arena.all.purge")under jemalloc. - Serialization & OOM recovery: Update
offset_allocator_test.cppdirectm_nodes.data()/m_freeNodes.data()checks (lines 387–410, 466–476) to accessor helpers; add golden byte-for-byte round-trip tests (including partial last chunks1,2,1000,65537),m_current_capacity == 0rejection, andbad_allocpropagation throughmooncake::deserialize_from<OffsetAllocator>→kTransientError; pass under ASan/UBSan. - Benchmarks: Report Release A/B results on
allocator_benchandoffset_allocator_concurrency_benchcovering P50, P99, and P99.9 latency (including growth across chunk boundaries and post-shrink regrowth).
- Memory & overcommit: Mounting 100 × 64 GiB segments drops
4. Open Questions for Reviewers
- Shrink hysteresis threshold (
kShrinkHysteresisChunks): Defaulting to2excess chunks (4 MiBslack above chunk 0) prevents boundary thrashing while still reclaiming >99% of metadata after large bursts drain. Does2(or4) look right? - Follow-up scope for [Usage]: Fixed OffsetAllocator node limits can underutilize large SSD caches with small KV pages #5272: Keeping this RFC strictly behavior-preserving lets the paged storage layer land quickly with minimal risk. Follow-up PRs can then independently address
OffsetAllocatorStorageBackend's512 MiB / 56vs.32 B/nodebudget alignment,RemoveAll()budget preservation, and configurable node budgets beyond64 Mi.
Before submitting a new issue...
- Make sure you already searched for relevant issues and read the documentation
Activity
github-actions commentedon Nov 27, 2026
Thanks for opening this issue, @CAICAIIs!
39020005A maintainer will triage this when possible. To help us respond faster, please include:
Useful links: Documentation · Contributing guide
yibol9768-alt commentedon Nov 28, 2026
Hi @CAICAIIs and maintainers — I checked
offset_allocator.h/.cpp,serializer.h, andstorage_backend.cpp(L5568–5574) and confirmed the upfrontm_nodes.reserve(m_max_capacity)/m_freeNodes.reserve(m_max_capacity)reservation (2 GiB per 64 GiB segment) and thestd::bad_allocswallowing across__Allocator,OffsetAllocator, anddeserialize_from.I am implementing this RFC locally with:
ChunkControltable via::operator new+ lazy per-slotmemset/construct_atinitialization, with check-bin-before-grow and strongstd::bad_allocexception safety.noexcepthysteresis empty-segment shrink (kShrinkHysteresisChunks = 2, detaching tail chunks to an intrusive list insidem_mutexand freeing iteratively outside the lock).SerializerReader::remaining()pre-allocation validation,1u << 26cap, andstd::bad_allocrethrow across all 3 deserialization layers.Please let me know if anyone is already working on this or prefers a different default for
kShrinkHysteresisChunksbefore I open a PR![Store] Replace OffsetAllocator contiguous vector reservation with pa…