Skip to content

[Store] Optionally pack SSD offload buckets in enqueue order - #5817

Draft
zhewenl wants to merge 2 commits into
kvcache-ai:mainfrom
zhewenl:zhewen/upstream-ordered-offload-buckets
Draft

zhewenl wants to merge 2 commits into
kvcache-ai:mainfrom
zhewenl:zhewen/upstream-ordered-offload-buckets

Conversation

@zhewenl

@zhewenl zhewenl commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Draft: data pending. End-to-end before/after numbers with this exact patch are still being collected (see "Data" below). Please treat this PR as a draft until they are added.

Description

Problem

Which objects share an SSD bucket is decided by hash order, twice:

  1. The master's per-client offload mailbox (LocalSsdTaskMailbox::pending_offloads_, an unordered_map) hands the store its tasks in hash order on each OffloadObjectHeartbeat.
  2. FileStorage::OffloadObjects copies them into another unordered_map, and GroupOffloadingKeysByBucket packs buckets by walking that map.

So a bucket holds a random subset of what was queued for the store between two heartbeats. Objects written together, such as the KV blocks of one prompt prefix, are spread over many buckets. Reading a prefix back opens many bucket files, and with lru bucket eviction every read refreshes the recency of all the unrelated objects that happen to share those buckets.

Because bucket LRU is per bucket, this also lets cold objects survive (they ride on hot neighbours) and lets a cold-bucket eviction take hot or mid-prefix blocks with it; since prefix matching stops at the first miss, one lost middle block invalidates the rest of the prefix.

Design

Two settings, both off by default. Each follows the existing convention of its side: a master flag, and a store environment variable read by FileStorageConfig::FromEnvironment.

  • Master: --offload_ordered_buckets (offload_ordered_buckets in the master config file; takes effect with --enable_offload=true). It is a MasterConfig field next to the other offload flags and reaches MasterServiceConfig through the supervisor and wrapped configs. MasterService passes it to LocalSsdManager, which hands it to every client's mailbox.
    • EnqueueOffload inserts into the map exactly as before. With the setting on, it also appends the task's scoped key to an order list.
    • SetOffloadingAndTakePending first computes the delivery order as a list of pointers to the map's entries: enqueue order when on, the map's iteration order when off. It then moves the tasks out in one loop over that list.
    • A task removed before the heartbeat (RemoveOffload, CancelOffloadsIfAllPending) is skipped, and a key removed and queued again goes at its last position.
    • Remove/enqueue churn leaves stale entries in the order list. Once the list outgrows 2 * offloading_queue_limit + 64 entries, it is compacted to one entry per queued key. Its memory stays bounded and the cost is amortized O(1) per enqueue. The threshold saturates instead of overflowing for very large limits.
  • Store: MOONCAKE_OFFLOAD_ORDERED_BUCKETS, read into FileStorageConfig::ordered_buckets. OffloadObjects passes the delivery order to BucketStorageBackend::AllocateOffloadingBuckets (new optional key_order argument), and GroupOffloadingKeysByBucket packs keys in that order. Keys the order does not list come after it, in the map's iteration order. Order entries that are not objects are ignored.
  • Tail across heartbeats. The ungrouped pool is unchanged. With MOONCAKE_OFFLOAD_FLUSH_PARTIAL_BUCKETS=0 (default), the partial last bucket of one heartbeat is deferred as before and opens the next heartbeat's first bucket, ahead of the new keys. Objects queued on either side of a heartbeat boundary still share a bucket. A carried key that the next heartbeat delivers again (re-put while deferred) loses its pooled copy as before and takes its new place in the order. With MOONCAKE_OFFLOAD_FLUSH_PARTIAL_BUCKETS=1 ([Store] Add opt-in same-cycle flush for partial SSD offload buckets #4673), the tail is flushed in order in the same cycle. A tail replayed without new tasks ([Store] Flush deferred bucket tails without new offload tasks #5287) is written as one bucket, as before.
  • Membership only. The settings decide which objects share a bucket. The layout of the objects inside a bucket file still follows the existing grouping: FileStorage hands each bucket to BatchOffload as an unordered_map, and BuildBucket writes it in that map's order.

Read paths, the bucket file format and RPCs are unchanged.

Settings

Setting Where Default Effect
--offload_ordered_buckets (offload_ordered_buckets in the config file) master false Deliver each client's offload tasks in enqueue order
MOONCAKE_OFFLOAD_ORDERED_BUCKETS every real client with SSD offload 0 Pack buckets in delivery order

Each side logs one line at startup when its setting is on, naming the setting the other side needs. With only one side on, nothing breaks, but buckets stay hash-ordered. Both are documented in the SSD offload deployment guide: the flag in the "Master Offload Parameters" table, the variable in the bucket backend table, and a short "Ordered bucket packing" section.

Compatibility and cost

  • Off (default). The mailbox delivers the same tasks in the same order as before. The take now goes through a list of entry pointers (one pointer per queued task, per heartbeat) instead of iterating the map directly. The grouping walks the map exactly as before and builds no order list, and FileStorage builds no key list. Buckets are unchanged; BucketStorageBackend_UnorderedPackingKeepsHashOrder and UnorderedOffloadsDeliverTheSameSet pin this.
  • Mixed fleets and rolling restarts are fine: the settings only change which keys go into which new bucket. Buckets written either way stay readable.
  • Cost when on.
    • Master: one copy of the scoped key (tenant prefix + key) per accepted enqueue, kept until the next heartbeat; at most about 2x the queue limit before compaction. At each heartbeat the take compacts the list (a hash set of entry pointers and a vector of the queued keys) and builds the pointer list.
    • Store, per OffloadObjects call: a vector with a copy of each delivered storage key. In the grouping, a vector of entry pointers and a hash set of entry pointers, both sized to the call's objects. These are small next to the call's existing per-key maps (storage_object_sizes, task_by_storage_key).

Interaction with other offload PRs

Not included

  • Caller-order read chunking (MC_OFFLOAD_READ_KEY_ORDER in our fork) is not part of this PR. It orders the keys of a multi-key LOCAL_DISK read before splitting them into bounded chunks. Upstream sends all keys for one owner in a single batch_get_offload_object RPC, and the owner already groups that request by bucket (ReadBucketValues). Without read chunking, key order on the read side does not change how many buckets are read, so there is nothing meaningful to port on its own.

Suggested Merge Priority

  • P0 — Urgent: Critical security vulnerability, data loss/corruption, or widespread production outage requiring immediate action
  • P1 — High: Significant correctness or stability issue in existing functionality, or a regression blocking users without a practical workaround
  • P2 — Normal: Routine bug fix, validated performance/compatibility improvement, or new feature for a confirmed use case
  • P3 — Low: Experimental feature, optional enhancement, refactoring, or cleanup with no urgent user impact

Module

  • Transfer Engine (mooncake-transfer-engine)
  • Mooncake Store (mooncake-store)
  • Mooncake Conductor (mooncake-conductor)
  • Reshard (mooncake-reshard)
  • Mooncake EP (mooncake-ep)
  • Mooncake PG (mooncake-pg)
  • Integration (mooncake-integration)
  • P2P Store (mooncake-p2p-store)
  • Python Wheel (mooncake-wheel)
  • Common (mooncake-common)
  • Mooncake RL (mooncake-rl)
  • CI/CD
  • Docs
  • Other

Type of Change

  • Bug fix
  • New feature
  • Refactor
  • Breaking change
  • Documentation update
  • Performance improvement
  • Other

How Has This Been Tested?

New tests:

Test What it proves
local_ssd_test OrderedOffloadsAreDeliveredInEnqueueOrder Mailbox delivers in enqueue order across tenants. Removed keys are skipped, a re-enqueued key goes last, duplicates are still rejected, and each take starts a fresh order
local_ssd_test OrderedOffloadsSurviveChurnCompaction Heavy remove/enqueue churn compacts the order list without losing, duplicating or reordering queued tasks
local_ssd_test OrderedOffloadsApplyToEveryClient LocalSsdManager hands the setting to every client's mailbox, and a cancelled mirror leaves no gap
local_ssd_test UnorderedOffloadsDeliverTheSameSet Off: the same tasks as before
storage_backend_test BucketStorageBackend_OrderedPackingFollowsKeyOrder Buckets are consecutive runs of the key order. Unknown and repeated order entries are ignored, and unlisted keys come last
storage_backend_test BucketStorageBackend_OrderedPackingTruncatesBySize A bucket closes when the next key would exceed bucket_size_limit or when it is exactly full, and that key opens the next bucket. An object over the limit is skipped without breaking the order
storage_backend_test BucketStorageBackend_OrderedPackingSkipsPersistedKeys Keys already persisted on the backend are skipped; the rest keep their order
storage_backend_test BucketStorageBackend_OrderedPackingCarriesTailAcrossCalls A deferred tail opens the next call's first bucket ahead of the new keys, which keep their order
storage_backend_test BucketStorageBackend_OrderedPackingRedrainedCarriedKey A carried key that the next heartbeat delivers again (its pooled copy dropped, as FileStorage does) takes its new place in the order, after the remaining carried key
storage_backend_test BucketStorageBackend_UnorderedPackingKeepsHashOrder Off: buckets are consecutive runs of the map's iteration order, i.e. unchanged
master_service_ssd_test OrderedOffloadsReachTheStoreInPutOrder OffloadObjectHeartbeat returns tasks in PutEnd order with offload_ordered_buckets; off, the same set
master_service_config_test OffloadOrderedBucketsPropagates The flag defaults to off and reaches MasterServiceConfig from MasterConfig, directly and through the supervisor config
file_storage_test OrderedBucketsPackPutsInOrderAcrossHeartbeats End to end (embedded master with the flag, real client, FileStorage with the variable): two heartbeats of 6 puts into 4-key buckets give buckets {0..3}, {4..7}, {8..11} of the put order, and every key gets a LOCAL_DISK replica
file_storage_test UnorderedBucketsStillOffloadEveryPut Same flow, both off: every put lands exactly once
file_storage_config_test (extended) MOONCAKE_OFFLOAD_ORDERED_BUCKETS: default off, 1 on, an invalid value warns and stays off

Revert check: with the grouping forced to ignore key_order and the mailbox take forced onto its unordered branch, all 10 ordered-mode tests above fail (3 in local_ssd_test, 5 in storage_backend_test, 1 in master_service_ssd_test, 1 in file_storage_test), and every off-mode test still passes.

Test commands:

cmake -S . -B build -G Ninja -DUSE_CUDA=OFF -DWITH_STORE=ON -DBUILD_UNIT_TESTS=ON \
  -DUSE_ETCD=OFF -DSTORE_USE_ETCD=OFF -DWITH_STORE_RUST=OFF -DWITH_P2P_STORE=OFF
ninja -C build
cd build/mooncake-store/tests
./local_ssd_test && ./storage_backend_test --gtest_filter='-*OffsetAllocatorReadPath*' \
  && ./file_storage_test && ./file_storage_config_test && ./master_service_ssd_test \
  && ./master_service_config_test
cd .. && ctest --output-on-failure

Test results:

  • Unit tests pass
  • Integration tests pass (if applicable)
  • Manual testing done (describe below)

Results on an aarch64 host (Ubuntu 24.04, GCC 13, kernel with 64 KiB pages, GPUs present), USE_CUDA=OFF:

Suite Result
local_ssd_test 13/13 passed
storage_backend_test 147/159 passed; the 12 OffsetAllocatorReadPath_* tests were excluded (see below)
file_storage_test 69 passed, 1 skipped (UringStagingBufferUnpinnedOnDestruction, environment)
file_storage_config_test 14/14 passed
master_service_ssd_test 8/8 passed
master_service_config_test 23/23 passed
full mooncake-store ctest (--parallel 8) 234/237 passed. The 3 failures are in code this PR does not touch (below)

The ctest failures:

  • storage_backend_test (environment): the OffsetAllocatorReadPath_* tests allocate guard pages with mprotect at 4 KiB granularity. On a 64 KiB-page kernel that returns EINVAL, so the helper throws std::bad_alloc: 10 of them fail and _ConcurrentEviction_Uring aborts the binary. With those 12 filtered out, the other 147 tests pass.
  • transfer_task_test BatchGetOffloadObjectCopiesPinnedHostToGpu (environment): the test is built because CMake finds the CUDA toolkit, and it runs because a GPU is present. The store itself is built with USE_CUDA=OFF, so PinnedBufferPool::AllocatePinned returns no pinned buffer.
  • pybind_client_test GetBufferRemoteReaderHealsOwnersDanglingLocalDiskReplica (flaky under load): it failed once in the parallel run, at its sanity read on the fixed ports 17813/17814 while other builds and tests ran on the host, and passed 3/3 when rerun alone. It passed in the same ctest on the previous revision of this branch and on the other branches tested alongside.

./scripts/code_format.sh --check against main (clang-format 20.1.8) and pre-commit run --files <changed files> pass. The docs build with Sphinx without warnings, and the new cross-references resolve.

Data

End-to-end before/after numbers (bucket reads per prefix read, keys used per bucket read, SSD read throughput) on a real deployment with this exact patch are still being collected. They will be added here; until then this PR is a draft.

Checklist

  • Every commit I contribute includes my Signed-off-by trailer certifying the DCO
  • I have performed a self-review of my own code
  • I have formatted my code using ./scripts/code_format.sh
  • I have run pre-commit on the files changed in this PR and all hooks pass
  • I have updated the documentation (if applicable)
  • I have added tests to prove my changes are effective
  • For changes >500 LOC: I have filed an RFC issue (N/A: +238/-33 lines outside tests and docs)

AI Assistance Disclosure

  • No AI tools were used
  • AI tools were used (specify below)

Claude Code (Anthropic) was used to port the change from our fork onto current main (adapting it to #5287 and to the existing master-flag and config-from-environment conventions), write the unit and end-to-end tests, run the test suites, and draft this description. The submitter is responsible for the change.

🤖 Generated with Claude Code

Zhewen Li and others added 2 commits November 25, 2026 03:34
Bucket membership is hash-ordered twice. The master's offload mailbox
(LocalSsdTaskMailbox::pending_offloads_, an unordered_map) hands each
store its tasks in hash order, and FileStorage::OffloadObjects copies
them into another unordered_map that GroupOffloadingKeysByBucket packs
in hash order. A bucket is therefore a random subset of what was queued
for the store between two heartbeats: the blocks of one prefix spread
over many buckets, a prefix read opens many bucket files, and with LRU
bucket eviction one read refreshes many unrelated keys.

Two settings, both off by default, keep the order:

- Master: --offload_ordered_buckets (offload_ordered_buckets in the
  config file; takes effect with enable_offload). MasterService passes
  it to LocalSsdManager, which hands it to every client's mailbox. The
  mailbox records the order of accepted offload enqueues.
  SetOffloadingAndTakePending first computes the delivery order
  (enqueue order, or the map's iteration order when off) and then moves
  the tasks out in one loop. A key removed before the take is skipped;
  a key removed and enqueued again goes at its last position.
  Remove/enqueue churn between two takes compacts the order list to one
  entry per queued key once it outgrows 2x the queue limit; the
  threshold saturates for huge limits.
- Store: MOONCAKE_OFFLOAD_ORDERED_BUCKETS (FileStorageConfig::
  ordered_buckets). OffloadObjects passes the delivery order to
  AllocateOffloadingBuckets, which packs keys in that order. The
  ungrouped tail deferred by one call still opens the next call's first
  bucket, ahead of the new keys, so keys queued on either side of a
  heartbeat share a bucket. With MOONCAKE_OFFLOAD_FLUSH_PARTIAL_BUCKETS=1
  the tail is flushed in order in the same call; a replayed tail (kvcache-ai#5287)
  is unchanged. Only bucket membership follows the order: the layout
  inside a bucket file does not change.

Off, the mailbox delivers the same tasks in the same order as before
(it collects pointers to them first), and the grouping walks the map as
before without building an order list, so buckets are unchanged. When a
setting is on, that side logs one line at startup that asks for the
other one; with one side only, buckets stay hash-ordered. No on-disk
format or RPC change.

Tests:
- local_ssd_test: enqueue order across removals, re-enqueue and
  duplicates; churn compaction; the manager applies the setting to every
  client and a cancelled mirror leaves no gap; off delivers the same
  set.
- storage_backend_test: packing follows the key order (unknown and
  repeated entries ignored, unlisted keys last); a bucket closes on the
  size limit and oversized objects are skipped in order; persisted keys
  are skipped; a deferred tail opens the next call's first bucket ahead
  of its keys; a carried key delivered again takes its new place;
  without an order the buckets are consecutive runs of the map's
  iteration order.
- master_service_ssd_test: OffloadObjectHeartbeat returns tasks in
  PutEnd order with the flag, the same set without it.
- master_service_config_test: the flag reaches MasterServiceConfig from
  MasterConfig directly and through the supervisor config.
- file_storage_test: end to end with an embedded master, two heartbeats
  of six puts into four-key buckets give buckets [0..3], [4..7], [8..11]
  of the put order; off, every put still lands exactly once.
- file_storage_config_test: default, valid and invalid values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Zhewen Li <zhewenli@inferact.ai>
Add --offload_ordered_buckets to the master offload parameters and
MOONCAKE_OFFLOAD_ORDERED_BUCKETS to the bucket backend settings of the
SSD offload deployment guide, with a section on what they change and
where to set them, and describe the ordered delivery and packing next to
the grouping strategy in the design notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Zhewen Li <zhewenli@inferact.ai>
@github-actions github-actions Bot added documentation Improvements or additions to documentation run-ci Store Common size/M 100-1000 changed lines (additions + deletions) labels Nov 25, 2026

This branch has not been deployed

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

Labels

Common documentation Improvements or additions to documentation run-ci size/M 100-1000 changed lines (additions + deletions) Store

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant