Skip to content

[RFC]: [Store] Replace OffsetAllocator Contiguous Vector Reservation with Paged Node Tables #5923

Backlog

Description

@CAICAIIs

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:

  1. Unified 2-Level Paged Chunk Table (64K slots = 2 MiB per full chunk):
    • Replace contiguous m_nodes and m_freeNodes std::vectors (which call reserve(m_max_capacity)) with a dynamically growing directory of 2 MiB chunks (65,536 slots = 1.75 MiB Node + 256 KiB NodeIndex), allocated via standard ::operator new and lazily initialized one slot at a time as m_current_capacity grows.
    • 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, while 2 MiB chunks keep VMA counts low (safe under Linux's default vm.max_map_count = 65,530), keep the max 64 Mi directory at 8 KiB (L1d-resident), and work seamlessly with both jemalloc and glibc.
  2. Hysteresis noexcept Empty-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 releasing m_mutex.
  3. 100% Wire-Compatible Serialization & Safe Deserialization:
    • Keep sizeof(Node) == 28 and stream Nodes then NodeIndexes in two passes so existing persisted checkpoints remain byte-for-byte compatible (kOffsetAllocatorPersistVersion unchanged).
    • Add SerializerReader::remaining() pre-allocation validation, reject m_current_capacity == 0, raise the hardcoded 1 << 24 m_max_capacity sanity cap to 1 << 26 (covering 64 Mi DRAM segments), and rethrow std::bad_alloc so transient OOM is not misclassified as checkpoint corruption (kCorrupt).

Non-goals:

  • Does not change OffsetAllocator SmallFloat binning, allocation/free return semantics, StorageReport semantics, or public OffsetAllocator / AllocatedBuffer APIs.
  • Does not change OffsetAllocatorStorageBackend key 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): default init = 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:

  1. vm.overcommit_memory=2 mount failures: Mounting 100 × 64 GiB segments fails with ENOMEM / std::bad_alloc if CommitLimit cannot absorb 200 GiB of unused metadata reservation.
  2. No reclamation after drain/eviction: Neither free() nor reset() shrinks the vectors; memory is returned only on segment unmount (~__Allocator()).
  3. Blocks [Usage]: Fixed OffsetAllocator node limits can underutilize large SSD caches with small KV pages #5272: Raising max_capacity for small-object workloads multiplies upfront Committed_AS across every segment/shard even when larger objects are stored.
  4. Deserialization pitfalls: __Allocator deserialization currently calls reserve(m_max_capacity), rejects m_max_capacity > 2^24 (already below DRAM's 64 Mi), allows m_current_capacity == 0, and swallows std::bad_alloc into std::runtime_error / nullptr (serializer.h), causing the SSD backend's catch (const std::bad_alloc&) to be unreachable and misclassifying transient OOM as kCorrupt.

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,536 slots) allocates a single 2 MiB raw block (65,536 × 28 B = 1.75 MiB for Node[], followed immediately by 65,536 × 4 B = 256 KiB for NodeIndex[], both 4-byte aligned) using standard ::operator new(bytes) / ::operator delete(ptr, bytes).
    • Each chunk is owned by a small ChunkControl struct (std::unique_ptr<ChunkControl> next_retired; void* mem; size_t bytes; uint32_t slots;). ChunkControl is allocated before ::operator new(bytes) inside an RAII guard so std::bad_alloc never leaks memory or leaves chunks_ / m_current_capacity partially updated.
    • Why ::operator new + lazy per-slot initialization instead of new Node[65536]():
      • Node has default member initializers (NSDMI), so new Node[65536]() (and even C++20 make_unique_for_overwrite<Node[]>(65536)) would touch all 1.75 MiB immediately on chunk creation—causing RSS regressions for small segments (init = 4096) and a multi-microsecond fault burst inside m_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 at 128 KiB). Whenever m_current_capacity exposes slot i, we explicitly initialize both arrays for slot i: std::memset(&nodeAt(i), 0, sizeof(Node)); std::construct_at(&nodeAt(i)); freeNodeAt(i) = i; (matching legacy reset() and m_freeNodes.push_back(m_current_capacity)). This guarantees zero uninitialized bytes anywhere in [0, m_current_capacity) (deterministic checkpoints, zero heap leakage, including Node's 3-byte trailing padding) and safe visit_used_nodes() scans.
      • __Allocator remains move-only (explicitly declaring = delete copy constructor/assignment and moving chunks_ in O(1) in __Allocator(__Allocator&&)).
      • Using standard ::operator new / ::operator delete is 100% portable across Linux and macOS and cooperates cleanly with both jemalloc (which manages 2 MiB extents without inflating Linux VMA counts and purges dirty pages via madvise(MADV_DONTNEED)) and glibc (2 MiB exceeds glibc's 128 KiB mmap_threshold, while keeping VMA count 16× lower than 128 KiB chunks—well below Linux's default vm.max_map_count = 65,530).
  • Directory footprint:
    • At init = 64K (1 chunk): 8 B.
    • At max = 64 Mi (1,024 chunks): 8 KiB total (fits in L1d cache).
  • 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
Loading

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
Loading

2.2 Growth, Hysteresis noexcept Shrink, and Lock Boundaries

  1. Decoupled logical capacity & check-bin-before-grow:
    • Logical m_current_capacity continues to increment by +1 only when a new node slot is actually required (preserving exact m_current_capacity semantics for existing tests such as SerializationOneElementAllocator and keeping checkpoints minimal).
    • In allocate(), find a fitting bin and confirm a split remainder is needed before growing m_current_capacity, so failing allocations never allocate a new chunk.
    • A new 2 MiB chunk is allocated only when m_current_capacity crosses a 65,536-slot boundary (reducing chunk-allocation frequency and kernel mmap_lock contention by 16× compared to 4K chunks).
  2. Provably zero-allocation (noexcept) empty-segment shrink with hysteresis:
    • Because OffsetAllocationHandle::~OffsetAllocationHandle() and move-assignment are noexcept, free() must never allocate memory.
    • Hysteresis: Trigger shrink only when m_freeStorage == m_size (segment completely empty) and chunks_.size() > 1 + kShrinkHysteresisChunks (e.g., kShrinkHysteresisChunks = 2, i.e., > 4 MiB beyond chunk 0), avoiding mmap/munmap thrashing and TLB shootdown storms when a segment oscillates between empty and lightly populated.
    • __Allocator::shrinkToInitial(std::unique_ptr<ChunkControl>& retired_head) noexcept (O(chunks) inside m_mutex, ~1 µs worst-case):
      • Keeps chunks_[0] in place (zero allocation), moves tail chunks chunks_[1..] (at most 1,023 pointer moves at 64 Mi nodes) onto the intrusive retired_head singly-linked list (no vector::push_back), shrinks chunks_ size to 1, and resets logical m_current_capacity = 1 so only slot 0 and the 256 bin heads (~1 KiB) are rewritten inside m_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 logical m_current_capacity resets to 1, shrinking touches only ~1 KiB inside m_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 slot 65,536, and serialize_to() on an empty drained allocator writes only 32 B.
      • OffsetAllocator::freeAllocation() unlocks m_mutex before destroying retired_head iteratively (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.
    • Why not middle-chunk reclamation: Both m_freeNodes and bin doubly-linked lists store raw NodeIndex values; reclaiming arbitrary middle chunks would require per-chunk live counts and freelist partitioning on every allocate()/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.

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 == 0 and verify all ceil(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) Node elements per chunk in ascending chunk order (m_current_capacity * 28 bytes total); Pass 2 writes count NodeIndex elements per chunk in ascending chunk order (m_current_capacity * 4 bytes total).
  • SerializerReader / deserialize_from():
    • Add size_t remaining() const { return size_ - offset_; } to SerializerReader (mooncake-store/include/serializer.h, documented as an optional deserializer capability).
    • In __Allocator::__Allocator(T& serializer):
      1. Reject m_size == 0 || m_max_capacity == 0 || m_current_capacity == 0 || m_current_capacity > m_max_capacity || m_freeOffset > m_current_capacity.
      2. Raise the explicit m_max_capacity sanity cap from 1u << 24 (16.7 Mi) to 1u << 26 (64 Mi) so DRAM segments can be serialized/deserialized while still guarding against corrupt 4G headers.
      3. Verify static_cast<uint64_t>(m_current_capacity) * (sizeof(Node) + sizeof(NodeIndex)) <= serializer.remaining() before allocating any chunk, preventing corrupt-checkpoint OOM DoS.
      4. Allocate chunks for m_current_capacity and read in two matching passes (Pass 1: all Node chunks; Pass 2: all NodeIndex chunks) with partial-last-chunk handling, preserving non-chunk-multiple capacities (1, 2, 1000, 65537) verbatim.
    • Explicitly rethrow std::bad_alloc (catch (const std::bad_alloc&) { throw; }) in all three layers—__Allocator::__Allocator(T&), OffsetAllocator::OffsetAllocator(T&), and mooncake::deserialize_from<T> (serializer.h)—so transient OOM reaches storage_backend.cpp's catch (const std::bad_alloc&) as kTransientError instead of kCorrupt.

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() and freeNodeAt() adds one load from the 8 KiB L1d-resident chunks_ directory plus bit-shift/mask (idx >> 16, idx & 0xFFFF). Actual P50/P99 latency delta on both allocate() and free() will be benchmarked with allocator_bench and offset_allocator_concurrency_bench (Release build, Linux x86_64) before merge.
  • HA Standby Recovery (ImportOffsetBufferAllocator) & CXL:
    • ImportOffsetBufferAllocator replays live allocations via allocate() and transparently drops the 2 GiB upfront mmap per restored segment during failover.
    • CXL uses CachelibBufferAllocator and is unaffected.
  • Verification & Acceptance Criteria (Single Focused PR):
    1. Memory & overcommit: Mounting 100 × 64 GiB segments drops VmSize / Committed_AS from 200 GiB → 200 MiB (-99.9%) and succeeds under strict RLIMIT_AS / vm.overcommit_memory=2.
    2. Small allocators: 16 MiB segment (init = 4096) stays at 128 KiB VmRSS; 4 KiB DFS shard (max = 4) stays at 128 B heap.
    3. Hysteresis shrink: Fill past 1 + kShrinkHysteresisChunks chunks then drain: deterministically assert chunks_.size() == 1, m_current_capacity == 1, and zero allocations inside free() (via allocation-failure injection and noexcept checks). Separately verify OS memory return (VmSize / VmRSS) immediately under default glibc M_MMAP_THRESHOLD, and after dirty_decay_ms expiry or explicit mallctl("arena.all.purge") under jemalloc.
    4. Serialization & OOM recovery: Update offset_allocator_test.cpp direct m_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 chunks 1, 2, 1000, 65537), m_current_capacity == 0 rejection, and bad_alloc propagation through mooncake::deserialize_from<OffsetAllocator> → kTransientError; pass under ASan/UBSan.
    5. Benchmarks: Report Release A/B results on allocator_bench and offset_allocator_concurrency_bench covering P50, P99, and P99.9 latency (including growth across chunk boundaries and post-shrink regrowth).

4. Open Questions for Reviewers

  1. Shrink hysteresis threshold (kShrinkHysteresisChunks): Defaulting to 2 excess chunks (4 MiB slack above chunk 0) prevents boundary thrashing while still reclaiming >99% of metadata after large bursts drain. Does 2 (or 4) look right?
  2. 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's 512 MiB / 56 vs. 32 B/node budget alignment, RemoveAll() budget preservation, and configurable node budgets beyond 64 Mi.

Before submitting a new issue...

  • Make sure you already searched for relevant issues and read the documentation

Activity

  1. github-actions commented on Nov 27, 2026

    @github-actions

    Thanks for opening this issue, @CAICAIIs!

    Field Value
    Issue #5923
    GitHub user ID 39020005
    Reporter @CAICAIIs

    A maintainer will triage this when possible. To help us respond faster, please include:

    • Mooncake version or commit SHA
    • Environment (OS, CUDA/driver, RDMA stack if relevant)
    • Steps to reproduce and expected vs. actual behavior

    Useful links: Documentation · Contributing guide

    This message was posted automatically by the issue bot.

  2. yibol9768-alt commented on Nov 28, 2026

    @yibol9768-alt

    Hi @CAICAIIs and maintainers — I checked offset_allocator.h/.cpp, serializer.h, and storage_backend.cpp (L5568–5574) and confirmed the upfront m_nodes.reserve(m_max_capacity) / m_freeNodes.reserve(m_max_capacity) reservation (2 GiB per 64 GiB segment) and the std::bad_alloc swallowing across __Allocator, OffsetAllocator, and deserialize_from.

    I am implementing this RFC locally with:

    1. Unified 2-level 64K-slot (2 MiB) paged ChunkControl table via ::operator new + lazy per-slot memset/construct_at initialization, with check-bin-before-grow and strong std::bad_alloc exception safety.
    2. noexcept hysteresis empty-segment shrink (kShrinkHysteresisChunks = 2, detaching tail chunks to an intrusive list inside m_mutex and freeing iteratively outside the lock).
    3. Wire-compatible two-pass serialization, SerializerReader::remaining() pre-allocation validation, 1u << 26 cap, and std::bad_alloc rethrow across all 3 deserialization layers.
    4. Full unit + randomized fuzz + OOM injection + golden byte-for-byte cross-compatibility tests under C++20 ASan/UBSan, plus Release A/B memory and latency benchmarks.

    Please let me know if anyone is already working on this or prefers a different default for kShrinkHysteresisChunks before I open a PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions