Skip to content
Closed
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
22 changes: 22 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,28 @@ 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_STREAM_SLOT_BYTES` defaults to 1 MiB and
`MOONCAKE_OFFLOAD_STREAM_SLOTS` defaults to four. Read and copy executors
default to four and two workers, configured with
`MOONCAKE_OFFLOAD_STREAM_READ_THREADS` and
`MOONCAKE_OFFLOAD_STREAM_WRITE_THREADS`.
`MOONCAKE_OFFLOAD_STREAM_MAX_OUTSTANDING` bounds accepted tasks and source
leases. Full executors apply backpressure. Shutdown waits for accepted local
reads before releasing their staging memory.

The entire batch is checked for invalid ranges and overlapping destinations
before copying. A preflight capacity failure can use the existing restore
path. An I/O failure after copying starts reports failure after accepted work
has drained. Publish the destination data only after the read succeeds.

## Storage Backends

### BucketStorageBackend (default)
Expand Down
6 changes: 6 additions & 0 deletions mooncake-common/include/environment_variables.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ 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(bool, MOONCAKE_OFFLOAD_LOCAL_STREAMING_READ);
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
24 changes: 24 additions & 0 deletions mooncake-store/include/file_storage.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
#include "common/read_singleflight.h"
#include "client_buffer.h"
#include "storage_backend.h"
#include "ssd_pipeline_io.h"
#include <shared_mutex>
#include "pinned_buffer_pool.h"

namespace mooncake {
Expand Down Expand Up @@ -68,6 +70,23 @@ 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 @@ -393,6 +412,11 @@ class FileStorage {
std::shared_ptr<ClientBufferAllocator> pinned_restore_arena_allocator_;
std::shared_ptr<StorageBackendInterface> storage_backend_;
std::shared_ptr<ClientBufferAllocator> client_buffer_allocator_;
mutable std::shared_mutex streaming_mutex_;
bool streaming_stopped_{false};
std::unique_ptr<ssd_offload::BoundedExecutor> streaming_reads_;
std::unique_ptr<ssd_offload::BoundedExecutor> streaming_writes_;
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 Down
92 changes: 92 additions & 0 deletions mooncake-store/include/ssd_pipeline_io.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright 2026 KVCache.AI
// Licensed under the Apache License, Version 2.0.
#pragma once

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

#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;
// Counts both queued and running tasks. false accepts no work.
bool TrySubmit(std::function<void()> task) noexcept;
// 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();
size_t outstanding() const;

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

class SourceDrainedWriteTarget {
public:
virtual ~SourceDrainedWriteTarget() = default;
// On return, no transport can still read the staging slot. Remote
// destination drain is a separate proof, queried after all calls return.
virtual Error WriteAndDrain(const ReadChunk&, SlotBuffer) noexcept = 0;
virtual bool DestinationsDrained() const noexcept = 0;
};

class DrainedWriteTarget : public SourceDrainedWriteTarget {
public:
virtual ~DrainedWriteTarget() = default;
// On return, no device can still read the slot or write the destination.
// A transport software timeout alone cannot satisfy this contract.
virtual Error WriteAndDrain(const ReadChunk&, SlotBuffer) noexcept = 0;
bool DestinationsDrained() const noexcept final { return true; }
};

struct IoCompletion {
SlotToken token{};
SlotStage stage{SlotStage::kFree};
size_t bytes{0};
Error result{Error::kOk};
};

class EventPipelineDriver : public PipelineDriver {
public:
virtual bool WaitForEvent(IoCompletion&, std::chrono::milliseconds) = 0;
};
class ThreadedPipelineDriver final : public EventPipelineDriver {
public:
ThreadedPipelineDriver(std::shared_ptr<ReadSource> source,
std::shared_ptr<SourceDrainedWriteTarget> target,
BoundedExecutor& reads, BoundedExecutor& writes,
size_t slot_count);
// One immutable source index per global chunk. Every source and mapping
// entry is validated before work can be accepted. Both vectors must be
// nonempty; the single-source overload keeps its unrestricted chunk IDs.
ThreadedPipelineDriver(std::vector<std::shared_ptr<ReadSource>> sources,
std::vector<size_t> chunk_sources,
std::shared_ptr<SourceDrainedWriteTarget> target,
BoundedExecutor& reads, BoundedExecutor& writes,
size_t slot_count);
~ThreadedPipelineDriver() override;
bool SubmitRead(const SlotToken&, const ReadChunk&,
SlotBuffer) noexcept override;
bool SubmitWrite(const SlotToken&, const ReadChunk&,
SlotBuffer) noexcept override;
void RequestCancel(const SlotToken&, SlotStage) noexcept override;
// The scheduler consumes events here, then calls ReadDrained/WriteDrained.
// At most one running/ready operation is stored per slot.
bool WaitForEvent(IoCompletion&,
std::chrono::milliseconds timeout) override;

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

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

#include <cstddef>
#include <cstdint>
#include <vector>

namespace mooncake::ssd_offload {

enum class Error {
kOk,
kInvalidArgument,
kOverflow,
kPlanLimit,
kInvalidState,
kStaleEvent,
kIoError,
kTransferError,
kCancelled,
kNotSupported,
};

// Opaque registry identity, not a pointer or an RNIC access key.
struct DestinationSlice {
uint64_t region_id;
uint64_t generation;
uint64_t offset;
uint64_t length;
};

struct ReadRange {
uint64_t source_offset;
std::vector<DestinationSlice> destinations;
};

struct ObjectRead {
uint64_t object_bytes;
uint64_t value_file_offset;
std::vector<ReadRange> ranges;
};

struct PlanOptions {
size_t slot_bytes;
size_t alignment;
size_t max_chunks;
size_t max_fragments{65536};
};

struct WriteFragment {
size_t buffer_offset;
DestinationSlice destination;
};

struct ReadChunk {
uint64_t source_offset;
uint64_t file_offset;
size_t read_bytes;
size_t payload_offset;
size_t payload_bytes;
std::vector<WriteFragment> fragments;
};

struct ReadPlan {
size_t slot_bytes{0};
size_t alignment{0};
uint64_t payload_bytes{0};
uint64_t io_bytes{0};
std::vector<ReadChunk> chunks;
};

struct PlanResult {
Error error{Error::kOk};
ReadPlan plan;
};

// Any failure returns an empty plan; no partial plan may be submitted.
PlanResult BuildReadPlan(const ObjectRead& object, PlanOptions options);

enum class SlotStage { kFree, kReading, kWriting };
enum class PipelineState {
kReady,
kRunning,
kDraining,
kSucceeded,
kCancelled,
kFailed,
};

struct SlotBuffer {
std::byte* data;
size_t capacity;
};

struct SlotToken {
uint64_t request_id;
uint64_t attempt_id;
size_t slot_index;
uint64_t generation;
size_t chunk_index;
};

class PipelineDriver {
public:
virtual ~PipelineDriver() = default;

// Called on the scheduler thread. No inline completion callbacks.
// false means rejected with NO outstanding device access. After true,
// the driver must deliver a staging-drained event even on
// cancellation/error. Destination drain is independently tracked by the
// remote write target. ReadChunk and buffers stay alive until that event
// has been consumed.
virtual bool SubmitRead(const SlotToken& token, const ReadChunk& chunk,
SlotBuffer buffer) noexcept = 0;
virtual bool SubmitWrite(const SlotToken& token, const ReadChunk& chunk,
SlotBuffer buffer) noexcept = 0;
// Best effort only. This call does not release a slot.
virtual void RequestCancel(const SlotToken&, SlotStage) noexcept {}
};

// Single scheduler thread. Other workers enqueue events for that thread.
// Caller owns arena/MRs and driver; keep them and this object alive until
// inflight()==0. A software timeout is NOT a drained completion.
class ReadPipeline {
public:
ReadPipeline(uint64_t request_id, uint64_t attempt_id, ReadPlan plan,
std::vector<SlotBuffer> buffers, PipelineDriver& driver);
ReadPipeline(const ReadPipeline&) = delete;
ReadPipeline& operator=(const ReadPipeline&) = delete;
ReadPipeline(ReadPipeline&&) = delete;
ReadPipeline& operator=(ReadPipeline&&) = delete;

Error Start();
void Cancel();
Error ReadDrained(const SlotToken& token, size_t bytes_read,
Error result = Error::kOk);
Error WriteDrained(const SlotToken& token, Error result = Error::kOk);

PipelineState state() const { return state_; }
Error error() const { return error_; }
size_t inflight() const { return inflight_; }
// Successfully written bytes, including writes drained after cancellation.
// Only kSucceeded permits publication of the complete destination object.
uint64_t completed_bytes() const { return completed_bytes_; }

private:
struct Slot {
SlotBuffer buffer;
SlotStage stage{SlotStage::kFree};
uint64_t generation{0};
size_t chunk_index{0};
};
Error Validate() const;
void Pump();
void Abort(Error error);
void Release(size_t slot_index);
void UpdateTerminal();
bool Matches(const SlotToken& token, SlotStage stage) const;
SlotToken Token(size_t slot_index) const;

uint64_t request_id_, attempt_id_;
ReadPlan plan_;
PipelineDriver& driver_;
std::vector<Slot> slots_;
PipelineState state_{PipelineState::kReady};
Error error_{Error::kOk};
size_t next_chunk_{0}, inflight_{0}, completed_chunks_{0};
uint64_t completed_bytes_{0};
};

} // namespace mooncake::ssd_offload
Loading
Loading