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
47 changes: 47 additions & 0 deletions docs/source/design/store/ssd-offload.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,55 @@ 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

### Owner-read controller development

The owner-read controller provides request validation, bounded admission,
terminal-result caching, and destination-registration lifetime tracking for
the owner-push work in RFC #5768. Integration supplies the trusted peer
bindings, a control-call adapter, an SSD reader and a transport write target.
The adapter must authenticate both directions before interpreting a reply
as evidence of drain.

`SsdFixedL2Requester::ReadWithRecovery` makes bounded recovery attempts.
A result without a terminal snapshot retains the registered allocation owner
and records the attempt as pending. Only managed allocations may use this
API. A raw borrowed application pointer requires an independent receiver
fence before the application can reuse it after a failed call.

Retired owner request IDs are stored as bounded, coalesced ranges. Recovering
one ID retires that ID alone, allowing earlier requests to arrive out of order.
The terminal cache evicts by completion time. Running attempts retain their
resource credits, while an admitted operation abandoned before start returns
its credits with a rejected result.

This component is exercised through injected transport and storage adapters.
The network listener, authenticated bootstrap, epoch retirement, and the
public managed-buffer API are integration work tracked by RFC #5768.

### BucketStorageBackend (default)

Objects are grouped into **buckets** before being written to disk. Each bucket produces two files:
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
30 changes: 30 additions & 0 deletions mooncake-store/include/random.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,40 @@
#include <concepts>
#include <cstddef>
#include <random>
#include <span>
#include <array>
#include <cerrno>
#include <cstring>
#include <algorithm>
#if defined(__linux__) || defined(__APPLE__)
#include <sys/random.h>
#endif
#include <stdexcept>

namespace mooncake {

// OS cryptographic entropy; false never falls back to the shared PRNG.
inline bool secureRandomBytes(std::span<std::byte> bytes) noexcept {
size_t offset = 0;
std::array<std::byte, 256> entropy;
while (offset < bytes.size()) {
#if defined(__linux__) || defined(__APPLE__)
// getentropy limits each request to 256 bytes. It either fills the
// entire request or fails; it never exposes a short successful read.
const auto count = std::min(size_t{256}, bytes.size() - offset);
if (::getentropy(entropy.data(), count) == 0) {
std::memcpy(bytes.data() + offset, entropy.data(), count);
offset += count;
continue;
}
if (errno == EINTR) continue;
#endif
std::fill(bytes.begin(), bytes.end(), std::byte{0});
return false;
}
return true;
}

using RandomEngine = std::mt19937_64;

namespace detail {
Expand Down
45 changes: 45 additions & 0 deletions mooncake-store/include/ssd_control_wire.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright 2026 KVCache.AI
// Licensed under the Apache License, Version 2.0.
#pragma once
#include "ssd_read_control.h"
#include <string_view>

namespace mooncake::ssd_offload {
inline constexpr size_t kSsdControlMaxWireBytes = 2 * 1024 * 1024;
enum class SsdControlCommand : uint32_t {
kResolve = 1,
kSubmit = 2,
kQuery = 3,
kForget = 4,
kReadInto = 5,
kRecoverReadInto = 6
};
struct SsdControlMessage {
SsdControlCommand command{SsdControlCommand::kQuery};
SsdGrantReferenceV1 reference;
std::optional<SsdReadRequestV1> request;
// Fixed-L2 direct reads carry locally resolved views inline. Legacy
// Submit/Resolve/Query/Forget frames remain byte-for-byte unchanged.
std::vector<ResolvedDestination> destinations{};
};
struct SsdControlReply {
SsdControlCommand command{SsdControlCommand::kQuery};
DestinationError error{DestinationError::kInvalidArgument};
std::optional<SsdOwnerRequestSnapshot> snapshot;
std::vector<ResolvedDestination> destinations;
};
struct SsdControlEncoded {
DestinationError error{DestinationError::kInvalidArgument};
std::string bytes;
};
SsdControlEncoded EncodeSsdControlMessage(const SsdControlMessage&,
SsdReadProtocolLimits = {});
SsdControlEncoded EncodeSsdControlReply(const SsdControlReply&,
SsdReadProtocolLimits = {});
// Two passes: first scan counts/string/payload bounds without allocation, then
// construct the bounded decoded value. Failure leaves output unchanged.
DestinationError DecodeSsdControlMessage(std::string_view, SsdControlMessage&,
SsdReadProtocolLimits = {});
DestinationError DecodeSsdControlReply(std::string_view, SsdControlReply&,
SsdReadProtocolLimits = {});
} // namespace mooncake::ssd_offload
195 changes: 195 additions & 0 deletions mooncake-store/include/ssd_destination_registry.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// Copyright 2026 KVCache.AI
// Licensed under the Apache License, Version 2.0.
#pragma once

#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>

namespace mooncake::ssd_offload {

enum class DestinationError {
kOk,
kInvalidArgument,
kOverflow,
kNotFound,
kStaleRegion,
kUnauthorized,
kOverlap,
kLimit,
kClosing,
kBusy,
kWrongAttempt,
kNotDrained,
kDuplicate,
kStaleRequest,
kNotSupported,
kTransportError,
};

struct PeerIdentity {
uint64_t client_id_high{0};
uint64_t client_id_low{0};
uint64_t boot_epoch{0};
bool operator==(const PeerIdentity&) const = default;
};

// Issued by an authorized registration adapter. The registry does not generate
// secrets, and IDs/generations alone do not authorize a write or revoke DMA.
struct WriteCredential {
uint64_t high{0};
uint64_t low{0};
bool operator==(const WriteCredential&) const = default;
};

struct DestinationRegion {
PeerIdentity requester;
uint64_t region_id{0};
uint64_t generation{0};
WriteCredential credential;
bool operator==(const DestinationRegion&) const = default;
};

struct RegisteredDestination {
DestinationRegion region;
uint64_t offset{0};
uint64_t length{0};
bool operator==(const RegisteredDestination&) const = default;
};

enum class DestinationMemory { kHost, kDevice };
struct DestinationBinding {
uint64_t logical_base{0};
uint64_t logical_bytes{0};
uint64_t registered_base{0};
uint64_t registered_bytes{0};
DestinationMemory memory{DestinationMemory::kHost};
};
struct ResolvedDestination {
std::string transport_endpoint;
uint64_t address{0};
uint64_t length{0};
DestinationMemory memory{DestinationMemory::kHost};
};

struct AttemptIdentity {
PeerIdentity owner;
uint64_t request_id{0};
uint64_t attempt_id{0};
bool operator==(const AttemptIdentity&) const = default;
};

enum class AttemptOutcome { kSucceeded, kFailed, kCancelled, kRejected };
struct DestinationDrainAck {
AttemptIdentity attempt;
AttemptOutcome outcome{AttemptOutcome::kFailed};
uint64_t valid_bytes{0};
bool dma_drained{false};
PeerIdentity requester;
};
enum class DestinationAttemptState {
kPrepared,
kExposed,
kQuarantined,
kDrained
};
struct DestinationAttemptSnapshot {
DestinationError error{DestinationError::kNotFound};
DestinationAttemptState state{DestinationAttemptState::kPrepared};
uint64_t requested_bytes{0};
uint64_t valid_bytes{0};
// Transfer completeness only; integrity still needs caller verification.
// Timed-out or abandoned attempts never become publishable on a late ACK.
bool publishable{false};
};

struct DestinationRegistryLimits {
size_t max_regions{1024};
size_t max_tracked_attempts{1024};
size_t max_owner_sessions{64};
size_t max_active_fragments{65536};
uint64_t max_active_bytes{4ULL * 1024 * 1024 * 1024};
};
struct DestinationRegistryStats {
size_t regions{0};
size_t tracked_attempts{0};
size_t active_attempts{0};
size_t quarantined_attempts{0};
size_t active_fragments{0};
uint64_t active_bytes{0};
// Reserved fragment-array storage, excluding map/string/allocator overhead.
uint64_t fragment_array_bytes{0};
};

class DestinationRegistry {
struct State;
struct Record;

public:
class Attempt {
public:
Attempt() = default;
Attempt(Attempt&&) noexcept;
Attempt& operator=(Attempt&&) noexcept;
~Attempt();
Attempt(const Attempt&) = delete;
Attempt& operator=(const Attempt&) = delete;
// Marks exposure before returning addresses that may be sent to an
// owner. Keep the handle/registry alive for later drain confirmation.
DestinationError Publish(
std::vector<ResolvedDestination>& destinations);
DestinationError Timeout();
DestinationError Complete(const DestinationDrainAck& ack);
DestinationAttemptSnapshot snapshot() const;

private:
friend class DestinationRegistry;
Attempt(std::shared_ptr<State>, std::shared_ptr<Record>);
void Abandon() noexcept;
std::shared_ptr<State> state_;
std::shared_ptr<Record> record_;
};
struct RegistrationResult {
DestinationError error{DestinationError::kInvalidArgument};
DestinationRegion region;
};
struct AcquireResult {
DestinationError error{DestinationError::kInvalidArgument};
Attempt attempt;
};

DestinationRegistry(PeerIdentity requester, std::string transport_endpoint,
DestinationRegistryLimits limits = {});
~DestinationRegistry();
DestinationRegistry(const DestinationRegistry&) = delete;
DestinationRegistry& operator=(const DestinationRegistry&) = delete;

// Pins transport registration/parent mapping. The caller holds its actual
// allocation until logical retirement AND transport deregistration succeed;
// a token is not ownership
// of an arbitrary application pointer. Logical aliases are rejected.
RegistrationResult Register(DestinationBinding, WriteCredential,
std::shared_ptr<void> registration_lifetime);
AcquireResult Acquire(
const AttemptIdentity&,
const std::vector<RegisteredDestination>& destinations);
DestinationError BeginRevoke(const DestinationRegion&);
// Call after no DMA remains; kBusy leaves the registration pinned. The
// adapter must retain/quarantine backing if transport deregistration fails.
DestinationError Retire(const DestinationRegion&);
DestinationError Complete(const DestinationDrainAck&);
DestinationAttemptSnapshot Inspect(const AttemptIdentity&) const;
// Acknowledges a completed logical request and advances an owner-session
// replay floor. New request IDs must increase; existing older attempts
// remain drainable. No active/quarantined request may be forgotten.
DestinationError ForgetRequest(PeerIdentity owner, uint64_t request_id);
DestinationRegistryStats stats() const;
bool HasPendingWrite(uint64_t address, uint64_t bytes) const;

private:
std::shared_ptr<State> state_;
};

} // namespace mooncake::ssd_offload
Loading
Loading