Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions docs/source/design/store/ssd-offload.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,58 @@ Step by step:

---

## Bounded local streaming restore

`MOONCAKE_OFFLOAD_LOCAL_STREAMING_READ=true` enables a CPU restore path for
objects owned by the same Store client. The bucket backend pins each source
file while a bounded set of staging slots reads and copies chunks into the
caller's destinations. Whole objects and ranges can exceed the staging arena.
The default is disabled.

`MOONCAKE_OFFLOAD_READ_IO_THREADS` configures the per-client restore RPC read
thread pool size (default 8, valid range 1–128), initialized lazily on first
offload read call and joined on teardown to keep blocking legacy SSD reads off
the `coro_rpc` I/O event loop.

`MOONCAKE_OFFLOAD_STREAM_SLOT_BYTES` defaults to 1 MiB and
`MOONCAKE_OFFLOAD_STREAM_SLOTS` defaults to four. Read executors are created
lazily on first streaming read and default to four workers
(`MOONCAKE_OFFLOAD_STREAM_READ_THREADS`). Local CPU restores copy chunks inline
on the calling thread without spawning a separate write thread pool
(`MOONCAKE_OFFLOAD_STREAM_WRITE_THREADS` defaults to two and is validated for
asynchronous write targets).
`MOONCAKE_OFFLOAD_STREAM_MAX_OUTSTANDING` (default 64) bounds accepted tasks
and unique open bucket leases (keys in the same bucket share one open file
descriptor and `BucketReadGuard`, and eviction skips read-pinned buckets). Full
executors apply backpressure. Shutdown waits for accepted local reads before
releasing their staging memory.

Destinations, limits, and destination overlaps are checked before opening files
and planning ranges. Overlapping destinations and preflight capacity limits fall
back to the existing sequential restore path; invalid ranges, arena-aliasing
destinations, exhausted staging arenas (`BUFFER_OVERFLOW`), shut-down storage
(`UNAVAILABLE_IN_CURRENT_STATUS`), and post-preflight I/O errors fail directly.
An I/O failure after copying starts reports failure after accepted work has
drained. Publish the destination data only after the read succeeds.

### Optional streaming io_uring

Set `MOONCAKE_OFFLOAD_STREAM_USE_URING=true` together with local streaming
to use persistent ordinary-READ `io_uring` workers (lazily created on first
streaming read; idle workers block in `poll()` without periodic wakeups). Each
worker owns one ring and retains every source and staging slot until its CQE is
consumed. Partial reads continue from the completed offset, and transient
`-EINTR`/`-EAGAIN` completions have a finite retry budget. Submission
backpressure keeps accepted work within the configured limit.

If `io_uring` is unavailable at build or runtime, or if a previous batch left
the persistent `io_uring` read executor in a failed state, a warning is logged
and subsequent local streaming batches fall back to the portable `pread` driver
(queued or unsubmitted operations on a failed worker complete with
`FILE_READ_FAIL`, and a broken ring tears down cleanly so shutdown never hangs).
Both drivers drain accepted work before releasing source leases or staging
slots.

## Storage Backends

### BucketStorageBackend (default)
Expand Down
8 changes: 8 additions & 0 deletions mooncake-common/include/environment_variables.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ struct FileStorageEnvironmentVariables {
MOONCAKE_OFFLOAD_DISK_EVICTION_LOW_WATERMARK_RATIO);
MC_DEFINE_ENV_VAR(std::string, MOONCAKE_DISK_EVICTION_LOW_WATERMARK_RATIO);
MC_DEFINE_ENV_VAR(std::string, MOONCAKE_OFFLOAD_USE_URING);
MC_DEFINE_ENV_VAR(std::string, MOONCAKE_OFFLOAD_READ_IO_THREADS);
MC_DEFINE_ENV_VAR(bool, MOONCAKE_OFFLOAD_LOCAL_STREAMING_READ);
MC_DEFINE_ENV_VAR(bool, MOONCAKE_OFFLOAD_STREAM_USE_URING);
MC_DEFINE_ENV_VAR(uint64_t, MOONCAKE_OFFLOAD_STREAM_SLOT_BYTES);
MC_DEFINE_ENV_VAR(uint32_t, MOONCAKE_OFFLOAD_STREAM_SLOTS);
MC_DEFINE_ENV_VAR(uint32_t, MOONCAKE_OFFLOAD_STREAM_READ_THREADS);
MC_DEFINE_ENV_VAR(uint32_t, MOONCAKE_OFFLOAD_STREAM_WRITE_THREADS);
MC_DEFINE_ENV_VAR(uint32_t, MOONCAKE_OFFLOAD_STREAM_MAX_OUTSTANDING);
MC_DEFINE_ENV_VAR(std::string, MOONCAKE_USE_URING);
};

Expand Down
12 changes: 7 additions & 5 deletions mooncake-common/include/rpc_client_io_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,11 @@ class RpcDrainGuard {
private:
static bool try_enter(State& state) {
if (state.stopping.load(std::memory_order_acquire)) return false;
state.inflight.fetch_add(1, std::memory_order_acq_rel);
// a drain that started between the two reads still sees this call
if (state.stopping.load(std::memory_order_acquire)) {
// Give the admission increment and the drain's stop/count
// snapshot one total order. Otherwise both sides can miss the
// other's update on weakly ordered machines.
state.inflight.fetch_add(1, std::memory_order_seq_cst);
if (state.stopping.load(std::memory_order_seq_cst)) {
leave(state);
return false;
}
Expand All @@ -101,10 +103,10 @@ class RpcDrainGuard {
// regardless (the registry already does), and the state itself stays
// valid until the last ScopedCall lets go of it.
bool drain_for(std::chrono::milliseconds timeout) {
state_->stopping.store(true, std::memory_order_release);
state_->stopping.store(true, std::memory_order_seq_cst);
std::unique_lock lk(state_->mutex);
return state_->cv.wait_for(lk, timeout, [&] {
return state_->inflight.load(std::memory_order_acquire) == 0;
return state_->inflight.load(std::memory_order_seq_cst) == 0;
});
}

Expand Down
42 changes: 42 additions & 0 deletions mooncake-store/include/file_storage.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
#include "common/read_singleflight.h"
#include "client_buffer.h"
#include "storage_backend.h"
#include "ssd_pipeline_io.h"
#if defined(__linux__) && defined(USE_URING)
#include "ssd_uring_pipeline.h"
#endif
#include <shared_mutex>
#include "pinned_buffer_pool.h"

namespace mooncake {
Expand Down Expand Up @@ -68,6 +73,22 @@ class FileStorage {
std::vector<uint64_t> pointers;
};

struct LocalReadRequest {
std::string storage_key;
// Size of the complete persisted object, before range selection.
uint64_t expected_size{0};
uint64_t source_offset{0};
std::vector<Slice> destinations;
};
bool SupportsLocalStreamingRead() const;
// Destinations are writable CPU memory, held exclusively through return.
// Their sizes select a continuous source range in destination order.
// Destinations across the whole batch must not overlap. An I/O error can
// partially modify them; publish only after whole-batch success. Every
// return drains accepted I/O before releasing staging or source leases.
tl::expected<void, ErrorCode> ReadLocalStreaming(
const std::vector<LocalReadRequest>& requests);

struct LocalBatchResult {
std::vector<uint64_t> pointers;

Expand Down Expand Up @@ -414,6 +435,25 @@ class FileStorage {
std::shared_ptr<ClientBufferAllocator> pinned_restore_arena_allocator_;
std::shared_ptr<StorageBackendInterface> storage_backend_;
std::shared_ptr<ClientBufferAllocator> client_buffer_allocator_;
// Lazily initializes streaming executors while caller holds
// streaming_mutex_ (shared); serialized internally by
// streaming_init_mutex_.
ssd_offload::BoundedExecutor* GetOrCreateStreamingReadsLocked();
#if defined(__linux__) && defined(USE_URING)
std::shared_ptr<ssd_offload::UringReadExecutor>
GetOrCreateStreamingUringReadsLocked();
#endif

mutable std::shared_mutex streaming_mutex_;
mutable std::mutex streaming_init_mutex_;
bool streaming_bucket_ready_{false};
bool streaming_stopped_{false};
#if defined(__linux__) && defined(USE_URING)
bool streaming_uring_init_attempted_{false};
std::shared_ptr<ssd_offload::UringReadExecutor> streaming_uring_reads_;
#endif
std::unique_ptr<ssd_offload::BoundedExecutor> streaming_reads_;
std::atomic<size_t> active_streaming_sources_{0};
// Whether client_buffer_allocator_'s buffer is the io_uring fixed buffer,
// which the destructor must unregister before the buffer is freed.
bool uring_buffer_registered_ = false;
Expand All @@ -437,6 +477,8 @@ class FileStorage {
return client_buffer_shards_[batch_id % kClientBufferShards];
}

void ReapExpiredClientBuffers();

std::atomic<uint64_t> next_batch_id_{1};

/**
Expand Down
28 changes: 28 additions & 0 deletions mooncake-store/include/offload_read_executor_config.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2026 KVCache.AI
// Licensed under the Apache License, Version 2.0.
#pragma once

#include <cstdint>
#include <optional>

#include "integer_parser.h"

namespace mooncake::detail {

// Conservative per-client default to avoid thread explosion in multi-client
// processes; override via MOONCAKE_OFFLOAD_READ_IO_THREADS (1..128) for
// high-concurrency multi-rank SSD restores.
inline constexpr uint32_t kDefaultOffloadReadIoThreads = 8;
inline constexpr uint32_t kMaxOffloadReadIoThreads = 128;

inline std::optional<uint32_t> ParseOffloadReadIoThreads(const char* value) {
if (!value || !*value) return kDefaultOffloadReadIoThreads;
auto parsed = TryParseInteger<uint32_t>(
value, {.trim_ascii_whitespace = true, .allow_leading_plus = true});
if (!parsed || *parsed == 0 || *parsed > kMaxOffloadReadIoThreads) {
return std::nullopt;
}
return parsed;
}

} // namespace mooncake::detail
6 changes: 6 additions & 0 deletions mooncake-store/include/offset_allocator/offset_allocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,12 @@ class OffsetAllocator : public std::enable_shared_from_this<OffsetAllocator> {
// the request cannot be represented by this allocator.
[[nodiscard]] uint64_t normalizedAllocationSize(size_t size) const;

// Computes {normalized_slot_bytes, effective_arena_bytes} for an arena of
// size arena_bytes without instantiating an allocator. Returns {0, 0} on
// invalid or overflowing inputs.
[[nodiscard]] static std::pair<uint64_t, uint64_t> slotBudget(
size_t slot_bytes, uint64_t arena_bytes) noexcept;

// Returns a mutex-free atomic upper-bound hint for the largest allocatable
// free region. The hint may be larger than the current value after a
// successful allocation, is tightened on a locked allocation failure, and
Expand Down
10 changes: 9 additions & 1 deletion mooncake-store/include/real_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -1011,7 +1011,8 @@ class RealClient : public PyClient {
tl::expected<void, ErrorCode> batch_get_into_offload_object_internal(
const std::string &target_rpc_service_addr,
std::unordered_map<std::string, std::vector<Slice>> &objects,
const OffloadReadRange *read_range = nullptr);
const OffloadReadRange *read_range = nullptr,
bool allow_local_streaming = true);

// Owner restore for LOCAL_DISK: RPC batch_get_offload_object or
// BatchGetLocal. Callers copy out of the restored arena (sequential
Expand Down Expand Up @@ -1411,9 +1412,16 @@ class RealClient : public PyClient {
tl::expected<std::string, ErrorCode> StartEmbeddedMaster(
bool enable_ssd_offload);

class OffloadReadThreadPool;
OffloadReadThreadPool *GetOrCreateOffloadReadPool();
void StopOffloadReadPool();

std::mutex teardown_mutex_;
ErrorCode storage_shutdown_error_ = ErrorCode::OK;
RpcDrainGuard offload_rpc_drain_;
std::mutex offload_read_pool_mutex_;
std::unique_ptr<OffloadReadThreadPool> offload_read_pool_;
std::atomic<OffloadReadThreadPool *> offload_read_pool_fast_{nullptr};
friend class RealClientShutdownTestPeer;
std::unique_ptr<class EmbeddedMaster> embedded_master_;

Expand Down
70 changes: 70 additions & 0 deletions mooncake-store/include/ssd_pipeline_io.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright 2026 KVCache.AI
// Licensed under the Apache License, Version 2.0.
#pragma once

#include <chrono>
#include <functional>
#include <memory>
#include <vector>

#include "ssd_read_source.h"

namespace mooncake::ssd_offload {

class BoundedExecutor {
public:
BoundedExecutor(size_t workers, size_t max_outstanding);
~BoundedExecutor();
BoundedExecutor(const BoundedExecutor&) = delete;
BoundedExecutor& operator=(const BoundedExecutor&) = delete;
// Wait for credit on the scheduler thread. Workers must never call this
// method on their own executor.
bool WaitSubmit(std::function<void()> task) noexcept;
// Call from the owning thread; drains tasks before returning.
void Shutdown();

private:
struct Impl;
std::unique_ptr<Impl> impl_;
};

class WriteTarget {
public:
virtual ~WriteTarget() = default;
// Copies the chunk's fragments out of the staging slot synchronously.
virtual Error Write(const ReadChunk&, SlotBuffer) noexcept = 0;
};

class ThreadedPipelineDriver final : public PipelineDriver {
public:
// One immutable source index per global chunk. Every source and mapping
// entry is validated before work can be accepted. Passing writes == nullptr
// runs WriteTarget::Write inline on the scheduler thread (ideal for pure
// CPU memcpy targets without spawning an extra write thread pool).
ThreadedPipelineDriver(std::vector<std::shared_ptr<ReadSource>> sources,
std::vector<size_t> chunk_sources,
std::shared_ptr<WriteTarget> target,
BoundedExecutor& reads, BoundedExecutor* writes,
size_t slot_count);
ThreadedPipelineDriver(std::vector<std::shared_ptr<ReadSource>> sources,
std::vector<size_t> chunk_sources,
std::shared_ptr<WriteTarget> target,
BoundedExecutor& reads, BoundedExecutor& writes,
size_t slot_count)
: ThreadedPipelineDriver(std::move(sources), std::move(chunk_sources),
std::move(target), reads, &writes,
slot_count) {}
~ThreadedPipelineDriver() override;
bool SubmitRead(const SlotToken&, const ReadChunk&,
SlotBuffer) noexcept override;
bool SubmitWrite(const SlotToken&, const ReadChunk&,
SlotBuffer) noexcept override;
bool WaitForEvent(IoCompletion&,
std::chrono::milliseconds timeout) override;

private:
struct Impl;
std::unique_ptr<Impl> impl_;
};

} // namespace mooncake::ssd_offload
Loading
Loading