diff --git a/docs/source/design/store/ssd-offload.md b/docs/source/design/store/ssd-offload.md index 90ca495c89d..fa9b3eebb55 100644 --- a/docs/source/design/store/ssd-offload.md +++ b/docs/source/design/store/ssd-offload.md @@ -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) diff --git a/mooncake-common/include/environment_variables.h b/mooncake-common/include/environment_variables.h index 131fed79042..af41ecaf186 100644 --- a/mooncake-common/include/environment_variables.h +++ b/mooncake-common/include/environment_variables.h @@ -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); }; diff --git a/mooncake-common/include/rpc_client_io_context.h b/mooncake-common/include/rpc_client_io_context.h index 5795668587b..9789ba1e9bd 100644 --- a/mooncake-common/include/rpc_client_io_context.h +++ b/mooncake-common/include/rpc_client_io_context.h @@ -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; } @@ -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; }); } diff --git a/mooncake-store/include/file_storage.h b/mooncake-store/include/file_storage.h index 5b9c4cbc1ab..d11dc900fca 100644 --- a/mooncake-store/include/file_storage.h +++ b/mooncake-store/include/file_storage.h @@ -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 #include "pinned_buffer_pool.h" namespace mooncake { @@ -68,6 +73,22 @@ class FileStorage { std::vector 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 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 ReadLocalStreaming( + const std::vector& requests); + struct LocalBatchResult { std::vector pointers; @@ -414,6 +435,25 @@ class FileStorage { std::shared_ptr pinned_restore_arena_allocator_; std::shared_ptr storage_backend_; std::shared_ptr 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 + 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 streaming_uring_reads_; +#endif + std::unique_ptr streaming_reads_; + std::atomic 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; @@ -437,6 +477,8 @@ class FileStorage { return client_buffer_shards_[batch_id % kClientBufferShards]; } + void ReapExpiredClientBuffers(); + std::atomic next_batch_id_{1}; /** diff --git a/mooncake-store/include/offload_read_executor_config.h b/mooncake-store/include/offload_read_executor_config.h new file mode 100644 index 00000000000..24cb51f5e05 --- /dev/null +++ b/mooncake-store/include/offload_read_executor_config.h @@ -0,0 +1,28 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#pragma once + +#include +#include + +#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 ParseOffloadReadIoThreads(const char* value) { + if (!value || !*value) return kDefaultOffloadReadIoThreads; + auto parsed = TryParseInteger( + value, {.trim_ascii_whitespace = true, .allow_leading_plus = true}); + if (!parsed || *parsed == 0 || *parsed > kMaxOffloadReadIoThreads) { + return std::nullopt; + } + return parsed; +} + +} // namespace mooncake::detail diff --git a/mooncake-store/include/offset_allocator/offset_allocator.h b/mooncake-store/include/offset_allocator/offset_allocator.h index 268de752326..3b3a11fb8af 100644 --- a/mooncake-store/include/offset_allocator/offset_allocator.h +++ b/mooncake-store/include/offset_allocator/offset_allocator.h @@ -171,6 +171,12 @@ class OffsetAllocator : public std::enable_shared_from_this { // 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 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 diff --git a/mooncake-store/include/real_client.h b/mooncake-store/include/real_client.h index 644f9d52e4a..1015b0578cb 100644 --- a/mooncake-store/include/real_client.h +++ b/mooncake-store/include/real_client.h @@ -1011,7 +1011,8 @@ class RealClient : public PyClient { tl::expected batch_get_into_offload_object_internal( const std::string &target_rpc_service_addr, std::unordered_map> &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 @@ -1411,9 +1412,16 @@ class RealClient : public PyClient { tl::expected 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 offload_read_pool_; + std::atomic offload_read_pool_fast_{nullptr}; friend class RealClientShutdownTestPeer; std::unique_ptr embedded_master_; diff --git a/mooncake-store/include/ssd_pipeline_io.h b/mooncake-store/include/ssd_pipeline_io.h new file mode 100644 index 00000000000..4f4556e2301 --- /dev/null +++ b/mooncake-store/include/ssd_pipeline_io.h @@ -0,0 +1,70 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#pragma once + +#include +#include +#include +#include + +#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 task) noexcept; + // Call from the owning thread; drains tasks before returning. + void Shutdown(); + + private: + struct Impl; + std::unique_ptr 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> sources, + std::vector chunk_sources, + std::shared_ptr target, + BoundedExecutor& reads, BoundedExecutor* writes, + size_t slot_count); + ThreadedPipelineDriver(std::vector> sources, + std::vector chunk_sources, + std::shared_ptr 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_; +}; + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/include/ssd_read_pipeline.h b/mooncake-store/include/ssd_read_pipeline.h new file mode 100644 index 00000000000..2e6ffe023df --- /dev/null +++ b/mooncake-store/include/ssd_read_pipeline.h @@ -0,0 +1,177 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#pragma once + +#include +#include +#include +#include + +namespace mooncake::ssd_offload { + +enum class Error { + kOk, + kInvalidArgument, + kOverflow, + kPlanLimit, + kInvalidState, + kStaleEvent, + kIoError, + kTransferError, + kNotSupported, +}; + +struct DestinationSlice { + size_t destination_index; + uint64_t offset; + uint64_t length; +}; + +struct ObjectRead { + uint64_t object_bytes; + uint64_t value_file_offset; + uint64_t source_offset; + std::vector destinations; +}; + +struct PlanOptions { + size_t slot_bytes; + size_t alignment{1}; + size_t max_chunks{65536}; + 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 fragments; +}; + +struct ReadPlan { + size_t slot_bytes{0}; + size_t alignment{0}; + uint64_t payload_bytes{0}; + uint64_t io_bytes{0}; + std::vector 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); + +// Pure completion classifier for buffered io_uring read CQEs: handles short +// reads, transient -EINTR/-EAGAIN retries, EOF, and over-long completions. +struct UringReadStep { + bool retry{false}; + size_t next_done{0}; + unsigned next_retries{0}; + Error error{Error::kOk}; + int sys_errno{0}; +}; + +UringReadStep ClassifyUringReadResult(int completed, size_t done, + size_t requested, unsigned retries, + unsigned max_retries = 3) noexcept; + +enum class SlotStage { kFree, kReading, kWriting }; +enum class PipelineState { + kReady, + kRunning, + kDraining, + kSucceeded, + kFailed, +}; + +struct SlotBuffer { + std::byte* data; + size_t capacity; +}; + +struct SlotToken { + size_t slot_index; + uint64_t generation; + size_t chunk_index; +}; + +struct IoCompletion { + SlotToken token{}; + SlotStage stage{SlotStage::kFree}; + size_t bytes{0}; + Error result{Error::kOk}; + int sys_errno{0}; +}; + +class PipelineDriver { + public: + virtual ~PipelineDriver() = default; + + // Called on the scheduler thread. No inline completion callbacks. + // false means rejected with NO outstanding I/O. After true, the driver + // borrows both buffer and chunk until the completion event is delivered or + // the driver is destroyed (so the owning ReadPlan must outlive the driver). + 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; + virtual bool WaitForEvent(IoCompletion&, std::chrono::milliseconds) { + return false; + } +}; + +// Single scheduler thread; worker threads deliver completions via WaitForEvent. +// Caller owns staging slots and driver and keeps them alive until inflight()==0 +// (or relies on driver destruction draining accepted I/O first). +class ReadPipeline { + public: + ReadPipeline(ReadPlan plan, std::vector buffers, + PipelineDriver& driver); + ReadPipeline(const ReadPipeline&) = delete; + ReadPipeline& operator=(const ReadPipeline&) = delete; + ReadPipeline(ReadPipeline&&) = delete; + ReadPipeline& operator=(ReadPipeline&&) = delete; + + Error Start(); + 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_; } + + 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; + + ReadPlan plan_; + PipelineDriver& driver_; + std::vector slots_; + PipelineState state_{PipelineState::kReady}; + Error error_{Error::kOk}; + size_t next_chunk_{0}, inflight_{0}, completed_chunks_{0}; +}; + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/include/ssd_read_source.h b/mooncake-store/include/ssd_read_source.h new file mode 100644 index 00000000000..770e35dbec5 --- /dev/null +++ b/mooncake-store/include/ssd_read_source.h @@ -0,0 +1,47 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#pragma once + +#include +#include +#include +#include + +#include "ssd_read_pipeline.h" + +namespace mooncake::ssd_offload { + +struct ReadResult { + size_t bytes{0}; + Error error{Error::kOk}; + int sys_errno{0}; +}; + +class ReadSource { + public: + virtual ~ReadSource() = default; + virtual uint64_t file_bytes() const noexcept = 0; + // Synchronous, position-independent read. When this returns, no I/O + // can still write into the supplied buffer, including on failure. + virtual ReadResult ReadAt(std::span buffer, + uint64_t file_offset) noexcept = 0; + // Borrowed fd, pinned by the source lifetime. Async drivers must retain + // this source until every submitted read has actually completed. + virtual std::optional native_read_fd() const noexcept { return {}; } +}; + +struct ReadSourceResult { + Error error; + std::shared_ptr source; + int sys_errno{0}; +}; + +// Opens a regular file read-only (non-blocking open cleared after S_ISREG +// validation) and verifies it is at least min_file_bytes long. The optional +// lifetime token pins backend metadata/file lifetime through the last source +// reference. +ReadSourceResult OpenPosixReadSource(const std::string& path, + uint64_t min_file_bytes, + std::shared_ptr lifetime = {}); + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/include/ssd_streaming_config.h b/mooncake-store/include/ssd_streaming_config.h new file mode 100644 index 00000000000..0288cd3a158 --- /dev/null +++ b/mooncake-store/include/ssd_streaming_config.h @@ -0,0 +1,49 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#pragma once + +#include +#include +#include + +#include "offset_allocator/offset_allocator.h" + +namespace mooncake::ssd_offload { + +// Delegates to OffsetAllocator::slotBudget() so config validation stays in +// lockstep with OffsetAllocator's bin rounding and multiplier calculation. +inline std::pair OffsetAllocatorSlotBudget( + size_t slot_bytes, uint64_t arena_bytes) noexcept { + return mooncake::offset_allocator::OffsetAllocator::slotBudget(slot_bytes, + arena_bytes); +} + +struct StreamingReadConfig { + bool enabled{false}; + bool use_uring{false}; + size_t slot_bytes{1024 * 1024}; + size_t slots{4}; + size_t read_workers{4}; + size_t write_workers{2}; + size_t max_outstanding{64}; + size_t max_chunks{65536}; + size_t max_fragments{65536}; + + bool Validate(uint64_t arena_bytes) const { + if (!enabled) return true; + if (slot_bytes == 0 || slot_bytes > 64ULL * 1024 * 1024 || slots == 0 || + slots > 64 || read_workers == 0 || read_workers > 64 || + write_workers == 0 || write_workers > 64 || + max_outstanding < slots || max_outstanding > 65536 || + read_workers > max_outstanding || max_chunks == 0 || + max_fragments == 0) { + return false; + } + const auto [normalized_slot, effective_arena] = + OffsetAllocatorSlotBudget(slot_bytes, arena_bytes); + return normalized_slot > 0 && + normalized_slot <= effective_arena / slots; + } +}; + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/include/ssd_uring_pipeline.h b/mooncake-store/include/ssd_uring_pipeline.h new file mode 100644 index 00000000000..9602d97a8d3 --- /dev/null +++ b/mooncake-store/include/ssd_uring_pipeline.h @@ -0,0 +1,85 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#pragma once + +#include +#include +#include +#include +#include + +#include "ssd_pipeline_io.h" + +namespace mooncake::ssd_offload { + +// Persistent ordinary-READ io_uring worker pool. Each worker owns one ring; +// accepted operations retain their source and buffer until the CQE is consumed. +class UringReadExecutor { + public: + using Completion = std::function; + // Returns empty when unsupported or initialization fails. Limits match + // StreamingReadConfig: 1..64 workers and 1..65536 outstanding reads. + static std::shared_ptr Create( + size_t workers, size_t max_outstanding) noexcept; + ~UringReadExecutor(); + UringReadExecutor(const UringReadExecutor&) = delete; + UringReadExecutor& operator=(const UringReadExecutor&) = delete; + + // Waits for admission credit on an external scheduler thread. fd must equal + // source->native_read_fd(). false accepts nothing and never invokes + // completion. true retains the source and borrowed buffer until completion, + // including across Shutdown(). Callback exceptions are contained; credit + // covers completion callback destruction. + bool WaitSubmit(std::shared_ptr source, int fd, + std::span buffer, uint64_t file_offset, + Completion completion) noexcept; + // Stops admission and drains accepted reads before joining workers. Call + // externally, never from a completion callback. + void Shutdown(); + bool healthy() const noexcept; + + private: + struct Impl; + explicit UringReadExecutor(std::unique_ptr); + std::unique_ptr impl_; +}; + +class UringPipelineDriver final : public PipelineDriver { + public: + struct Creation { + Error error{Error::kNotSupported}; + std::unique_ptr driver; + }; + // Executes reads on the shared UringReadExecutor and copies through writes + // (or inline on the scheduler thread when writes == nullptr). + // chunk_sources maps each chunk index to an index in sources. + static Creation Create(std::vector> sources, + std::vector chunk_sources, + std::shared_ptr target, + std::shared_ptr reader, + BoundedExecutor* writes, + std::vector buffers); + static Creation Create(std::vector> sources, + std::vector chunk_sources, + std::shared_ptr target, + std::shared_ptr reader, + BoundedExecutor& writes, + std::vector buffers) { + return Create(std::move(sources), std::move(chunk_sources), + std::move(target), std::move(reader), &writes, + std::move(buffers)); + } + ~UringPipelineDriver() 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) override; + + private: + struct Impl; + explicit UringPipelineDriver(std::unique_ptr); + std::unique_ptr impl_; +}; + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/include/storage_backend.h b/mooncake-store/include/storage_backend.h index 3c98c6ad46f..0979fb23623 100644 --- a/mooncake-store/include/storage_backend.h +++ b/mooncake-store/include/storage_backend.h @@ -27,6 +27,8 @@ #include "mutex.h" #include "offset_allocator/offset_allocator.h" #include "types.h" +#include "ssd_read_source.h" +#include "ssd_streaming_config.h" namespace mooncake { struct FileRecord { @@ -357,6 +359,8 @@ struct FileStorageConfig { double disk_eviction_high_watermark_ratio = 0.90; double disk_eviction_low_watermark_ratio = 0.80; + ssd_offload::StreamingReadConfig streaming_read; + // Validates the configuration for correctness and consistency bool Validate() const; @@ -976,6 +980,27 @@ class BucketStorageBackend : public StorageBackendInterface { tl::expected GetBucketKeys( int64_t bucket_id, std::vector& bucket_keys); + struct ReadSourceRequest { + std::string_view key; + uint64_t expected_size{0}; + }; + struct AcquiredObjectLocation { + size_t source_index{0}; + uint64_t object_bytes{0}; + uint64_t value_file_offset{0}; + }; + struct AcquiredReadSources { + std::vector> sources; + std::vector locations; + }; + + // Resolves a batch of keys under one shared metadata lock, deduplicates + // open descriptors and BucketReadGuards per bucket, and calls + // reserve_credits(unique_bucket_count) before opening any file. + tl::expected AcquireReadSources( + const std::vector& requests, + const std::function& reserve_credits = nullptr); + /** * @brief Initializes the bucket storage backend. * @return tl::expected indicating operation status. diff --git a/mooncake-store/src/CMakeLists.txt b/mooncake-store/src/CMakeLists.txt index ee0d62fd11c..cf95f949b1a 100644 --- a/mooncake-store/src/CMakeLists.txt +++ b/mooncake-store/src/CMakeLists.txt @@ -146,6 +146,9 @@ set(MOONCAKE_STORE_CLIENT_SOURCES shm_helper.cpp config/shm_spdk_registration_config.cpp file_storage.cpp + ssd_read_pipeline.cpp + ssd_read_source.cpp + ssd_pipeline_io.cpp config/client_host_identity_config.cpp ssd_prefetcher.cpp config/client_metric_config.cpp @@ -348,6 +351,9 @@ endif() set(MOONCAKE_HAVE_NVME_URING_CMD OFF) if(TARGET Mooncake::liburing) list(APPEND MOONCAKE_STORE_CLIENT_SOURCES uring_file.cpp) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + list(APPEND MOONCAKE_STORE_CLIENT_SOURCES ssd_uring_pipeline.cpp) + endif() include(CheckCXXSourceCompiles) get_target_property(MOONCAKE_LIBURING_INCLUDE_DIRS Mooncake::liburing diff --git a/mooncake-store/src/config/file_storage_config.cpp b/mooncake-store/src/config/file_storage_config.cpp index c4c39a0cf82..ef82580f56b 100644 --- a/mooncake-store/src/config/file_storage_config.cpp +++ b/mooncake-store/src/config/file_storage_config.cpp @@ -171,6 +171,29 @@ FileStorageConfig FileStorageConfig::FromEnvironment() { Variables::MOONCAKE_OFFLOAD_USE_URING, legacy_use_uring); config.use_uring = ParseStrictBoolOr(use_uring, false); + auto& stream = config.streaming_read; + stream.use_uring = + Environ::ReadOr(Variables::MOONCAKE_OFFLOAD_STREAM_USE_URING, false); + stream.enabled = Environ::ReadOr( + Variables::MOONCAKE_OFFLOAD_LOCAL_STREAMING_READ, stream.enabled); + const uint64_t slot_bytes = + Environ::ReadOr(Variables::MOONCAKE_OFFLOAD_STREAM_SLOT_BYTES, + uint64_t(stream.slot_bytes)); + stream.slot_bytes = slot_bytes > std::numeric_limits::max() + ? std::numeric_limits::max() + : size_t(slot_bytes); + stream.slots = Environ::ReadOr(Variables::MOONCAKE_OFFLOAD_STREAM_SLOTS, + uint32_t(stream.slots)); + stream.read_workers = + Environ::ReadOr(Variables::MOONCAKE_OFFLOAD_STREAM_READ_THREADS, + uint32_t(stream.read_workers)); + stream.write_workers = + Environ::ReadOr(Variables::MOONCAKE_OFFLOAD_STREAM_WRITE_THREADS, + uint32_t(stream.write_workers)); + stream.max_outstanding = + Environ::ReadOr(Variables::MOONCAKE_OFFLOAD_STREAM_MAX_OUTSTANDING, + uint32_t(stream.max_outstanding)); + return config; } @@ -236,6 +259,13 @@ bool FileStorageConfig::ValidatePath(std::string path) const { } bool FileStorageConfig::Validate() const { + if (streaming_read.enabled && + storage_backend_type == StorageBackendType::kBucket && + (local_buffer_size <= 0 || + !streaming_read.Validate(local_buffer_size))) { + LOG(ERROR) << "Invalid SSD streaming limits or staging arena size"; + return false; + } // storage_filepath may be a comma-separated multi-disk list. ValidatePath // stats a single path and would reject the raw list string (stat of // "/d0,/d1" is ENOENT), so validate each root on its own. Distributed diff --git a/mooncake-store/src/file_storage.cpp b/mooncake-store/src/file_storage.cpp index 1e5d6924928..f711f687922 100644 --- a/mooncake-store/src/file_storage.cpp +++ b/mooncake-store/src/file_storage.cpp @@ -28,6 +28,33 @@ namespace mooncake { namespace { +class CpuStreamingTarget final : public ssd_offload::WriteTarget { + public: + explicit CpuStreamingTarget(std::vector destinations) + : destinations_(std::move(destinations)) {} + ssd_offload::Error Write(const ssd_offload::ReadChunk& chunk, + ssd_offload::SlotBuffer buffer) noexcept override { + for (const auto& fragment : chunk.fragments) { + const auto& destination = fragment.destination; + if (destination.destination_index >= destinations_.size()) + return ssd_offload::Error::kInvalidArgument; + const auto& slice = destinations_[destination.destination_index]; + if (destination.offset > slice.size || + destination.length > slice.size - destination.offset || + fragment.buffer_offset > buffer.capacity || + destination.length > buffer.capacity - fragment.buffer_offset) + return ssd_offload::Error::kInvalidArgument; + std::memcpy(static_cast(slice.ptr) + destination.offset, + buffer.data + fragment.buffer_offset, + destination.length); + } + return ssd_offload::Error::kOk; + } + + private: + const std::vector destinations_; +}; + // syncfs for every failure except a data or metadata read: reads leave the // log nothing to write (measured: they alone never shut XFS down), and one // bad file would otherwise flush the whole filesystem on every failed read. @@ -119,12 +146,12 @@ FileStorage::FileStorage(const FileStorageConfig& config, client_(client), ssd_metric_(ssd_metric), local_rpc_addr_(local_rpc_addr), - pinned_buffer_pool_(std::make_unique()), - client_buffer_allocator_(AlignedClientBufferAllocator::create( - config.local_buffer_size, client ? client->GetProtocol() : "")) { + pinned_buffer_pool_(std::make_unique()) { if (!config_.Validate()) { throw std::invalid_argument("Invalid FileStorage configuration"); } + client_buffer_allocator_ = AlignedClientBufferAllocator::create( + config.local_buffer_size, client ? client->GetProtocol() : ""); if (config.pinned_restore_arena_size > 0) { if (config.use_uring) { @@ -156,6 +183,15 @@ FileStorage::FileStorage(const FileStorageConfig& config, } storage_backend_ = create_storage_backend_result.value(); + streaming_bucket_ready_ = config_.streaming_read.enabled && + std::dynamic_pointer_cast( + storage_backend_) != nullptr; +#if !(defined(__linux__) && defined(USE_URING)) + if (streaming_bucket_ready_ && config_.streaming_read.use_uring) { + LOG(WARNING) << "MOONCAKE_OFFLOAD_STREAM_USE_URING is set, but " + "io_uring support is not built in; using pread"; + } +#endif if (auto distributed_backend = std::dynamic_pointer_cast( storage_backend_)) { @@ -219,6 +255,15 @@ FileStorage::~FileStorage() { tl::expected FileStorage::Shutdown() { std::lock_guard lock(shutdown_mutex_); LOG(INFO) << "Shutdown FileStorage..."; + { + std::unique_lock lock(streaming_mutex_); + streaming_stopped_ = true; +#if defined(__linux__) && defined(USE_URING) + streaming_uring_reads_.reset(); + streaming_uring_init_attempted_ = true; +#endif + streaming_reads_.reset(); + } heartbeat_running_ = false; WakeHeartbeat(); if (heartbeat_thread_.joinable()) { @@ -675,6 +720,285 @@ FileStorage::BatchGetLocalRanges(const std::vector& keys, return result; } +bool FileStorage::SupportsLocalStreamingRead() const { + if (!streaming_bucket_ready_) return false; + std::shared_lock lock(streaming_mutex_); + return !streaming_stopped_; +} + +ssd_offload::BoundedExecutor* FileStorage::GetOrCreateStreamingReadsLocked() { + std::lock_guard init_lock(streaming_init_mutex_); + if (!streaming_reads_) { + const auto& stream = config_.streaming_read; + try { + streaming_reads_ = std::make_unique( + stream.read_workers, stream.max_outstanding); + } catch (const std::exception& e) { + LOG(ERROR) << "Failed to initialize local streaming read pool: " + << e.what(); + return nullptr; + } + } + return streaming_reads_.get(); +} + +#if defined(__linux__) && defined(USE_URING) +std::shared_ptr +FileStorage::GetOrCreateStreamingUringReadsLocked() { + std::lock_guard init_lock(streaming_init_mutex_); + if (!streaming_uring_init_attempted_) { + streaming_uring_init_attempted_ = true; + const auto& stream = config_.streaming_read; + streaming_uring_reads_ = ssd_offload::UringReadExecutor::Create( + stream.read_workers, stream.max_outstanding); + } + return streaming_uring_reads_; +} +#endif + +void FileStorage::ReapExpiredClientBuffers() { + auto gc_now = std::chrono::steady_clock::now(); + for (auto& shard : client_buffer_shards_) { + MutexLocker locker(&shard.mutex); + for (auto it = shard.batches.begin(); it != shard.batches.end();) { + if (gc_now >= it->second.lease_timeout) { + it = shard.batches.erase(it); + } else { + ++it; + } + } + } +} + +tl::expected FileStorage::ReadLocalStreaming( + const std::vector& requests) { + using namespace ssd_offload; + if (!streaming_bucket_ready_) + return tl::make_unexpected(ErrorCode::NOT_SUPPORTED); + std::shared_lock lock(streaming_mutex_); + if (streaming_stopped_) + return tl::make_unexpected(ErrorCode::UNAVAILABLE_IN_CURRENT_STATUS); + if (disk_fenced_.load()) + return tl::make_unexpected(ErrorCode::FILE_READ_FAIL); + const auto start = std::chrono::steady_clock::now(); + const auto& config = config_.streaming_read; + auto* buckets = dynamic_cast(storage_backend_.get()); + if (!buckets) return tl::make_unexpected(ErrorCode::NOT_SUPPORTED); + if (!config.Validate(client_buffer_allocator_->size())) + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + if (requests.size() > config.max_fragments) + return tl::make_unexpected(ErrorCode::NO_AVAILABLE_HANDLE); + + std::vector> request_destinations; + request_destinations.reserve(requests.size()); + std::vector all_destinations; + std::vector> intervals; + size_t destination_count = 0; + const auto arena_begin = + reinterpret_cast(client_buffer_allocator_->getBase()); + const auto arena_end = arena_begin + client_buffer_allocator_->size(); + // Validate destinations before opening any bucket files. Overlapping + // destinations return NOT_SUPPORTED so RealClient can fall back to the + // sequential restore path. + for (const auto& request : requests) { + if (request.destinations.size() > + config.max_fragments - destination_count) + return tl::make_unexpected(ErrorCode::NO_AVAILABLE_HANDLE); + destination_count += request.destinations.size(); + std::vector dst_slices; + dst_slices.reserve(request.destinations.size()); + for (const auto& slice : request.destinations) { + if (slice.size && !slice.ptr) + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + const auto begin = reinterpret_cast(slice.ptr); + if (slice.size > std::numeric_limits::max() - begin) + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + const auto end = begin + slice.size; + if (slice.size && begin < arena_end && end > arena_begin) + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + if (slice.size) intervals.emplace_back(begin, end); + const size_t dst_index = all_destinations.size(); + all_destinations.push_back(slice); + dst_slices.push_back({dst_index, 0, slice.size}); + } + request_destinations.push_back(std::move(dst_slices)); + } + std::sort(intervals.begin(), intervals.end()); + for (size_t i = 1; i < intervals.size(); ++i) { + if (intervals[i].first < intervals[i - 1].second) + return tl::make_unexpected(ErrorCode::NOT_SUPPORTED); + } + + // Reserve open-file credits against deduplicated bucket sources before + // opening any descriptors. + struct SourceCredits { + std::atomic& active; + size_t count{0}; + ~SourceCredits() { + if (count) active.fetch_sub(count, std::memory_order_relaxed); + } + } source_credits{active_streaming_sources_}; + + std::vector source_requests; + source_requests.reserve(requests.size()); + for (const auto& request : requests) { + source_requests.push_back({request.storage_key, request.expected_size}); + } + auto acquired = buckets->AcquireReadSources( + source_requests, [&](size_t unique_sources) { + size_t active = + active_streaming_sources_.load(std::memory_order_relaxed); + do { + if (active > config.max_outstanding || + unique_sources > config.max_outstanding - active) + return false; + } while (!active_streaming_sources_.compare_exchange_weak( + active, active + unique_sources, std::memory_order_relaxed)); + source_credits.count = unique_sources; + return true; + }); + if (!acquired) return tl::make_unexpected(acquired.error()); + + std::vector chunk_sources; + ReadPlan batch_plan; + batch_plan.slot_bytes = config.slot_bytes; + batch_plan.alignment = 1; + size_t fragments = 0; + // Preflight the complete batch before writing any destination, merging all + // objects into one multi-source plan so small-object batches read in + // parallel while sharing deduplicated bucket file descriptors. + for (size_t i = 0; i < requests.size(); ++i) { + const auto& loc = acquired->locations[i]; + auto result = BuildReadPlan( + {loc.object_bytes, loc.value_file_offset, requests[i].source_offset, + std::move(request_destinations[i])}, + {config.slot_bytes, 1, config.max_chunks, config.max_fragments}); + if (result.error == Error::kPlanLimit || + result.plan.chunks.size() > + config.max_chunks - batch_plan.chunks.size()) + return tl::make_unexpected(ErrorCode::NO_AVAILABLE_HANDLE); + if (result.error != Error::kOk || + result.plan.payload_bytes > + uint64_t(std::numeric_limits::max()) - + batch_plan.payload_bytes || + result.plan.io_bytes > + std::numeric_limits::max() - batch_plan.io_bytes) + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + for (const auto& chunk : result.plan.chunks) { + if (chunk.fragments.size() > config.max_fragments - fragments) + return tl::make_unexpected(ErrorCode::NO_AVAILABLE_HANDLE); + fragments += chunk.fragments.size(); + } + batch_plan.payload_bytes += result.plan.payload_bytes; + batch_plan.io_bytes += result.plan.io_bytes; + for (auto& chunk : result.plan.chunks) { + batch_plan.chunks.push_back(std::move(chunk)); + chunk_sources.push_back(loc.source_index); + } + } + if (batch_plan.chunks.empty()) return {}; + if (disk_fenced_.load()) + return tl::make_unexpected(ErrorCode::FILE_READ_FAIL); + + const uint64_t payload_bytes = batch_plan.payload_bytes; + std::vector handles; + std::vector buffers; + bool gc_triggered = false; + const size_t desired_slots = + std::min(config.slots, batch_plan.chunks.size()); + for (size_t i = 0; i < desired_slots; ++i) { + auto handle = client_buffer_allocator_->allocate(config.slot_bytes); + if (!handle && !gc_triggered) { + gc_triggered = true; + ReapExpiredClientBuffers(); + handle = client_buffer_allocator_->allocate(config.slot_bytes); + } + if (!handle) { + if (handles.empty()) + return tl::make_unexpected(ErrorCode::BUFFER_OVERFLOW); + // Degrade gracefully to the slots already reserved when concurrent + // remote leases occupy part of the shared staging arena. + break; + } + buffers.push_back( + {static_cast(handle->ptr()), config.slot_bytes}); + handles.push_back(std::move(*handle)); + } + + auto target = + std::make_shared(std::move(all_destinations)); + // Declare ownership before the driver so exceptional unwinding drains the + // driver while its ReadChunk pointers still refer to a live plan. + // Local CPU memcpy runs inline on this scheduler thread (writes == nullptr) + // to avoid spawning a separate write thread pool for local restores. + std::unique_ptr pipeline; + std::unique_ptr driver; +#if defined(__linux__) && defined(USE_URING) + if (config.use_uring) { + auto uring_reads = GetOrCreateStreamingUringReadsLocked(); + if (uring_reads) { + auto native = UringPipelineDriver::Create( + acquired->sources, chunk_sources, target, + std::move(uring_reads), nullptr, buffers); + driver = std::move(native.driver); + } + } +#endif + if (!driver) { + if (config.use_uring) { + LOG_FIRST_N(WARNING, 5) + << "Local streaming io_uring driver unavailable; falling back " + "to pread executor"; + } + auto* reads = GetOrCreateStreamingReadsLocked(); + if (!reads) return tl::make_unexpected(ErrorCode::INTERNAL_ERROR); + driver = std::make_unique( + std::move(acquired->sources), std::move(chunk_sources), target, + *reads, nullptr, buffers.size()); + } + pipeline = + std::make_unique(std::move(batch_plan), buffers, *driver); + const auto start_err = pipeline->Start(); + if (start_err != Error::kOk && !pipeline->inflight()) + return tl::make_unexpected(ErrorCode::FILE_READ_FAIL); + while (pipeline->inflight()) { + IoCompletion completion; + if (!driver->WaitForEvent(completion, std::chrono::seconds(1))) + continue; // A wait timeout never releases an accepted slot. + Error drain_err = Error::kOk; + if (completion.stage == SlotStage::kReading) { + if (completion.result == Error::kIoError && + completion.sys_errno != 0) { + OnDiskError(completion.sys_errno, "read"); + } + drain_err = pipeline->ReadDrained( + completion.token, completion.bytes, completion.result); + } else { + drain_err = + pipeline->WriteDrained(completion.token, completion.result); + } + if (drain_err != Error::kOk) + return tl::make_unexpected(ErrorCode::FILE_READ_FAIL); + } + if (pipeline->state() != PipelineState::kSucceeded) + return tl::make_unexpected(ErrorCode::FILE_READ_FAIL); + if (ssd_metric_) { + const auto elapsed = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start) + .count(); + ssd_metric_->ssd_read_ops.inc(requests.size()); + ssd_metric_->ssd_read_bytes.inc(payload_bytes); + ssd_metric_->ssd_read_latency_us.observe(elapsed); + ssd_metric_->ssd_read_latency_summary.observe(elapsed); + ssd_metric_->ssd_total_ops.inc(requests.size()); + ssd_metric_->ssd_total_bytes.inc(payload_bytes); + ssd_metric_->ssd_total_latency_us.observe(elapsed); + ssd_metric_->ssd_total_latency_summary.observe(elapsed); + } + return {}; +} + bool FileStorage::IsPerBucketSoftOffloadError(ErrorCode error) { return error == ErrorCode::INVALID_READ || error == ErrorCode::OBJECT_ALREADY_EXISTS; @@ -2021,20 +2345,7 @@ FileStorage::AllocateBatch(const std::vector& keys, if (!alloc_result && !gc_triggered && &allocator == client_buffer_allocator_.get()) { gc_triggered = true; - { - auto gc_now = std::chrono::steady_clock::now(); - for (auto& shard : client_buffer_shards_) { - MutexLocker locker(&shard.mutex); - for (auto it = shard.batches.begin(); - it != shard.batches.end();) { - if (gc_now >= it->second.lease_timeout) { - it = shard.batches.erase(it); - } else { - ++it; - } - } - } - } + ReapExpiredClientBuffers(); alloc_result = allocator.allocate(alloc_size); } if (!alloc_result) { diff --git a/mooncake-store/src/offset_allocator.cpp b/mooncake-store/src/offset_allocator.cpp index cfe526e3ad8..b3bd0bb72c2 100644 --- a/mooncake-store/src/offset_allocator.cpp +++ b/mooncake-store/src/offset_allocator.cpp @@ -642,6 +642,29 @@ uint64_t OffsetAllocator::normalizedAllocationSize(size_t size) const { << m_multiplier_bits; } +std::pair OffsetAllocator::slotBudget( + size_t slot_bytes, uint64_t arena_bytes) noexcept { + if (slot_bytes == 0 || arena_bytes == 0) { + return {0, 0}; + } + const uint64_t multiplier_bits = calculateMultiplier(arena_bytes); + const uint64_t quantum = uint64_t{1} << multiplier_bits; + if (slot_bytes > std::numeric_limits::max() - (quantum - 1)) { + return {0, 0}; + } + const uint64_t fake_size = (slot_bytes + quantum - 1) >> multiplier_bits; + if (fake_size > SmallFloat::MAX_BIN_SIZE) { + return {0, 0}; + } + const uint64_t normalized_slot = + static_cast(SmallFloat::floatToUint( + SmallFloat::uintToFloatRoundUp(static_cast(fake_size)))) + << multiplier_bits; + const uint64_t effective_arena = (arena_bytes >> multiplier_bits) + << multiplier_bits; + return {normalized_slot, effective_arena}; +} + OffsetAllocStorageReport OffsetAllocator::storageReport() const { MutexLocker guard(&m_mutex); if (!m_allocator) { diff --git a/mooncake-store/src/real_client.cpp b/mooncake-store/src/real_client.cpp index dc05e7042fd..d7d97e40fd1 100644 --- a/mooncake-store/src/real_client.cpp +++ b/mooncake-store/src/real_client.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include // for dlsym (Python detection) #include // for atexit @@ -43,6 +44,7 @@ #include "config/distributed_storage_config.h" #include "config/rpc_protocol_config.h" #include "store_rpc_client_io_context.h" +#include "offload_read_executor_config.h" #include "bool_parser.h" #include "client_auto_port_config.h" #include "config/cxl_segment_config.h" @@ -90,9 +92,123 @@ DEFINE_int32(http_port, 9300, "(only effective when --enable_http_server=true)."); namespace mooncake { + +class RealClient::OffloadReadThreadPool { + public: + explicit OffloadReadThreadPool(size_t thread_count) : pool_(0) { + const size_t count = std::max(thread_count, 1); + workers_.reserve(count); + try { + for (size_t i = 0; i < count; ++i) { + workers_.emplace_back([this] { pool_.attach(); }); + } + } catch (...) { + Stop(); + throw; + } + } + + ~OffloadReadThreadPool() { Stop(); } + + OffloadReadThreadPool(const OffloadReadThreadPool &) = delete; + OffloadReadThreadPool &operator=(const OffloadReadThreadPool &) = delete; + + asio::thread_pool::executor_type executor() noexcept { + return pool_.get_executor(); + } + + void Stop() noexcept { + pool_.stop(); + for (auto &worker : workers_) { + if (worker.joinable()) { + worker.join(); + } + } + workers_.clear(); + } + + private: + asio::thread_pool pool_; + std::vector workers_; +}; + +RealClient::OffloadReadThreadPool *RealClient::GetOrCreateOffloadReadPool() { + if (auto *fast = offload_read_pool_fast_.load(std::memory_order_acquire)) { + return fast; + } + std::lock_guard lock(offload_read_pool_mutex_); + if (!offload_read_pool_) { + const auto env_value = Environ::Process().Get( + FileStorageEnvironmentVariables::MOONCAKE_OFFLOAD_READ_IO_THREADS + .name); + const char *value = env_value ? env_value->c_str() : nullptr; + const auto configured = detail::ParseOffloadReadIoThreads(value); + const auto threads = + configured.value_or(detail::kDefaultOffloadReadIoThreads); + if (!configured) { + LOG(WARNING) << "Invalid MOONCAKE_OFFLOAD_READ_IO_THREADS; using " + << threads << " threads"; + } + try { + offload_read_pool_ = + std::make_unique(threads); + offload_read_pool_fast_.store(offload_read_pool_.get(), + std::memory_order_release); + } catch (const std::exception &e) { + LOG(ERROR) << "Failed to initialize offload read thread pool: " + << e.what(); + return nullptr; + } + } + return offload_read_pool_.get(); +} + +void RealClient::StopOffloadReadPool() { + std::unique_ptr pool; + { + std::lock_guard lock(offload_read_pool_mutex_); + offload_read_pool_fast_.store(nullptr, std::memory_order_release); + pool = std::move(offload_read_pool_); + } + if (pool) { + pool->Stop(); + } +} + namespace { constexpr std::chrono::seconds kIpcRequestRecvTimeout{5}; +// Unconditionally hops execution back to the caller's executor even if the +// coroutine's cancellation slot was signaled while blocked on a worker thread. +// Unlike async_simple::coro::Yield{}, await_ready() does not short-circuit on +// cancellation so unwinding and coro_rpc cleanup always run on the I/O thread. +struct RescheduleOnExecutor { + async_simple::Executor *executor; + + auto coAwait(async_simple::Executor *) const noexcept { return *this; } + bool await_ready() const noexcept { return executor == nullptr; } + bool await_suspend(std::coroutine_handle<> handle) const noexcept { + return executor->schedule(std::move(handle)); + } + void await_resume() const noexcept {} +}; + +bool CanUseLocalStreamingRestore( + const FileStorage *storage, const std::string &local_rpc_addr, + const std::string &target_rpc_addr, + const RealClient::LocalDiskOffloadObjects &objects) { + if (!storage || local_rpc_addr.empty() || + target_rpc_addr != local_rpc_addr || + !storage->SupportsLocalStreamingRead()) + return false; + auto accelerators = device::GetAcceleratorRegistry().RuntimeAccelerators(); + for (const auto &[key, slices] : objects) + for (const auto &slice : slices) + if (slice.size && accelerators.FindDeviceForPointer(slice.ptr)) + return false; + return true; +} + size_t DivideRoundUp(size_t value, size_t divisor) { return value / divisor + (value % divisor != 0); } @@ -1973,6 +2089,7 @@ tl::expected RealClient::tearDownAll_internal() { offload_rpc_server_->stop(); offload_rpc_server_.reset(); } + StopOffloadReadPool(); std::unique_lock lock(dummy_client_mutex_); { std::lock_guard heartbeat_lock(dummy_heartbeat_mutex_); @@ -5242,9 +5359,42 @@ tl::expected RealClient::execute_ranged_read( void *dst = static_cast(buffer) + dst_offset; std::unordered_map> objects{ {key, {{dst, size}}}}; - if (can_use_pinned_restore_arena(endpoint, objects)) { + bool use_pinned_restore = false; + const bool is_local_owner = + !local_rpc_addr.empty() && endpoint == local_rpc_addr; + if (is_local_owner) { + use_pinned_restore = + can_use_pinned_restore_arena(endpoint, objects); + const bool streaming_enabled = + !use_pinned_restore && file_storage_ && + file_storage_->SupportsLocalStreamingRead(); + if (streaming_enabled) { + RpcDrainGuard::ScopedCall inflight(offload_rpc_drain_); + if (!inflight.ok()) { + return tl::unexpected(ErrorCode::INVALID_PARAMS); + } + if (CanUseLocalStreamingRestore(file_storage_.get(), + local_rpc_addr, endpoint, + objects)) { + const TenantId tenant_id(client_->tenant_id()); + auto result = file_storage_->ReadLocalStreaming({{ + tenant_id.MakeScopedKey(key), + uint64_t(read_range.object_size), + read_range.source_offset, + objects.at(key), + }}); + if (result) return static_cast(size); + if (result.error() != ErrorCode::NO_AVAILABLE_HANDLE && + result.error() != ErrorCode::NOT_SUPPORTED) { + return tl::unexpected(result.error()); + } + } + } + } + if (use_pinned_restore) { auto result = batch_get_into_offload_object_internal( - endpoint, objects, &read_range); + endpoint, objects, &read_range, + /*allow_local_streaming=*/false); if (!result) return tl::unexpected(result.error()); return static_cast(size); } @@ -5254,8 +5404,9 @@ tl::expected RealClient::execute_ranged_read( std::unordered_map> objects; objects.emplace(key, std::vector{ {static_cast(tmp_buf), size}}); - return batch_get_into_offload_object_internal(endpoint, objects, - &read_range); + return batch_get_into_offload_object_internal( + endpoint, objects, &read_range, + /*allow_local_streaming=*/!is_local_owner); }, size); } @@ -9673,7 +9824,12 @@ async_simple::coro::Lazy> RealClient::batch_get_offload_object(const std::vector &keys, const std::vector &sizes) { RpcDrainGuard::ScopedCall inflight(offload_rpc_drain_); - if (!inflight.ok()) { + if (!inflight.ok() || !file_storage_ || !client_) { + co_return tl::unexpected(ErrorCode::INTERNAL_ERROR); + } + + auto *read_pool = GetOrCreateOffloadReadPool(); + if (!read_pool) { co_return tl::unexpected(ErrorCode::INTERNAL_ERROR); } @@ -9684,14 +9840,19 @@ RealClient::batch_get_offload_object(const std::vector &keys, std::vector keys; std::vector sizes; std::shared_ptr file_storage; + std::shared_ptr client; }; auto state = std::make_unique(); state->keys = keys; state->sizes = sizes; state->file_storage = file_storage_; + state->client = client_; auto *s = state.get(); + auto *rpc_exec = co_await async_simple::CurrentExecutor{}; auto try_result = co_await coro_io::post( - [s]() { return s->file_storage->BatchGet(s->keys, s->sizes); }); + [s]() { return s->file_storage->BatchGet(s->keys, s->sizes); }, + read_pool->executor()); + co_await RescheduleOnExecutor{rpc_exec}; auto result = try_result.value(); if (!result) { LOG(ERROR) << "Batch get offload object failed,err_code = " @@ -9700,8 +9861,8 @@ RealClient::batch_get_offload_object(const std::vector &keys, } co_return BatchGetOffloadObjectResponse( result.value().batch_id, std::move(result.value().pointers), - client_->GetSegmentEndpoint(), - file_storage_->config_.client_buffer_gc_ttl_ms); + state->client->GetSegmentEndpoint(), + state->file_storage->config_.client_buffer_gc_ttl_ms); } async_simple::coro::Lazy> @@ -9710,7 +9871,12 @@ RealClient::batch_get_offload_object_ranges( const std::vector &sizes, const std::vector &object_sizes) { RpcDrainGuard::ScopedCall inflight(offload_rpc_drain_); - if (!inflight.ok()) { + if (!inflight.ok() || !file_storage_ || !client_) { + co_return tl::unexpected(ErrorCode::INTERNAL_ERROR); + } + + auto *read_pool = GetOrCreateOffloadReadPool(); + if (!read_pool) { co_return tl::unexpected(ErrorCode::INTERNAL_ERROR); } @@ -9720,6 +9886,7 @@ RealClient::batch_get_offload_object_ranges( std::vector sizes; std::vector object_sizes; std::shared_ptr file_storage; + std::shared_ptr client; }; auto state = std::make_unique(); state->keys = keys; @@ -9727,11 +9894,16 @@ RealClient::batch_get_offload_object_ranges( state->sizes = sizes; state->object_sizes = object_sizes; state->file_storage = file_storage_; + state->client = client_; auto *s = state.get(); - auto try_result = co_await coro_io::post([s]() { - return s->file_storage->BatchGetRanges(s->keys, s->offsets, s->sizes, - s->object_sizes); - }); + auto *rpc_exec = co_await async_simple::CurrentExecutor{}; + auto try_result = co_await coro_io::post( + [s]() { + return s->file_storage->BatchGetRanges(s->keys, s->offsets, + s->sizes, s->object_sizes); + }, + read_pool->executor()); + co_await RescheduleOnExecutor{rpc_exec}; auto result = try_result.value(); if (!result) { LOG(ERROR) << "Batch get offload object range failed, err_code = " @@ -9740,8 +9912,8 @@ RealClient::batch_get_offload_object_ranges( } co_return BatchGetOffloadObjectResponse( result.value().batch_id, std::move(result.value().pointers), - client_->GetSegmentEndpoint(), - file_storage_->config_.client_buffer_gc_ttl_ms); + state->client->GetSegmentEndpoint(), + state->file_storage->config_.client_buffer_gc_ttl_ms); } bool RealClient::release_offload_buffer(uint64_t batch_id) { @@ -9935,8 +10107,8 @@ RealClient::verify_disk_replica(const VerifyDiskReplicaRequest &request) { bool RealClient::can_use_pinned_restore_arena( const std::string &target_rpc_service_addr, const std::unordered_map> &objects) const { - if (!file_storage_ || target_rpc_service_addr != local_rpc_addr || - !file_storage_->HasPinnedRestoreArena()) { + if (local_rpc_addr.empty() || target_rpc_service_addr != local_rpc_addr || + !file_storage_ || !file_storage_->HasPinnedRestoreArena()) { return false; } auto accelerators = device::GetAcceleratorRegistry().RuntimeAccelerators(); @@ -10027,7 +10199,7 @@ tl::expected RealClient::batch_get_into_offload_object_internal( const std::string &target_rpc_service_addr, std::unordered_map> &objects, - const OffloadReadRange *read_range) { + const OffloadReadRange *read_range, bool allow_local_streaming) { std::vector keys; std::vector sizes; if (read_range && objects.size() != 1) { @@ -10061,6 +10233,38 @@ RealClient::batch_get_into_offload_object_internal( sizes.emplace_back(storage_size); } + // Only enter offload_rpc_drain_ locally when actually touching local + // file_storage_ directly (streaming enabled on this client). The fallback + // loopback RPC acquires offload_rpc_drain_ on the server handler itself, + // and default-off paths avoid extra atomic/lock overhead. + if (allow_local_streaming && !local_rpc_addr.empty() && + target_rpc_service_addr == local_rpc_addr && file_storage_ && + file_storage_->SupportsLocalStreamingRead()) { + RpcDrainGuard::ScopedCall local_inflight(offload_rpc_drain_); + if (!local_inflight.ok()) { + return tl::unexpected(ErrorCode::INVALID_PARAMS); + } + if (CanUseLocalStreamingRestore(file_storage_.get(), local_rpc_addr, + target_rpc_service_addr, objects)) { + const TenantId tenant_id(client_->tenant_id()); + std::vector requests; + requests.reserve(keys.size()); + for (size_t i = 0; i < keys.size(); ++i) { + requests.push_back({tenant_id.MakeScopedKey(keys[i]), + read_range + ? uint64_t(read_range->object_size) + : uint64_t(sizes[i]), + read_range ? read_range->source_offset : 0, + objects.at(keys[i])}); + } + auto result = file_storage_->ReadLocalStreaming(requests); + if (result || (result.error() != ErrorCode::NO_AVAILABLE_HANDLE && + result.error() != ErrorCode::NOT_SUPPORTED)) { + return result; + } + } + } + std::vector value_offsets; std::vector object_sizes; const std::vector *offsets_arg = nullptr; diff --git a/mooncake-store/src/ssd_pipeline_io.cpp b/mooncake-store/src/ssd_pipeline_io.cpp new file mode 100644 index 00000000000..0982b7de9cd --- /dev/null +++ b/mooncake-store/src/ssd_pipeline_io.cpp @@ -0,0 +1,265 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include "ssd_pipeline_io.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mooncake::ssd_offload { + +struct BoundedExecutor::Impl { + explicit Impl(size_t count, size_t limit) : limit(limit) { + if (!count || !limit) + throw std::invalid_argument("SSD executor limits must be positive"); + try { + for (size_t i = 0; i < count; ++i) + workers.emplace_back([this] { Work(); }); + } catch (...) { + Shutdown(); + throw; + } + } + void Work() { + for (;;) { + std::function task; + { + std::unique_lock lock(mutex); + changed.wait(lock, [&] { return stopping || !tasks.empty(); }); + if (tasks.empty()) return; + task = std::move(tasks.front()); + tasks.pop(); + } + // I/O tasks encode their errors in completions. Keep this executor + // alive if a callback unexpectedly throws. + try { + task(); + } catch (...) { + } + task = {}; + { + std::lock_guard lock(mutex); + --pending; + changed.notify_all(); + } + } + } + bool WaitSubmit(std::function task) noexcept { + if (!task) return false; + try { + std::unique_lock lock(mutex); + changed.wait(lock, [&] { return stopping || pending < limit; }); + if (stopping) return false; + tasks.push(std::move(task)); + ++pending; + changed.notify_all(); + return true; + } catch (...) { + return false; + } + } + void Shutdown() { + std::lock_guard serial(shutdown_mutex); + { + std::lock_guard lock(mutex); + stopping = true; + changed.notify_all(); + } + for (auto& worker : workers) + if (worker.joinable()) worker.join(); + } + size_t limit, pending{0}; + bool stopping{false}; + mutable std::mutex mutex; + std::mutex shutdown_mutex; + std::condition_variable changed; + std::queue> tasks; + std::vector workers; +}; + +BoundedExecutor::BoundedExecutor(size_t workers, size_t max_outstanding) + : impl_(std::make_unique(workers, max_outstanding)) {} +BoundedExecutor::~BoundedExecutor() { Shutdown(); } +bool BoundedExecutor::WaitSubmit(std::function task) noexcept { + return impl_->WaitSubmit(std::move(task)); +} +void BoundedExecutor::Shutdown() { impl_->Shutdown(); } + +struct ThreadedPipelineDriver::Impl { + enum class State { kIdle, kRunning, kReady }; + struct Record { + State state{State::kIdle}; + IoCompletion event; + }; + Impl(std::vector> sources, + std::vector chunk_sources, std::shared_ptr target, + BoundedExecutor& reads, BoundedExecutor* writes, size_t count) + : sources(std::move(sources)), + chunk_sources(std::move(chunk_sources)), + target(std::move(target)), + reads(reads), + writes(writes), + records(count) { + if (this->sources.empty() || + std::any_of(this->sources.begin(), this->sources.end(), + [](const auto& source) { return !source; }) || + this->chunk_sources.empty() || + std::any_of(this->chunk_sources.begin(), this->chunk_sources.end(), + [&](size_t source) { + return source >= this->sources.size(); + }) || + !this->target || !count) + throw std::invalid_argument( + "SSD I/O driver requires valid sources, mapping, target and " + "slots"); + } + ~Impl() { + std::unique_lock lock(mutex); + stopping = true; + changed.wait(lock, [&] { return running == 0; }); + } + bool Submit(const SlotToken& token, const ReadChunk& chunk, + SlotBuffer buffer, SlotStage stage) noexcept { + if (!token.generation || token.slot_index >= records.size() || + !buffer.data || !chunk.read_bytes || + chunk.read_bytes > buffer.capacity || + token.chunk_index >= chunk_sources.size()) + return false; + if (stage == SlotStage::kWriting && writes == nullptr) { + { + std::lock_guard lock(mutex); + auto& record = records[token.slot_index]; + if (stopping || record.state != State::kIdle) return false; + record.event = {token, stage, 0, Error::kOk}; + record.state = State::kRunning; + } + const auto result = target->Write(chunk, buffer); + std::lock_guard lock(mutex); + auto& record = records[token.slot_index]; + record.event.result = result; + record.event.bytes = result == Error::kOk ? chunk.payload_bytes : 0; + record.state = State::kReady; + changed.notify_all(); + return true; + } + std::shared_ptr source; + if (stage == SlotStage::kReading) + source = sources[chunk_sources[token.chunk_index]]; + { + std::lock_guard lock(mutex); + auto& record = records[token.slot_index]; + if (stopping || record.state != State::kIdle) return false; + record.event = {token, stage, 0, Error::kOk}; + record.state = State::kRunning; + ++running; + } + bool accepted = false; + try { + const size_t read_bytes = chunk.read_bytes; + const uint64_t file_offset = chunk.file_offset; + auto task = [this, token, stage, buffer, read_bytes, file_offset, + chunk_ptr = &chunk, + source = std::move(source)]() mutable { + IoCompletion event{token, stage, 0, Error::kOk}; + if (stage == SlotStage::kReading) { + const auto result = + source->ReadAt({buffer.data, read_bytes}, file_offset); + event.bytes = result.bytes; + event.result = result.error; + event.sys_errno = result.sys_errno; + } else { + event.result = target->Write(*chunk_ptr, buffer); + event.bytes = event.result == Error::kOk + ? chunk_ptr->payload_bytes + : 0; + } + source.reset(); + // Notify under mutex so destructor drain cannot race a late + // notify(). + std::lock_guard lock(mutex); + auto& record = records[token.slot_index]; + record.event = event; + record.state = State::kReady; + --running; + changed.notify_all(); + }; + accepted = (stage == SlotStage::kReading ? reads : *writes) + .WaitSubmit(std::move(task)); + } catch (...) { + } + if (!accepted) { + std::lock_guard lock(mutex); + records[token.slot_index].state = State::kIdle; + --running; + changed.notify_all(); + } + return accepted; + } + bool Wait(IoCompletion& event, std::chrono::milliseconds timeout) { + const auto start = std::chrono::steady_clock::now(); + const auto clamped = + std::max(timeout, std::chrono::milliseconds::zero()); + const auto max_ms = + std::chrono::duration_cast( + std::chrono::steady_clock::time_point::max() - start); + const auto until = clamped >= max_ms + ? std::chrono::steady_clock::time_point::max() + : start + clamped; + std::unique_lock lock(mutex); + auto ready = [&] { + return std::find_if(records.begin(), records.end(), + [](const auto& record) { + return record.state == State::kReady; + }); + }; + if (!changed.wait_until(lock, until, [&] { + return ready() != records.end() || running == 0; + })) + return false; + auto found = ready(); + if (found == records.end()) return false; + event = found->event; + found->state = State::kIdle; + return true; + } + const std::vector> sources; + const std::vector chunk_sources; + std::shared_ptr target; + BoundedExecutor& reads; + BoundedExecutor* writes; + std::vector records; + std::mutex mutex; + std::condition_variable changed; + size_t running{0}; + bool stopping{false}; +}; + +ThreadedPipelineDriver::ThreadedPipelineDriver( + std::vector> sources, + std::vector chunk_sources, std::shared_ptr target, + BoundedExecutor& reads, BoundedExecutor* writes, size_t slot_count) + : impl_(std::make_unique(std::move(sources), std::move(chunk_sources), + std::move(target), reads, writes, + slot_count)) {} +ThreadedPipelineDriver::~ThreadedPipelineDriver() = default; +bool ThreadedPipelineDriver::SubmitRead(const SlotToken& token, + const ReadChunk& chunk, + SlotBuffer buffer) noexcept { + return impl_->Submit(token, chunk, buffer, SlotStage::kReading); +} +bool ThreadedPipelineDriver::SubmitWrite(const SlotToken& token, + const ReadChunk& chunk, + SlotBuffer buffer) noexcept { + return impl_->Submit(token, chunk, buffer, SlotStage::kWriting); +} +bool ThreadedPipelineDriver::WaitForEvent(IoCompletion& event, + std::chrono::milliseconds timeout) { + return impl_->Wait(event, timeout); +} + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/src/ssd_read_pipeline.cpp b/mooncake-store/src/ssd_read_pipeline.cpp new file mode 100644 index 00000000000..8e80c2a3255 --- /dev/null +++ b/mooncake-store/src/ssd_read_pipeline.cpp @@ -0,0 +1,326 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include "ssd_read_pipeline.h" + +#include +#include +#include +#include +#include + +namespace mooncake::ssd_offload { +namespace { + +constexpr uint64_t kMaxFileOffset = std::numeric_limits::max(); + +bool ValidShape(size_t slot_bytes, size_t alignment) { + return alignment != 0 && (alignment & (alignment - 1)) == 0 && + slot_bytes != 0 && slot_bytes % alignment == 0 && + slot_bytes <= kMaxFileOffset; +} + +bool Add(uint64_t& total, uint64_t amount) { + if (amount > std::numeric_limits::max() - total) return false; + total += amount; + return true; +} + +bool DisjointDestinations(std::vector& destinations) { + std::sort(destinations.begin(), destinations.end(), + [](const auto& left, const auto& right) { + return std::tie(left.destination_index, left.offset) < + std::tie(right.destination_index, right.offset); + }); + for (size_t i = 1; i < destinations.size(); ++i) { + const auto& previous = destinations[i - 1]; + const auto& current = destinations[i]; + if (previous.destination_index == current.destination_index && + current.offset < previous.offset + previous.length) + return false; + } + return true; +} + +} // namespace + +PlanResult BuildReadPlan(const ObjectRead& object, PlanOptions options) { + auto fail = [](Error error) { return PlanResult{error, {}}; }; + if (!ValidShape(options.slot_bytes, options.alignment) || + options.max_chunks == 0 || options.max_fragments == 0) + return fail(Error::kInvalidArgument); + + std::vector destinations; + uint64_t range_bytes = 0; + for (const auto& destination : object.destinations) { + if (destination.length == 0) continue; + if (destination.length > UINT64_MAX - destination.offset) + return fail(Error::kOverflow); + if (destinations.size() == options.max_fragments) + return fail(Error::kPlanLimit); + if (!Add(range_bytes, destination.length)) + return fail(Error::kOverflow); + destinations.push_back(destination); + } + if (!DisjointDestinations(destinations)) + return fail(Error::kInvalidArgument); + if (object.source_offset > object.object_bytes || + range_bytes > object.object_bytes - object.source_offset) + return fail(Error::kInvalidArgument); + + ReadPlan plan; + plan.slot_bytes = options.slot_bytes; + plan.alignment = options.alignment; + plan.payload_bytes = range_bytes; + if (range_bytes == 0) return {Error::kOk, std::move(plan)}; + + if (object.value_file_offset > kMaxFileOffset || + object.source_offset > kMaxFileOffset - object.value_file_offset) + return fail(Error::kOverflow); + uint64_t position = object.value_file_offset + object.source_offset; + if (range_bytes > kMaxFileOffset - position) return fail(Error::kOverflow); + + size_t fragment_count = 0; + uint64_t remaining = range_bytes; + uint64_t source_offset = object.source_offset; + size_t destination_cursor = 0; + uint64_t destination_consumed = 0; + while (remaining != 0) { + if (plan.chunks.size() == options.max_chunks) + return fail(Error::kPlanLimit); + const uint64_t file_offset = + position & ~(static_cast(options.alignment) - 1); + const size_t head = static_cast(position - file_offset); + const size_t payload = static_cast( + std::min(remaining, options.slot_bytes - head)); + const size_t used = head + payload; + const size_t read_bytes = + (used / options.alignment + (used % options.alignment != 0)) * + options.alignment; + if (read_bytes > kMaxFileOffset - file_offset || + !Add(plan.io_bytes, read_bytes)) + return fail(Error::kOverflow); + ReadChunk chunk{source_offset, file_offset, read_bytes, + head, payload, {}}; + size_t fragment_remaining = payload; + size_t buffer_offset = head; + while (fragment_remaining != 0) { + const auto& destination = object.destinations[destination_cursor]; + const uint64_t available = + destination.length - destination_consumed; + if (available == 0) { + ++destination_cursor; + destination_consumed = 0; + continue; + } + const auto length = static_cast( + std::min(fragment_remaining, available)); + auto fragment_destination = destination; + fragment_destination.offset += destination_consumed; + fragment_destination.length = length; + if (fragment_count == options.max_fragments) + return fail(Error::kPlanLimit); + ++fragment_count; + chunk.fragments.push_back({buffer_offset, fragment_destination}); + buffer_offset += length; + fragment_remaining -= length; + destination_consumed += length; + } + plan.chunks.push_back(std::move(chunk)); + remaining -= payload; + position += payload; + source_offset += payload; + } + return {Error::kOk, std::move(plan)}; +} + +UringReadStep ClassifyUringReadResult(int completed, size_t done, + size_t requested, unsigned retries, + unsigned max_retries) noexcept { + if (done >= requested) { + return {false, done, retries, Error::kIoError, 0}; + } + if (completed == -EINTR || completed == -EAGAIN) { + if (retries < max_retries) { + return {true, done, retries + 1, Error::kOk, 0}; + } + return {false, done, retries, Error::kIoError, -completed}; + } + if (completed < 0) { + const int sys_errno = + completed > std::numeric_limits::min() ? -completed : 0; + return {false, done, retries, Error::kIoError, sys_errno}; + } + if (completed == 0) { + return {false, done, retries, Error::kOk, 0}; + } + const auto got = static_cast(completed); + if (got > requested - done) { + return {false, done, retries, Error::kIoError, 0}; + } + const size_t next_done = done + got; + if (next_done < requested) { + return {true, next_done, 0, Error::kOk, 0}; + } + return {false, next_done, 0, Error::kOk, 0}; +} + +ReadPipeline::ReadPipeline(ReadPlan plan, std::vector buffers, + PipelineDriver& driver) + : plan_(std::move(plan)), driver_(driver) { + for (const auto buffer : buffers) slots_.push_back({buffer}); +} + +Error ReadPipeline::Validate() const { + if (!ValidShape(plan_.slot_bytes, plan_.alignment)) + return Error::kInvalidArgument; + uint64_t payload_bytes = 0, io_bytes = 0; + for (const auto& chunk : plan_.chunks) { + if (chunk.read_bytes == 0 || chunk.read_bytes > plan_.slot_bytes || + chunk.read_bytes % plan_.alignment != 0 || + chunk.file_offset % plan_.alignment != 0 || + chunk.file_offset > kMaxFileOffset || + chunk.read_bytes > kMaxFileOffset - chunk.file_offset || + chunk.payload_bytes == 0 || + chunk.payload_offset > chunk.read_bytes || + chunk.payload_bytes > chunk.read_bytes - chunk.payload_offset) + return Error::kInvalidArgument; + size_t cursor = chunk.payload_offset; + const size_t end = cursor + chunk.payload_bytes; + for (const auto& fragment : chunk.fragments) { + const auto& destination = fragment.destination; + if (fragment.buffer_offset != cursor || destination.length == 0 || + destination.length > UINT64_MAX - destination.offset || + destination.length > end - cursor) + return Error::kInvalidArgument; + cursor += static_cast(destination.length); + } + if (cursor != end || !Add(payload_bytes, chunk.payload_bytes) || + !Add(io_bytes, chunk.read_bytes)) + return Error::kInvalidArgument; + } + if (payload_bytes != plan_.payload_bytes || io_bytes != plan_.io_bytes) + return Error::kInvalidArgument; + if (plan_.chunks.empty()) return Error::kOk; + if (slots_.empty()) return Error::kInvalidArgument; + for (size_t i = 0; i < slots_.size(); ++i) { + const auto& buffer = slots_[i].buffer; + const auto base = reinterpret_cast(buffer.data); + if (!buffer.data || buffer.capacity < plan_.slot_bytes || + base % plan_.alignment != 0 || + plan_.slot_bytes > std::numeric_limits::max() - base) + return Error::kInvalidArgument; + for (size_t j = 0; j < i; ++j) { + const auto other = + reinterpret_cast(slots_[j].buffer.data); + if (base < other + plan_.slot_bytes && + other < base + plan_.slot_bytes) + return Error::kInvalidArgument; + } + } + return Error::kOk; +} + +Error ReadPipeline::Start() { + if (state_ != PipelineState::kReady) return Error::kInvalidState; + const auto validation = Validate(); + if (validation != Error::kOk) { + Abort(validation); + return validation; + } + state_ = PipelineState::kRunning; + Pump(); + return error_; +} + +SlotToken ReadPipeline::Token(size_t slot_index) const { + const auto& slot = slots_[slot_index]; + return {slot_index, slot.generation, slot.chunk_index}; +} + +bool ReadPipeline::Matches(const SlotToken& token, SlotStage stage) const { + if (token.slot_index >= slots_.size()) return false; + const auto& slot = slots_[token.slot_index]; + return slot.stage == stage && slot.generation == token.generation && + slot.chunk_index == token.chunk_index; +} + +void ReadPipeline::Pump() { + for (size_t i = 0; i < slots_.size() && state_ == PipelineState::kRunning && + next_chunk_ < plan_.chunks.size(); + ++i) { + auto& slot = slots_[i]; + if (slot.stage != SlotStage::kFree) continue; + if (slot.generation == UINT64_MAX) { + Abort(Error::kOverflow); + break; + } + ++slot.generation; + slot.chunk_index = next_chunk_++; + slot.stage = SlotStage::kReading; + ++inflight_; + if (!driver_.SubmitRead(Token(i), plan_.chunks[slot.chunk_index], + slot.buffer)) { + Release(i); + Abort(Error::kIoError); + } + } + UpdateTerminal(); +} + +void ReadPipeline::Abort(Error error) { + if (error_ != Error::kOk) return; + error_ = error; + state_ = PipelineState::kDraining; + UpdateTerminal(); +} + +void ReadPipeline::Release(size_t slot_index) { + slots_[slot_index].stage = SlotStage::kFree; + --inflight_; +} + +void ReadPipeline::UpdateTerminal() { + if (inflight_ != 0) return; + if (error_ != Error::kOk) { + state_ = PipelineState::kFailed; + } else if (state_ == PipelineState::kRunning && + completed_chunks_ == plan_.chunks.size()) { + state_ = PipelineState::kSucceeded; + } +} + +Error ReadPipeline::ReadDrained(const SlotToken& token, size_t bytes_read, + Error result) { + if (!Matches(token, SlotStage::kReading)) return Error::kStaleEvent; + auto& slot = slots_[token.slot_index]; + const auto& chunk = plan_.chunks[slot.chunk_index]; + if (state_ == PipelineState::kDraining) { + Release(token.slot_index); + } else if (result != Error::kOk || + bytes_read < chunk.payload_offset + chunk.payload_bytes || + bytes_read > chunk.read_bytes) { + Release(token.slot_index); + Abort(Error::kIoError); + } else { + slot.stage = SlotStage::kWriting; + if (!driver_.SubmitWrite(token, chunk, slot.buffer)) { + Release(token.slot_index); + Abort(Error::kTransferError); + } + } + Pump(); + return Error::kOk; +} + +Error ReadPipeline::WriteDrained(const SlotToken& token, Error result) { + if (!Matches(token, SlotStage::kWriting)) return Error::kStaleEvent; + if (result == Error::kOk) { + ++completed_chunks_; + } + Release(token.slot_index); + if (result != Error::kOk) Abort(Error::kTransferError); + Pump(); + return Error::kOk; +} + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/src/ssd_read_source.cpp b/mooncake-store/src/ssd_read_source.cpp new file mode 100644 index 00000000000..75142a685f5 --- /dev/null +++ b/mooncake-store/src/ssd_read_source.cpp @@ -0,0 +1,95 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include "ssd_read_source.h" + +#include +#include +#include +#include +#include +#include + +namespace mooncake::ssd_offload { +namespace { + +class ScopedFd { + public: + explicit ScopedFd(int fd) : fd_(fd) {} + ~ScopedFd() { + if (fd_ >= 0) close(fd_); + } + int get() const { return fd_; } + void Release() { fd_ = -1; } + + private: + int fd_; +}; + +class PosixReadSource final : public ReadSource { + public: + PosixReadSource(int fd, uint64_t file_bytes, std::shared_ptr lifetime) + : fd_(fd), file_bytes_(file_bytes), lifetime_(std::move(lifetime)) {} + ~PosixReadSource() override { close(fd_); } + uint64_t file_bytes() const noexcept override { return file_bytes_; } + std::optional native_read_fd() const noexcept override { return fd_; } + ReadResult ReadAt(std::span buffer, + uint64_t file_offset) noexcept override { + constexpr uint64_t max_offset = std::numeric_limits::max(); + if (file_offset > max_offset || + buffer.size() > max_offset - file_offset || + buffer.size() > + static_cast(std::numeric_limits::max())) + return {0, Error::kOverflow}; + if (!buffer.empty() && !buffer.data()) + return {0, Error::kInvalidArgument}; + size_t bytes = 0; + while (bytes < buffer.size()) { + const auto result = + pread(fd_, buffer.data() + bytes, buffer.size() - bytes, + static_cast(file_offset + bytes)); + if (result < 0) { + if (errno == EINTR) continue; + return {bytes, Error::kIoError, errno}; + } + if (result == 0) break; + bytes += static_cast(result); + } + return {bytes, Error::kOk}; + } + + private: + int fd_; + const uint64_t file_bytes_; + std::shared_ptr lifetime_; +}; + +} // namespace + +ReadSourceResult OpenPosixReadSource(const std::string& path, + uint64_t min_file_bytes, + std::shared_ptr lifetime) { + constexpr uint64_t max_offset = std::numeric_limits::max(); + if (min_file_bytes > max_offset) return {Error::kOverflow, {}}; + + int raw_fd = -1; + do { + raw_fd = + open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK); + } while (raw_fd < 0 && errno == EINTR); + ScopedFd fd(raw_fd); + if (fd.get() < 0) return {Error::kIoError, {}, errno}; + struct stat metadata{}; + if (fstat(fd.get(), &metadata) != 0) return {Error::kIoError, {}, errno}; + if (!S_ISREG(metadata.st_mode) || metadata.st_size < 0 || + min_file_bytes > static_cast(metadata.st_size)) + return {Error::kInvalidArgument, {}}; + const int status = fcntl(fd.get(), F_GETFL); + if (status < 0 || fcntl(fd.get(), F_SETFL, status & ~O_NONBLOCK) < 0) + return {Error::kIoError, {}, errno}; + auto source = std::make_shared( + fd.get(), static_cast(metadata.st_size), std::move(lifetime)); + fd.Release(); + return {Error::kOk, std::move(source)}; +} + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/src/ssd_uring_pipeline.cpp b/mooncake-store/src/ssd_uring_pipeline.cpp new file mode 100644 index 00000000000..7a003c0d660 --- /dev/null +++ b/mooncake-store/src/ssd_uring_pipeline.cpp @@ -0,0 +1,759 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include "ssd_uring_pipeline.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mooncake::ssd_offload { +namespace { + +void FreeUringProbe(io_uring_probe* probe) noexcept { + // liburing < 2.0 (e.g., EL8 liburing 1.0.7) allocates probes via calloc() + // and does not provide io_uring_free_probe(). +#if defined(IO_URING_VERSION_MAJOR) && IO_URING_VERSION_MAJOR >= 2 + io_uring_free_probe(probe); +#else + std::free(probe); +#endif +} + +bool RingSupportsOpcode(io_uring& ring, int opcode) noexcept { + io_uring_probe* probe = io_uring_get_probe_ring(&ring); + if (!probe) return false; + const bool supported = io_uring_opcode_supported(probe, opcode) != 0; + FreeUringProbe(probe); + return supported; +} + +std::chrono::steady_clock::time_point ClampedDeadline( + std::chrono::milliseconds timeout) noexcept { + const auto start = std::chrono::steady_clock::now(); + const auto clamped = std::max(timeout, std::chrono::milliseconds::zero()); + const auto max_ms = std::chrono::duration_cast( + std::chrono::steady_clock::time_point::max() - start); + return clamped >= max_ms ? std::chrono::steady_clock::time_point::max() + : start + clamped; +} + +} // namespace + +struct UringReadExecutor::Impl { + static constexpr unsigned kMaxReadRetries = 3; + + struct Operation { + std::shared_ptr source; + int fd; + std::span buffer; + uint64_t offset; + Completion completion; + uint64_t id{0}; + unsigned retries{0}; + size_t done{0}; + bool submitted{false}; + }; + + struct Worker { + explicit Worker(size_t depth) : active(depth) {} + ~Worker() { + if (initialized) io_uring_queue_exit(&ring); + if (signal >= 0) close(signal); + } + bool Init() { + const int init_rc = + io_uring_queue_init(unsigned(active.size()), &ring, 0); + if (init_rc < 0) { + LOG(WARNING) + << "io_uring_queue_init failed (errno=" << -init_rc << ")"; + return false; + } + initialized = true; + if (!RingSupportsOpcode(ring, IORING_OP_READ)) { + LOG(WARNING) << "io_uring does not support IORING_OP_READ"; + return false; + } + // Exercise io_uring_enter upfront so seccomp policies that allow + // setup/register but block io_uring_enter fail Create() cleanly. + auto* sqe = io_uring_get_sqe(&ring); + if (!sqe) return false; + io_uring_prep_nop(sqe); + int enter_rc; + do { + enter_rc = io_uring_submit_and_wait(&ring, 1); + } while (enter_rc == -EINTR); + if (enter_rc < 0) { + LOG(WARNING) + << "io_uring_enter NOP probe failed (errno=" << -enter_rc + << ")"; + return false; + } + io_uring_cqe* cqe = nullptr; + if (io_uring_peek_cqe(&ring, &cqe) != 0) { + LOG(WARNING) << "io_uring NOP probe produced no CQE"; + return false; + } + const int nop_res = cqe->res; + io_uring_cqe_seen(&ring, cqe); + if (nop_res < 0) { + LOG(WARNING) + << "io_uring NOP probe failed (errno=" << -nop_res << ")"; + return false; + } + signal = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); + if (signal < 0) { + LOG(WARNING) + << "eventfd failed for UringReadExecutor (errno=" << errno + << ")"; + return false; + } + return true; + } + bool Wake() const noexcept { + uint64_t one = 1; + ssize_t result; + do { + result = ::write(signal, &one, sizeof(one)); + } while (result < 0 && errno == EINTR); + return result == ssize_t(sizeof(one)) || + (result < 0 && errno == EAGAIN); + } + + io_uring ring{}; + int signal{-1}; + bool initialized{false}; + bool submit_broken{false}; + bool ring_poll_broken{false}; + bool signal_broken{false}; + int broken_errno{0}; + uint64_t next_id{0}; + std::deque> queued; // executor mutex + std::vector> active; // ring owner only + std::deque pending_submit; // ring owner only + std::thread thread; + }; + + explicit Impl(size_t limit) : limit(limit) {} + ~Impl() { Shutdown(); } + + bool Init(size_t count) { + const size_t depth = std::min(size_t{32}, (limit + count - 1) / count); + for (size_t i = 0; i < count; ++i) { + auto worker = std::make_unique(depth); + if (!worker->Init()) return false; + workers.push_back(std::move(worker)); + } + for (auto& worker : workers) { + worker->thread = + std::thread([this, ptr = worker.get()] { Work(*ptr); }); + } + return true; + } + + void Fail(const char* reason, int err = 0) noexcept { + bool latched = false; + { + std::lock_guard lock(mutex); + if (!failed) { + failed = stopping = true; + failure_errno = err; + latched = true; + credit.notify_all(); + for (auto& worker : workers) (void)worker->Wake(); + } + } + if (latched) { + LOG(WARNING) << "UringReadExecutor disabled (" << reason + << ", errno=" << err + << "); subsequent streaming reads will fall back to " + "pread"; + } + } + + bool Submit(std::unique_ptr operation) { + Worker* worker; + { + std::unique_lock lock(mutex); + credit.wait(lock, [&] { return stopping || pending < limit; }); + if (stopping || pending == limit) return false; + worker = workers[next_worker].get(); + worker->queued.push_back(std::move(operation)); + // Enqueue is the acceptance point. A later wake failure cannot + // authorize the caller to release or retry this buffer. + ++pending; + next_worker = (next_worker + 1) % workers.size(); + } + if (!worker->Wake()) Fail("eventfd wake failed", errno); + return true; + } + + void Complete(std::unique_ptr operation, ReadResult result) { + operation->source.reset(); + try { + operation->completion(result); + } catch (...) { + } + operation.reset(); + std::lock_guard lock(mutex); + --pending; + credit.notify_all(); + } + + void PrepareRead(Worker& worker, io_uring_sqe* sqe, Operation& op) { + // A new ID distinguishes this submission from a retired CQE. + op.id = ++worker.next_id; + op.submitted = false; + io_uring_prep_read(sqe, op.fd, op.buffer.data() + op.done, + unsigned(op.buffer.size() - op.done), + op.offset + op.done); + sqe->user_data = op.id; + worker.pending_submit.push_back(&op); + } + + void FailUnsubmittedActive(Worker& worker, int err) { + worker.pending_submit.clear(); + for (auto& slot : worker.active) { + if (!slot || slot->submitted) continue; + const size_t done = slot->done; + Complete(std::move(slot), {done, Error::kIoError, err}); + } + } + + static bool HasActiveOps(const Worker& worker) noexcept { + return std::any_of(worker.active.begin(), worker.active.end(), + [](const auto& op) { return bool(op); }); + } + + bool Harvest(Worker& worker) { + if (!worker.initialized) return false; + bool prepared_retry = false; + io_uring_cqe* cqe = nullptr; + while (io_uring_peek_cqe(&worker.ring, &cqe) == 0) { + const auto id = cqe->user_data; + const int completed = cqe->res; + io_uring_cqe_seen(&worker.ring, cqe); + auto found = std::find_if( + worker.active.begin(), worker.active.end(), + [id](const auto& op) { return op && op->id == id; }); + if (found == worker.active.end()) { + Fail("unexpected cqe user_data"); + worker.submit_broken = true; + FailUnsubmittedActive(worker, worker.broken_errno); + continue; + } + auto& op = **found; + const auto step = + ClassifyUringReadResult(completed, op.done, op.buffer.size(), + op.retries, kMaxReadRetries); + op.done = step.next_done; + op.retries = step.next_retries; + Error error = step.error; + int sys_errno = step.sys_errno; + if (step.retry) { + bool id_exhausted = false; + bool requeued = false; + { + std::lock_guard lock(mutex); + if (!failed && !worker.submit_broken) { + if (worker.next_id == UINT64_MAX) { + id_exhausted = true; + } else if (auto* sqe = io_uring_get_sqe(&worker.ring)) { + PrepareRead(worker, sqe, op); + prepared_retry = true; + continue; + } else { + // SQ ring is temporarily full; push back to the + // front of queued so the next Flush/Prepare cycle + // retries without failing the read spuriously. + (*found)->submitted = false; + worker.queued.push_front(std::move(*found)); + requeued = true; + } + } + } + if (requeued) { + prepared_retry = true; + continue; + } + if (id_exhausted) Fail("sqe id exhausted"); + error = Error::kIoError; + sys_errno = sys_errno ? sys_errno : worker.broken_errno; + } + Complete(std::move(*found), {op.done, error, sys_errno}); + } + return prepared_retry; + } + + void Prepare(Worker& worker) { + if (!worker.initialized || worker.submit_broken) return; + bool id_exhausted = false; + for (auto& active : worker.active) { + if (active) continue; + std::lock_guard lock(mutex); + if (failed || worker.queued.empty()) break; + if (worker.next_id == UINT64_MAX) { + id_exhausted = true; + break; + } + auto* sqe = io_uring_get_sqe(&worker.ring); + if (!sqe) break; + active = std::move(worker.queued.front()); + worker.queued.pop_front(); + // IDs live in the worker's ring domain across all requests. + PrepareRead(worker, sqe, *active); + } + if (id_exhausted) Fail("sqe id exhausted"); + } + + void Flush(Worker& worker) { + if (!worker.initialized || worker.submit_broken) return; + for (unsigned attempt = 0; + attempt < 4 && io_uring_sq_ready(&worker.ring); ++attempt) { + const int result = io_uring_submit(&worker.ring); + if (result > 0) { + const size_t accepted = std::min(static_cast(result), + worker.pending_submit.size()); + for (size_t i = 0; i < accepted; ++i) { + worker.pending_submit.front()->submitted = true; + worker.pending_submit.pop_front(); + } + continue; // Includes partial submissions. + } + if (result < 0 && result != -EINTR && result != -EAGAIN && + result != -ENOMEM && result != -EBUSY) { + worker.submit_broken = true; + if (worker.broken_errno == 0) worker.broken_errno = -result; + Fail("io_uring_submit failed", -result); + // Any SQEs still in pending_submit were never accepted by the + // kernel; fail them immediately, while keeping + // already-submitted operations pinned until their CQEs arrive + // so kernel DMA/io-wq never writes into freed caller staging + // buffers. + FailUnsubmittedActive(worker, -result); + } + break; + } + } + + void Work(Worker& worker) { + for (;;) { + Harvest(worker); + // Only queued operations have never been prepared or published. + // A permanent failure can safely complete these with an error. + for (;;) { + std::unique_ptr rejected; + int err = 0; + { + std::lock_guard lock(mutex); + if (!failed || worker.queued.empty()) break; + rejected = std::move(worker.queued.front()); + worker.queued.pop_front(); + err = worker.broken_errno ? worker.broken_errno + : failure_errno; + } + Complete(std::move(rejected), {0, Error::kIoError, err}); + } + Prepare(worker); + Flush(worker); + if (Harvest(worker)) continue; + bool idle = false; + { + std::lock_guard lock(mutex); + idle = !HasActiveOps(worker); + if (stopping && worker.queued.empty() && idle) return; + if (failed && !worker.queued.empty()) continue; + if (!failed && !worker.submit_broken && + !worker.queued.empty() && + std::any_of( + worker.active.begin(), worker.active.end(), + [](const auto& operation) { return !operation; }) && + io_uring_sq_space_left(&worker.ring)) + continue; + } + if (worker.ring_poll_broken) { + // Keep harvesting CQEs directly from the shared CQ ring until + // every already-submitted kernel I/O completes; never tear down + // the ring or release buffers while submitted ops remain. + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + continue; + } + pollfd wake[] = { + {worker.initialized ? worker.ring.ring_fd : -1, POLLIN, 0}, + {worker.signal_broken ? -1 : worker.signal, POLLIN, 0}}; + // When completely idle with no queued or active SQEs, block in + // poll() without periodic wakeups until eventfd signals new work or + // shutdown. Keep a 1 ms retry poll when SQEs are pending submission + // under transient backpressure, and a 100 ms safety net while I/O + // is in flight. + int timeout_ms = -1; + if (!worker.submit_broken && worker.initialized && + io_uring_sq_ready(&worker.ring)) { + timeout_ms = 1; + } else if (!idle) { + timeout_ms = 100; + } + const int result = poll(wake, 2, timeout_ms); + if (result < 0) { + if (errno == EINTR) continue; + const int err = errno; + worker.submit_broken = true; + worker.ring_poll_broken = true; + if (worker.broken_errno == 0) worker.broken_errno = err; + Fail("poll failed", err); + FailUnsubmittedActive(worker, err); + continue; + } + if (result > 0) { + const bool ring_err = + (wake[0].revents & (POLLERR | POLLHUP | POLLNVAL)) != 0; + const bool sig_err = + (wake[1].revents & (POLLERR | POLLHUP | POLLNVAL)) != 0; + if (sig_err) { + worker.signal_broken = true; + worker.submit_broken = true; + Fail("eventfd poll failed", 0); + FailUnsubmittedActive(worker, worker.broken_errno); + } + if (ring_err) { + worker.submit_broken = true; + worker.ring_poll_broken = true; + Fail("ring_fd poll failed", 0); + FailUnsubmittedActive(worker, worker.broken_errno); + } + if (!sig_err && (wake[1].revents & POLLIN)) { + uint64_t value; + while (::read(worker.signal, &value, sizeof(value)) < 0 && + errno == EINTR) { + } + } + } + } + } + + void Shutdown() { + std::lock_guard serial(shutdown_mutex); + { + std::lock_guard lock(mutex); + stopping = true; + credit.notify_all(); + for (auto& worker : workers) (void)worker->Wake(); + } + for (auto& worker : workers) { + if (worker->thread.joinable()) worker->thread.join(); + } + } + + const size_t limit; + size_t pending{0}, next_worker{0}; + bool stopping{false}, failed{false}; + int failure_errno{0}; + mutable std::mutex mutex; + std::condition_variable credit; + std::mutex shutdown_mutex; + std::vector> workers; +}; + +std::shared_ptr UringReadExecutor::Create( + size_t workers, size_t max_outstanding) noexcept { + if (!workers || workers > 64 || !max_outstanding || max_outstanding > 65536) + return {}; + try { + auto impl = std::make_unique(max_outstanding); + if (!impl->Init(workers)) { + LOG(WARNING) << "UringReadExecutor initialization failed; local " + "streaming reads will fall back to pread"; + return {}; + } + return std::shared_ptr( + new UringReadExecutor(std::move(impl))); + } catch (...) { + return {}; + } +} + +UringReadExecutor::UringReadExecutor(std::unique_ptr impl) + : impl_(std::move(impl)) {} + +UringReadExecutor::~UringReadExecutor() = default; + +bool UringReadExecutor::WaitSubmit(std::shared_ptr source, int fd, + std::span buffer, + uint64_t file_offset, + Completion completion) noexcept { + constexpr auto max_offset = uint64_t(std::numeric_limits::max()); + if (!source || fd < 0 || source->native_read_fd() != fd || !buffer.data() || + buffer.empty() || buffer.size() > INT_MAX || + buffer.size() > std::numeric_limits::max() - + reinterpret_cast(buffer.data()) || + file_offset > max_offset || buffer.size() > max_offset - file_offset || + !completion) + return false; + try { + return impl_->Submit(std::make_unique( + Impl::Operation{std::move(source), fd, buffer, file_offset, + std::move(completion)})); + } catch (...) { + return false; // Allocation failed before enqueue/acceptance. + } +} + +void UringReadExecutor::Shutdown() { impl_->Shutdown(); } + +bool UringReadExecutor::healthy() const noexcept { + std::lock_guard lock(impl_->mutex); + return !impl_->stopping && !impl_->failed; +} + +struct UringPipelineDriver::Impl { + enum class Stage { kIdle, kRead, kWrite, kReady }; + struct Record { + Stage stage{Stage::kIdle}; + IoCompletion event; + }; + + Impl(std::vector> sources, + std::vector chunk_sources, std::vector source_fds, + std::shared_ptr target, + std::shared_ptr reader, BoundedExecutor* writes, + std::vector buffers) + : sources(std::move(sources)), + chunk_sources(std::move(chunk_sources)), + source_fds(std::move(source_fds)), + target(std::move(target)), + reader(std::move(reader)), + writes(writes), + buffers(std::move(buffers)), + records(this->buffers.size()) {} + + ~Impl() { + std::unique_lock lock(mutex); + stopping = true; + // Every accepted read or write callback decrements its counter and + // notifies under mutex before dropping its last access to this Impl. + changed.wait(lock, [&] { return !reads_running && !writes_running; }); + } + + bool Valid(const SlotToken& token, const ReadChunk& chunk, + SlotBuffer buffer) const { + return token.generation && token.slot_index < buffers.size() && + token.chunk_index < chunk_sources.size() && buffer.data && + chunk.read_bytes && + buffer.data == buffers[token.slot_index].data && + buffer.capacity == buffers[token.slot_index].capacity && + chunk.read_bytes <= buffer.capacity && + chunk.read_bytes <= INT_MAX && + chunk.file_offset <= + uint64_t(std::numeric_limits::max()) && + chunk.read_bytes <= uint64_t(std::numeric_limits::max()) - + chunk.file_offset; + } + + bool Read(const SlotToken& token, const ReadChunk& chunk, + SlotBuffer buffer) noexcept { + if (!Valid(token, chunk, buffer)) return false; + std::unique_lock lock(mutex); + auto& record = records[token.slot_index]; + if (stopping || record.stage != Stage::kIdle) return false; + const size_t source_index = chunk_sources[token.chunk_index]; + const int fd = source_fds[source_index]; + record.stage = Stage::kRead; + record.event = {token, SlotStage::kReading, 0, Error::kOk}; + ++reads_running; + lock.unlock(); + + bool accepted = false; + try { + accepted = reader->WaitSubmit( + sources[source_index], fd, {buffer.data, chunk.read_bytes}, + chunk.file_offset, [this, token](ReadResult result) { + std::lock_guard done_lock(mutex); + auto& completed = records[token.slot_index]; + completed.event.bytes = result.bytes; + completed.event.result = result.error; + completed.event.sys_errno = result.sys_errno; + completed.stage = Stage::kReady; + --reads_running; + changed.notify_all(); + }); + } catch (...) { + } + if (!accepted) { + lock.lock(); + record.stage = Stage::kIdle; + --reads_running; + changed.notify_all(); + } + return accepted; + } + + bool Write(const SlotToken& token, const ReadChunk& chunk, + SlotBuffer buffer) noexcept { + if (!Valid(token, chunk, buffer)) return false; + if (writes == nullptr) { + { + std::lock_guard lock(mutex); + auto& record = records[token.slot_index]; + if (stopping || record.stage != Stage::kIdle) return false; + record.stage = Stage::kWrite; + record.event = {token, SlotStage::kWriting, 0, Error::kOk}; + } + const auto result = target->Write(chunk, buffer); + std::lock_guard lock(mutex); + auto& completed = records[token.slot_index]; + completed.event.result = result; + completed.event.bytes = + result == Error::kOk ? chunk.payload_bytes : 0; + completed.stage = Stage::kReady; + changed.notify_all(); + return true; + } + { + std::lock_guard lock(mutex); + auto& record = records[token.slot_index]; + if (stopping || record.stage != Stage::kIdle) return false; + record.stage = Stage::kWrite; + record.event = {token, SlotStage::kWriting, 0, Error::kOk}; + ++writes_running; + } + + bool accepted = false; + try { + accepted = + writes->WaitSubmit([this, token, buffer, chunk_ptr = &chunk] { + const auto result = target->Write(*chunk_ptr, buffer); + std::lock_guard done_lock(mutex); + auto& completed = records[token.slot_index]; + completed.event.result = result; + completed.event.bytes = + result == Error::kOk ? chunk_ptr->payload_bytes : 0; + completed.stage = Stage::kReady; + --writes_running; + changed.notify_all(); + }); + } catch (...) { + } + if (!accepted) { + std::lock_guard lock(mutex); + records[token.slot_index].stage = Stage::kIdle; + --writes_running; + changed.notify_all(); + } + return accepted; + } + + bool Wait(IoCompletion& event, std::chrono::milliseconds timeout) { + const auto until = ClampedDeadline(timeout); + std::unique_lock lock(mutex); + auto ready = [&] { + return std::find_if(records.begin(), records.end(), + [](const auto& record) { + return record.stage == Stage::kReady; + }); + }; + if (!changed.wait_until(lock, until, [&] { + return ready() != records.end() || + (!reads_running && !writes_running); + })) + return false; + const auto found = ready(); + if (found == records.end()) return false; + event = found->event; + found->stage = Stage::kIdle; + return true; + } + + std::vector> sources; + const std::vector chunk_sources; + std::vector source_fds; + std::shared_ptr target; + std::shared_ptr reader; + BoundedExecutor* writes; + std::vector buffers; + std::vector records; + std::mutex mutex; + std::condition_variable changed; + size_t reads_running{0}, writes_running{0}; + bool stopping{false}; +}; + +UringPipelineDriver::Creation UringPipelineDriver::Create( + std::vector> sources, + std::vector chunk_sources, std::shared_ptr target, + std::shared_ptr reader, BoundedExecutor* writes, + std::vector buffers) { + if (!reader || !reader->healthy()) return {Error::kNotSupported, {}}; + if (sources.empty() || chunk_sources.empty() || + std::any_of(chunk_sources.begin(), chunk_sources.end(), + [&](size_t index) { return index >= sources.size(); })) + return {Error::kInvalidArgument, {}}; + std::vector source_fds; + source_fds.reserve(sources.size()); + for (const auto& source : sources) { + if (!source) return {Error::kInvalidArgument, {}}; + const auto fd = source->native_read_fd(); + if (!fd || *fd < 0 || fcntl(*fd, F_GETFD) < 0) + return {Error::kNotSupported, {}}; + source_fds.push_back(*fd); + } + if (!target || buffers.empty() || buffers.size() > 64) + return {Error::kInvalidArgument, {}}; + std::vector> spans; + spans.reserve(buffers.size()); + for (auto buffer : buffers) { + const auto begin = reinterpret_cast(buffer.data); + if (!begin || !buffer.capacity || buffer.capacity > INT_MAX || + buffer.capacity > std::numeric_limits::max() - begin) + return {Error::kInvalidArgument, {}}; + spans.emplace_back(begin, begin + buffer.capacity); + } + std::sort(spans.begin(), spans.end()); + for (size_t i = 1; i < spans.size(); ++i) { + if (spans[i].first < spans[i - 1].second) + return {Error::kInvalidArgument, {}}; + } + try { + auto impl = std::make_unique( + std::move(sources), std::move(chunk_sources), std::move(source_fds), + std::move(target), std::move(reader), writes, std::move(buffers)); + return {Error::kOk, std::unique_ptr( + new UringPipelineDriver(std::move(impl)))}; + } catch (...) { + return {Error::kIoError, {}}; + } +} + +UringPipelineDriver::UringPipelineDriver(std::unique_ptr p) + : impl_(std::move(p)) {} + +UringPipelineDriver::~UringPipelineDriver() = default; + +bool UringPipelineDriver::SubmitRead(const SlotToken& t, const ReadChunk& c, + SlotBuffer b) noexcept { + return impl_->Read(t, c, b); +} + +bool UringPipelineDriver::SubmitWrite(const SlotToken& t, const ReadChunk& c, + SlotBuffer b) noexcept { + return impl_->Write(t, c, b); +} + +bool UringPipelineDriver::WaitForEvent(IoCompletion& c, + std::chrono::milliseconds t) { + return impl_->Wait(c, t); +} + +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/src/storage_backend.cpp b/mooncake-store/src/storage_backend.cpp index b24a2077cac..4afc673dd30 100644 --- a/mooncake-store/src/storage_backend.cpp +++ b/mooncake-store/src/storage_backend.cpp @@ -2135,6 +2135,95 @@ tl::expected BucketStorageBackend::ReadBucketValues( return {}; } +tl::expected +BucketStorageBackend::AcquireReadSources( + const std::vector& requests, + const std::function& reserve_credits) { + AcquiredReadSources result; + if (requests.empty()) return result; + + struct PendingBucket { + int64_t bucket_id; + int disk_index; + uint64_t min_file_bytes; + std::shared_ptr guard; + }; + std::vector pending_buckets; + std::unordered_map bucket_to_source; + result.locations.reserve(requests.size()); + { + SharedMutexLocker lock(&mutex_, shared_lock); + const bool update_lru = + bucket_backend_config_.eviction_policy == BucketEvictionPolicy::LRU; + const int64_t now_ns = + update_lru + ? std::chrono::steady_clock::now().time_since_epoch().count() + : 0; + for (const auto& req : requests) { + auto object = object_bucket_map_.find(std::string(req.key)); + if (!object) return tl::make_unexpected(ErrorCode::INVALID_KEY); + const auto& metadata = *object; + if (metadata.data_size < 0 || metadata.offset < 0 || + metadata.key_size < 0 || + uint64_t(metadata.data_size) != req.expected_size || + metadata.offset > + std::numeric_limits::max() - metadata.key_size) { + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + } + const uint64_t value_file_offset = + uint64_t(metadata.offset) + uint64_t(metadata.key_size); + if (req.expected_size > + uint64_t(std::numeric_limits::max()) - + value_file_offset) { + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + } + const uint64_t end_offset = value_file_offset + req.expected_size; + auto [it, inserted] = bucket_to_source.emplace( + metadata.bucket_id, pending_buckets.size()); + if (inserted) { + auto bucket = buckets_.find(metadata.bucket_id); + if (bucket == buckets_.end()) { + return tl::make_unexpected(ErrorCode::BUCKET_NOT_FOUND); + } + if (update_lru) { + bucket->second->last_access_ns_.store( + now_ns, std::memory_order_relaxed); + } + pending_buckets.push_back( + {metadata.bucket_id, bucket->second->disk_index, end_offset, + std::make_shared(bucket->second)}); + } else { + auto& pending = pending_buckets[it->second]; + pending.min_file_bytes = + std::max(pending.min_file_bytes, end_offset); + } + result.locations.push_back( + {it->second, req.expected_size, value_file_offset}); + } + } + + if (reserve_credits && !reserve_credits(pending_buckets.size())) { + return tl::make_unexpected(ErrorCode::NO_AVAILABLE_HANDLE); + } + + result.sources.reserve(pending_buckets.size()); + for (auto& pending : pending_buckets) { + auto path = GetBucketDataPath(pending.bucket_id, pending.disk_index); + if (!path) return tl::make_unexpected(path.error()); + auto opened = ssd_offload::OpenPosixReadSource( + *path, pending.min_file_bytes, std::move(pending.guard)); + if (opened.error != ssd_offload::Error::kOk) { + if (opened.error == ssd_offload::Error::kIoError && + opened.sys_errno != 0) { + NotifyDiskError(opened.sys_errno, "open"); + } + return tl::make_unexpected(ErrorCode::FILE_READ_FAIL); + } + result.sources.push_back(std::move(opened.source)); + } + return result; +} + tl::expected BucketStorageBackend::GetBucketKeys( int64_t bucket_id, std::vector& bucket_keys) { SharedMutexLocker locker(&mutex_, shared_lock); @@ -3454,6 +3543,13 @@ BucketStorageBackend::SelectEvictionCandidate(int disk_index) { ++pos; continue; } + if (bucket_it->second->inflight_reads_.load( + std::memory_order_acquire) > 0) { + VLOG(1) << "SelectEvictionCandidate: skipping read-pinned " + << "bucket_id=" << bucket_it->first; + ++pos; + continue; + } return bucket_it; } return buckets_.end(); @@ -3493,6 +3589,13 @@ BucketStorageBackend::SelectEvictionCandidate(int disk_index) { ++it; continue; } + if (bucket_it->second->inflight_reads_.load( + std::memory_order_acquire) > 0) { + VLOG(1) << "SelectEvictionCandidate: skipping read-pinned " + << "bucket_id=" << id; + ++it; + continue; + } int64_t actual_ts = bucket_it->second->last_access_ns_.load( std::memory_order_relaxed); if (actual_ts == ts) { diff --git a/mooncake-store/tests/CMakeLists.txt b/mooncake-store/tests/CMakeLists.txt index 374e3a91804..aa032dfaa19 100644 --- a/mooncake-store/tests/CMakeLists.txt +++ b/mooncake-store/tests/CMakeLists.txt @@ -492,6 +492,37 @@ else() endif() add_store_test(mutex_test mutex_test.cpp) add_store_test(file_storage_test file_storage_test.cpp) +add_store_test(offload_read_executor_config_test + offload_read_executor_config_test.cpp) +add_store_test(ssd_read_pipeline_test ssd_read_pipeline_test.cpp) +add_store_test(ssd_read_source_test ssd_read_source_test.cpp) +add_store_test(ssd_pipeline_io_test ssd_pipeline_io_test.cpp) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND TARGET Mooncake::liburing) + add_executable( + ssd_uring_read_executor_contract_test + ../src/ssd_read_pipeline.cpp ../src/ssd_read_source.cpp + ../src/ssd_pipeline_io.cpp ../src/ssd_uring_pipeline.cpp + ssd_uring_read_executor_contract_test.cpp) + target_include_directories(ssd_uring_read_executor_contract_test + PRIVATE ../include) + target_compile_definitions(ssd_uring_read_executor_contract_test + PRIVATE USE_URING) + target_link_libraries( + ssd_uring_read_executor_contract_test + PRIVATE Mooncake::liburing glog::glog gtest_main pthread) + target_link_options( + ssd_uring_read_executor_contract_test + PRIVATE + -Wl,--wrap=io_uring_queue_init + -Wl,--wrap=io_uring_queue_exit + -Wl,--wrap=io_uring_submit + -Wl,--wrap=poll + -Wl,--wrap=eventfd) + add_test(NAME ssd_uring_read_executor_contract_test + COMMAND ssd_uring_read_executor_contract_test) + set_tests_properties(ssd_uring_read_executor_contract_test PROPERTIES TIMEOUT + 60) +endif() add_store_test(file_storage_config_test file_storage_config_test.cpp) add_store_test(fileread_worker_pool_test fileread_worker_pool_test.cpp fileread_worker_pool_config_test.cpp) diff --git a/mooncake-store/tests/file_storage_config_test.cpp b/mooncake-store/tests/file_storage_config_test.cpp index 7b0f29ee145..97f86500849 100644 --- a/mooncake-store/tests/file_storage_config_test.cpp +++ b/mooncake-store/tests/file_storage_config_test.cpp @@ -73,6 +73,14 @@ struct FileStorageEnvironment { "MOONCAKE_DISK_EVICTION_LOW_WATERMARK_RATIO"}; ScopedEnvVar use_uring{"MOONCAKE_OFFLOAD_USE_URING"}; ScopedEnvVar legacy_use_uring{"MOONCAKE_USE_URING"}; + ScopedEnvVar local_streaming_read{"MOONCAKE_OFFLOAD_LOCAL_STREAMING_READ"}; + ScopedEnvVar stream_use_uring{"MOONCAKE_OFFLOAD_STREAM_USE_URING"}; + ScopedEnvVar stream_slot_bytes{"MOONCAKE_OFFLOAD_STREAM_SLOT_BYTES"}; + ScopedEnvVar stream_slots{"MOONCAKE_OFFLOAD_STREAM_SLOTS"}; + ScopedEnvVar stream_read_threads{"MOONCAKE_OFFLOAD_STREAM_READ_THREADS"}; + ScopedEnvVar stream_write_threads{"MOONCAKE_OFFLOAD_STREAM_WRITE_THREADS"}; + ScopedEnvVar stream_max_outstanding{ + "MOONCAKE_OFFLOAD_STREAM_MAX_OUTSTANDING"}; }; void ExpectDefaultFileStorageConfig(const FileStorageConfig& config) { @@ -91,6 +99,13 @@ void ExpectDefaultFileStorageConfig(const FileStorageConfig& config) { EXPECT_TRUE(config.enable_disk_watermark_eviction); EXPECT_DOUBLE_EQ(config.disk_eviction_high_watermark_ratio, 0.90); EXPECT_DOUBLE_EQ(config.disk_eviction_low_watermark_ratio, 0.80); + EXPECT_FALSE(config.streaming_read.enabled); + EXPECT_FALSE(config.streaming_read.use_uring); + EXPECT_EQ(config.streaming_read.slot_bytes, 1024u * 1024u); + EXPECT_EQ(config.streaming_read.slots, 4u); + EXPECT_EQ(config.streaming_read.read_workers, 4u); + EXPECT_EQ(config.streaming_read.write_workers, 2u); + EXPECT_EQ(config.streaming_read.max_outstanding, 64u); } class FileStorageConfigTest : public ::testing::Test { @@ -372,6 +387,76 @@ TEST_F(FileStorageConfigTest, ValidateFailsOnInvalidLimits) { EXPECT_FALSE(config.Validate()); } +TEST_F(FileStorageConfigTest, StreamingReadEnvAndValidation) { + env.storage_path.Set(data_path.c_str()); + env.local_buffer_size.Set("16777216"); + env.local_streaming_read.Set("true"); + env.stream_use_uring.Set("true"); + env.stream_slot_bytes.Set("1048576"); + env.stream_slots.Set("4"); + env.stream_read_threads.Set("2"); + env.stream_write_threads.Set("3"); + env.stream_max_outstanding.Set("16"); + + auto config = FileStorageConfig::FromEnvironment(); + EXPECT_TRUE(config.streaming_read.enabled); + EXPECT_TRUE(config.streaming_read.use_uring); + EXPECT_EQ(config.streaming_read.slot_bytes, 1048576u); + EXPECT_EQ(config.streaming_read.slots, 4u); + EXPECT_EQ(config.streaming_read.read_workers, 2u); + EXPECT_EQ(config.streaming_read.write_workers, 3u); + EXPECT_EQ(config.streaming_read.max_outstanding, 16u); + EXPECT_TRUE(config.Validate()); + + config.streaming_read.slots = 32; // 32 * 1 MiB > 16 MiB arena + EXPECT_FALSE(config.Validate()); + + config.streaming_read.slots = 4; + config.streaming_read.max_outstanding = 4; + config.streaming_read.read_workers = 8; // read_workers > max_outstanding + EXPECT_FALSE(config.Validate()); + config.storage_backend_type = StorageBackendType::kFilePerKey; + EXPECT_TRUE(config.Validate()); // non-bucket ignores streaming limits + config.storage_backend_type = StorageBackendType::kBucket; + config.streaming_read.read_workers = 2; + config.streaming_read.max_outstanding = 16; + + // Minimal single-slot / single-reader configuration must validate without + // overriding the unused default write_workers value. + { + FileStorageConfig minimal; + minimal.storage_filepath = data_path; + minimal.local_buffer_size = 16 * 1024 * 1024; + minimal.streaming_read.enabled = true; + minimal.streaming_read.slots = 1; + minimal.streaming_read.read_workers = 1; + minimal.streaming_read.max_outstanding = 1; + EXPECT_EQ(minimal.streaming_read.write_workers, 2u); + EXPECT_TRUE(minimal.Validate()); + } + + // OffsetAllocator rounds non-exact bin sizes up (1150976 -> 1179648) and + // our config helper stays in lockstep with OffsetAllocator itself. + config.streaming_read.slots = 4; + config.streaming_read.slot_bytes = 1150976; // 1 MiB + 100 KiB + config.local_buffer_size = 4 * 1150976; + EXPECT_FALSE(config.Validate()); + config.local_buffer_size = 4 * 1179648; + EXPECT_TRUE(config.Validate()); + + for (uint64_t arena : {4ULL * 1024 * 1024, 8ULL * 1024 * 1024 * 1024}) { + auto allocator = + mooncake::offset_allocator::OffsetAllocator::create(0, arena); + for (size_t slot : {size_t{4096}, size_t{1048576}, size_t{1150976}, + size_t{2097151}, size_t{64ULL * 1024 * 1024}}) { + const auto [normalized, _] = + ssd_offload::OffsetAllocatorSlotBudget(slot, arena); + EXPECT_EQ(normalized, allocator->normalizedAllocationSize(slot)) + << "arena=" << arena << " slot=" << slot; + } + } +} + } // namespace } // namespace mooncake diff --git a/mooncake-store/tests/file_storage_test.cpp b/mooncake-store/tests/file_storage_test.cpp index 7c7daad44ea..72aa4f9016b 100644 --- a/mooncake-store/tests/file_storage_test.cpp +++ b/mooncake-store/tests/file_storage_test.cpp @@ -154,6 +154,32 @@ enum class ReclaimCase { class FileStorageTest : public ::testing::Test { protected: + void OffloadStreamingObject(FileStorage& storage, const std::string& key, + std::string& value) { + ASSERT_TRUE(storage.storage_backend_->BatchOffload( + {{key, {{value.data(), value.size()}}}}, + [](const auto&, auto&) { return ErrorCode::OK; })); + } + + void PrepareStreamingObject(FileStorage& storage, const std::string& key, + std::string& value) { + ASSERT_TRUE(storage.storage_backend_->Init()); + OffloadStreamingObject(storage, key, value); + } + + void PrepareStreamingObjects( + FileStorage& storage, + const std::vector>& objects) { + ASSERT_TRUE(storage.storage_backend_->Init()); + std::unordered_map> batch; + for (const auto& [key, value] : objects) { + batch.emplace(key, + std::vector{{value->data(), value->size()}}); + } + ASSERT_TRUE(storage.storage_backend_->BatchOffload( + batch, [](const auto&, auto&) { return ErrorCode::OK; })); + } + std::string data_path; static uintmax_t StoredFileBytes(const std::string& path) { @@ -1451,6 +1477,27 @@ class FileStorageTest : public ::testing::Test { return fileStorage.disk_fenced_.load(); } + static void SetDiskFenced(FileStorage& storage, bool fenced) { + storage.disk_fenced_.store(fenced); + } + + static bool HasStreamingReadPool(const FileStorage& storage) { + std::shared_lock lock(storage.streaming_mutex_); + std::lock_guard init_lock(storage.streaming_init_mutex_); + return storage.streaming_reads_ != nullptr; + } + + static bool HasStreamingUringReadPool(const FileStorage& storage) { +#if defined(__linux__) && defined(USE_URING) + std::shared_lock lock(storage.streaming_mutex_); + std::lock_guard init_lock(storage.streaming_init_mutex_); + return storage.streaming_uring_reads_ != nullptr; +#else + (void)storage; + return false; +#endif + } + void AssertHeartbeatEvictsAllKeys( FileStorage& fileStorage, const std::vector& expected_keys, const std::unordered_map>& @@ -3608,4 +3655,382 @@ INSTANTIATE_TEST_SUITE_P( ReclaimCase::kExistingData, ReclaimCase::kOffloadFails), ReclaimCaseName); +TEST_F(FileStorageTest, LocalStreamingRestoreExceedsStagingArenaCapacity) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + FileStorage storage(config, nullptr, "local"); + std::string value(20 * 1024 * 1024, 's'); + for (size_t i = 0; i < value.size(); ++i) value[i] = char(i % 251); + PrepareStreamingObject(storage, "stream-key", value); + ASSERT_TRUE(storage.SupportsLocalStreamingRead()); + std::vector first(12 * 1024 * 1024), second(8 * 1024 * 1024); + ASSERT_TRUE(storage.ReadLocalStreaming( + {{"stream-key", + value.size(), + 0, + {{first.data(), first.size()}, {second.data(), second.size()}}}})); + EXPECT_EQ(std::memcmp(first.data(), value.data(), first.size()), 0); + EXPECT_EQ( + std::memcmp(second.data(), value.data() + first.size(), second.size()), + 0); +} + +TEST_F(FileStorageTest, LocalStreamingRangeAndInvalidRange) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + FileStorage storage(config, nullptr, "local"); + std::string value(12000, 'x'); + value.replace(300, 5, "hello"); + PrepareStreamingObject(storage, "range-key", value); + std::array destination{}; + ASSERT_TRUE(storage.ReadLocalStreaming( + {{"range-key", + value.size(), + 300, + {{destination.data(), destination.size()}}}})); + EXPECT_EQ(std::string(destination.data(), destination.size()), "hello"); + destination.fill('z'); + auto invalid = storage.ReadLocalStreaming( + {{"range-key", + value.size(), + value.size(), + {{destination.data(), destination.size()}}}}); + ASSERT_FALSE(invalid); + EXPECT_EQ(invalid.error(), ErrorCode::INVALID_PARAMS); + EXPECT_EQ(std::string(destination.data(), destination.size()), "zzzzz"); +} + +TEST_F(FileStorageTest, LocalStreamingRemainsOptIn) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + FileStorage storage(config, nullptr, "local"); + EXPECT_FALSE(storage.SupportsLocalStreamingRead()); + auto result = storage.ReadLocalStreaming({}); + ASSERT_FALSE(result); + EXPECT_EQ(result.error(), ErrorCode::NOT_SUPPORTED); +} + +TEST_F(FileStorageTest, LocalStreamingPreflightsBatchAndRejectsOverlap) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + FileStorage storage(config, nullptr, "local"); + std::string value(12000, 's'); + PrepareStreamingObject(storage, "valid-key", value); + std::array destination; + destination.fill('z'); + auto bad_key = storage.ReadLocalStreaming( + {{"valid-key", value.size(), 0, {{destination.data(), 8}}}, + {"missing-key", value.size(), 0, {{destination.data() + 8, 8}}}}); + ASSERT_FALSE(bad_key); + EXPECT_EQ(bad_key.error(), ErrorCode::INVALID_KEY); + EXPECT_EQ(std::string(destination.data(), 16), std::string(16, 'z')); + auto overlap = storage.ReadLocalStreaming( + {{"valid-key", value.size(), 0, {{destination.data(), 8}}}, + {"valid-key", value.size(), 8, {{destination.data() + 4, 8}}}}); + ASSERT_FALSE(overlap); + EXPECT_EQ(overlap.error(), ErrorCode::NOT_SUPPORTED); + auto null = storage.ReadLocalStreaming( + {{"valid-key", value.size(), 0, {{nullptr, 1}}}}); + ASSERT_FALSE(null); + EXPECT_EQ(null.error(), ErrorCode::INVALID_PARAMS); + EXPECT_TRUE(storage.ReadLocalStreaming({})); +} + +TEST_F(FileStorageTest, LocalStreamingDeduplicatesBucketFdsAndBoundsBuckets) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + config.streaming_read.max_outstanding = 8; + FileStorage storage(config, nullptr, "local"); + + // 80 keys sharing a single bucket must stream cleanly even when + // max_outstanding == 8, because bucket sources are deduplicated. + std::string value(128, 'b'); + for (size_t i = 0; i < value.size(); ++i) value[i] = char('a' + (i % 26)); + std::vector> same_bucket; + same_bucket.reserve(80); + for (size_t i = 0; i < 80; ++i) { + same_bucket.emplace_back("same-bucket-" + std::to_string(i), &value); + } + PrepareStreamingObjects(storage, same_bucket); + std::vector out(80 * value.size(), 'z'); + std::vector many_same_bucket; + many_same_bucket.reserve(80); + for (size_t i = 0; i < 80; ++i) { + many_same_bucket.push_back( + {same_bucket[i].first, + value.size(), + 0, + {{out.data() + i * value.size(), value.size()}}}); + } + ASSERT_TRUE(storage.ReadLocalStreaming(many_same_bucket)); + for (size_t i = 0; i < 80; ++i) { + EXPECT_EQ(std::string(out.data() + i * value.size(), value.size()), + value); + } + + // 9 distinct buckets exceed max_outstanding == 8 before copying. + std::vector distinct_buckets; + std::array bucket_dest; + bucket_dest.fill('z'); + for (size_t i = 0; i < 9; ++i) { + const std::string key = "distinct-bucket-" + std::to_string(i); + OffloadStreamingObject(storage, key, value); + distinct_buckets.push_back( + {key, value.size(), 0, {{bucket_dest.data() + i, 1}}}); + } + auto rejected = storage.ReadLocalStreaming(distinct_buckets); + ASSERT_FALSE(rejected); + EXPECT_EQ(rejected.error(), ErrorCode::NO_AVAILABLE_HANDLE); + EXPECT_EQ(std::string(bucket_dest.data(), 9), std::string(9, 'z')); + distinct_buckets.pop_back(); + EXPECT_TRUE(storage.ReadLocalStreaming(distinct_buckets)); +} + +TEST_F(FileStorageTest, LocalStreamingUringCopiesAcrossSlots) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + config.streaming_read.use_uring = true; + config.streaming_read.slot_bytes = 4096; + config.streaming_read.slots = 2; + FileStorage storage(config, nullptr, "local"); + std::string value(20017, 'x'); + for (size_t i = 0; i < value.size(); ++i) value[i] = char(i % 251); + const std::string key = "uring-ordinary"; + PrepareStreamingObject(storage, key, value); + std::vector destination(17000 + 32, 'z'); + ASSERT_TRUE(storage.ReadLocalStreaming( + {{key, value.size(), 113, {{destination.data() + 16, 17000}}}})); + EXPECT_EQ(std::string(destination.data() + 16, 17000), + value.substr(113, 17000)); + EXPECT_EQ(std::string(destination.data(), 16), std::string(16, 'z')); + EXPECT_EQ(std::string(destination.end() - 16, destination.end()), + std::string(16, 'z')); + std::vector multi_a(4096, 'z'), multi_b(4096, 'z'); + ASSERT_TRUE(storage.ReadLocalStreaming( + {{key, value.size(), 100, {{multi_a.data(), multi_a.size()}}}, + {key, value.size(), 5000, {{multi_b.data(), multi_b.size()}}}})); + EXPECT_EQ(std::string(multi_a.data(), multi_a.size()), + value.substr(100, multi_a.size())); + EXPECT_EQ(std::string(multi_b.data(), multi_b.size()), + value.substr(5000, multi_b.size())); + ASSERT_TRUE(storage.Shutdown()); + EXPECT_FALSE(storage.SupportsLocalStreamingRead()); +} + +TEST_F(FileStorageTest, LocalStreamingRejectsWhenDiskFenced) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + FileStorage storage(config, nullptr, "local"); + std::string value(4096, 'f'); + PrepareStreamingObject(storage, "fenced-key", value); + SetDiskFenced(storage, true); + std::array destination; + destination.fill('z'); + auto result = storage.ReadLocalStreaming( + {{"fenced-key", value.size(), 0, {{destination.data(), 16}}}}); + ASSERT_FALSE(result); + EXPECT_EQ(result.error(), ErrorCode::FILE_READ_FAIL); + EXPECT_EQ(std::string(destination.data(), 16), std::string(16, 'z')); +} + +TEST_F(FileStorageTest, LocalStreamingPlanLimitsReturnNoAvailableHandle) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + config.streaming_read.slot_bytes = 4096; + config.streaming_read.max_chunks = 2; + config.streaming_read.max_fragments = 1; + FileStorage storage(config, nullptr, "local"); + std::string value(16384, 'p'); + PrepareStreamingObject(storage, "plan-limit-key", value); + + std::vector big_dest(16384, 'z'); + auto too_many_chunks = + storage.ReadLocalStreaming({{"plan-limit-key", + value.size(), + 0, + {{big_dest.data(), big_dest.size()}}}}); + ASSERT_FALSE(too_many_chunks); + EXPECT_EQ(too_many_chunks.error(), ErrorCode::NO_AVAILABLE_HANDLE); + EXPECT_EQ(big_dest.front(), 'z'); + + std::array frag_a, frag_b; + frag_a.fill('z'); + frag_b.fill('z'); + auto too_many_fragments = storage.ReadLocalStreaming( + {{"plan-limit-key", + value.size(), + 0, + {{frag_a.data(), frag_a.size()}, {frag_b.data(), frag_b.size()}}}}); + ASSERT_FALSE(too_many_fragments); + EXPECT_EQ(too_many_fragments.error(), ErrorCode::NO_AVAILABLE_HANDLE); + EXPECT_EQ(std::string(frag_a.data(), 8), std::string(8, 'z')); +} + +TEST_F(FileStorageTest, LocalStreamingReapsExpiredRemoteLease) { + FileStorageConfig config; + config.storage_filepath = data_path; + config.local_buffer_size = 1024 * 1024; + config.client_buffer_gc_ttl_ms = 5000; + config.streaming_read.enabled = true; + config.streaming_read.slot_bytes = 512 * 1024; + config.streaming_read.slots = 1; + FileStorage storage(config, nullptr, "local"); + std::string value(768 * 1024, 'r'); + for (size_t i = 0; i < value.size(); ++i) value[i] = char(i % 251); + PrepareStreamingObject(storage, "lease-reap-key", value); + + // Exhaust the staging arena with a remote lease, then expire it without + // running the background GC thread. + auto lease = storage.BatchGet({"lease-reap-key"}, + {static_cast(value.size())}); + ASSERT_TRUE(lease); + ASSERT_TRUE(ExpireClientBufferBatch(storage, lease->batch_id)); + + std::vector destination(value.size(), 'z'); + ASSERT_TRUE(storage.ReadLocalStreaming( + {{"lease-reap-key", + value.size(), + 0, + {{destination.data(), destination.size()}}}})); + EXPECT_EQ(std::memcmp(destination.data(), value.data(), value.size()), 0); +} + +TEST_F(FileStorageTest, LocalStreamingOverlapBeatsPlanLimitAndSmallBatchSlots) { + const std::string overlap_dir = data_path + "/overlap"; + const std::string multi_dir = data_path + "/multi"; + ASSERT_TRUE(fs::create_directories(overlap_dir)); + ASSERT_TRUE(fs::create_directories(multi_dir)); + std::string value(4096, 'm'); + + { + FileStorageConfig config; + config.storage_filepath = overlap_dir; + config.local_buffer_size = 512 * 1024; + config.streaming_read.enabled = true; + config.streaming_read.slot_bytes = 512 * 1024; + config.streaming_read.slots = 1; + config.streaming_read.max_chunks = 1; + FileStorage storage(config, nullptr, "local"); + PrepareStreamingObjects(storage, + {{"small-a", &value}, {"small-b", &value}}); + + // Overlapping destinations return NOT_SUPPORTED even when the batch + // also exceeds max_chunks so RealClient falls back to the sequential + // restore path. + std::array overlap_buf; + overlap_buf.fill('z'); + auto overlap = storage.ReadLocalStreaming( + {{"small-a", value.size(), 0, {{overlap_buf.data(), value.size()}}}, + {"small-b", + value.size(), + 0, + {{overlap_buf.data() + 1024, value.size()}}}}); + ASSERT_FALSE(overlap); + EXPECT_EQ(overlap.error(), ErrorCode::NOT_SUPPORTED); + EXPECT_EQ(overlap_buf[0], 'z'); + } + + { + // A multi-object batch under partial staging pressure degrades + // gracefully to the remaining free slot instead of failing when a + // live 512 KiB remote lease occupies half of the 1 MiB arena. + FileStorageConfig config; + config.storage_filepath = multi_dir; + config.local_buffer_size = 1024 * 1024; + config.client_buffer_gc_ttl_ms = 60000; + config.streaming_read.enabled = true; + config.streaming_read.slot_bytes = 512 * 1024; + config.streaming_read.slots = 2; + config.streaming_read.max_chunks = 4; + FileStorage multi(config, nullptr, "local"); + std::string occupy_value(512 * 1024, 'o'); + PrepareStreamingObjects(multi, {{"occupy-slot", &occupy_value}, + {"multi-a", &value}, + {"multi-b", &value}}); + auto lease = multi.BatchGet( + {"occupy-slot"}, {static_cast(occupy_value.size())}); + ASSERT_TRUE(lease); + std::vector out_a(value.size(), 'z'), out_b(value.size(), 'z'); + ASSERT_TRUE(multi.ReadLocalStreaming( + {{"multi-a", value.size(), 0, {{out_a.data(), out_a.size()}}}, + {"multi-b", value.size(), 0, {{out_b.data(), out_b.size()}}}})); + EXPECT_EQ(std::string(out_a.data(), out_a.size()), value); + EXPECT_EQ(std::string(out_b.data(), out_b.size()), value); + EXPECT_TRUE(multi.ReleaseBuffer(lease->batch_id)); + } +} + +TEST_F(FileStorageTest, LocalStreamingDefersFallbackReadPoolUntilNeeded) { + const std::string posix_dir = data_path + "/lazy-posix"; + const std::string uring_dir = data_path + "/lazy-uring"; + ASSERT_TRUE(fs::create_directories(posix_dir)); + ASSERT_TRUE(fs::create_directories(uring_dir)); + std::string value(4096, 'l'); + + { + FileStorageConfig config; + config.storage_filepath = posix_dir; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + config.streaming_read.use_uring = false; + FileStorage storage(config, nullptr, "local"); + EXPECT_TRUE(storage.SupportsLocalStreamingRead()); + EXPECT_FALSE(HasStreamingReadPool(storage)); + PrepareStreamingObject(storage, "lazy-posix-key", value); + std::vector out(value.size(), 'z'); + ASSERT_TRUE(storage.ReadLocalStreaming( + {{"lazy-posix-key", value.size(), 0, {{out.data(), out.size()}}}})); + EXPECT_EQ(std::string(out.data(), out.size()), value); + EXPECT_TRUE(HasStreamingReadPool(storage)); + ASSERT_TRUE(storage.Shutdown()); + EXPECT_FALSE(HasStreamingReadPool(storage)); + EXPECT_FALSE(storage.SupportsLocalStreamingRead()); + auto after_shutdown = storage.ReadLocalStreaming( + {{"lazy-posix-key", value.size(), 0, {{out.data(), out.size()}}}}); + ASSERT_FALSE(after_shutdown); + EXPECT_EQ(after_shutdown.error(), + ErrorCode::UNAVAILABLE_IN_CURRENT_STATUS); + } + + { + FileStorageConfig config; + config.storage_filepath = uring_dir; + config.local_buffer_size = 8 * 1024 * 1024; + config.streaming_read.enabled = true; + config.streaming_read.use_uring = true; + FileStorage storage(config, nullptr, "local"); + EXPECT_TRUE(storage.SupportsLocalStreamingRead()); + EXPECT_FALSE(HasStreamingReadPool(storage)); + EXPECT_FALSE(HasStreamingUringReadPool(storage)); + PrepareStreamingObject(storage, "lazy-uring-key", value); + std::vector out(value.size(), 'z'); + ASSERT_TRUE(storage.ReadLocalStreaming( + {{"lazy-uring-key", value.size(), 0, {{out.data(), out.size()}}}})); + EXPECT_EQ(std::string(out.data(), out.size()), value); + if (HasStreamingUringReadPool(storage)) { + EXPECT_FALSE(HasStreamingReadPool(storage)); + } else { + EXPECT_TRUE(HasStreamingReadPool(storage)); + } + ASSERT_TRUE(storage.Shutdown()); + EXPECT_FALSE(HasStreamingUringReadPool(storage)); + EXPECT_FALSE(HasStreamingReadPool(storage)); + } +} + } // namespace mooncake diff --git a/mooncake-store/tests/offload_read_executor_config_test.cpp b/mooncake-store/tests/offload_read_executor_config_test.cpp new file mode 100644 index 00000000000..32b6eb8bb0c --- /dev/null +++ b/mooncake-store/tests/offload_read_executor_config_test.cpp @@ -0,0 +1,40 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include + +#include + +#include "offload_read_executor_config.h" + +namespace mooncake::detail { + +TEST(OffloadReadExecutorConfig, DefaultsTo8WhenUnsetOrEmpty) { + EXPECT_EQ(kDefaultOffloadReadIoThreads, 8u); + EXPECT_EQ(ParseOffloadReadIoThreads(nullptr).value(), 8u); + EXPECT_EQ(ParseOffloadReadIoThreads("").value(), 8u); +} + +TEST(OffloadReadExecutorConfig, AcceptsExplicitThreadCounts) { + for (uint32_t count : {1u, 8u, 16u, 32u, 64u, 96u, 128u}) { + const auto parsed = + ParseOffloadReadIoThreads(std::to_string(count).c_str()); + ASSERT_TRUE(parsed.has_value()); + EXPECT_EQ(*parsed, count); + } +} + +TEST(OffloadReadExecutorConfig, PreservesWhitespaceAndPlusParsing) { + EXPECT_EQ(ParseOffloadReadIoThreads(" +32 \t").value(), 32u); + EXPECT_EQ(ParseOffloadReadIoThreads(" 64 ").value(), 64u); +} + +TEST(OffloadReadExecutorConfig, RejectsInvalidValuesAndFallsBackToDefault) { + for (const char* value : {"0", "-1", "129", "abc", "1.5", "64threads", " ", + "+", "++64", "+-64", "4294967296"}) { + const auto parsed = ParseOffloadReadIoThreads(value); + EXPECT_FALSE(parsed.has_value()) << value; + EXPECT_EQ(parsed.value_or(kDefaultOffloadReadIoThreads), 8u) << value; + } +} + +} // namespace mooncake::detail diff --git a/mooncake-store/tests/real_client_shutdown_test.cpp b/mooncake-store/tests/real_client_shutdown_test.cpp index 14424d2463c..10630551d04 100644 --- a/mooncake-store/tests/real_client_shutdown_test.cpp +++ b/mooncake-store/tests/real_client_shutdown_test.cpp @@ -38,6 +38,7 @@ class FileStorageShutdownTestPeer { static void* Staging(FileStorage& s) { return s.client_buffer_allocator_->getBase(); } + static auto Backend(FileStorage& s) { return s.storage_backend_; } static void SetBackend(FileStorage& s, std::shared_ptr backend) { s.storage_backend_ = std::move(backend); @@ -52,6 +53,28 @@ class RealClientShutdownTestPeer { return std::make_unique( c.offload_rpc_drain_); } + static bool HasOffloadReadPool(RealClient& c) { + std::lock_guard lock(c.offload_read_pool_mutex_); + return c.offload_read_pool_ != nullptr; + } + static tl::expected ExecuteLocalDiskRangedRead( + RealClient& c, const std::string& key, void* buffer, size_t dst_offset, + size_t src_offset, size_t size, uint64_t total_size, + const std::string& endpoint) { + Replica::Descriptor replica; + replica.id = 1; + replica.status = ReplicaStatus::COMPLETE; + replica.descriptor_variant = + LocalDiskDescriptor{UUID{1, 1}, total_size, endpoint}; + RealClient::RangedReadMetadata meta{ + QueryResult( + std::vector{replica}, + std::chrono::steady_clock::now() + std::chrono::seconds(60)), + replica, total_size}; + return c.execute_ranged_read(key, buffer, dst_offset, src_offset, size, + meta, /*size_is_buffer_capacity=*/false, + /*verify_checksum=*/false); + } }; namespace { using namespace std::chrono_literals; @@ -167,6 +190,7 @@ class BlockedReadBackend : public BucketStorageBackend { }; TEST_F(RealClientShutdownTest, CloseDrainsOffloadCallsBeforeStoppingExecutor) { + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); std::promise release; auto backend = std::make_shared( client->file_storage_->config_, release.get_future().share()); @@ -183,6 +207,7 @@ TEST_F(RealClientShutdownTest, CloseDrainsOffloadCallsBeforeStoppingExecutor) { read.wait(); FAIL() << "Read did not reach the backend gate"; } + EXPECT_TRUE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); const auto port = client->offload_rpc_server_->port(); auto closed = std::async(std::launch::async, [&] { return client->tearDownAll(); }); @@ -196,11 +221,80 @@ TEST_F(RealClientShutdownTest, CloseDrainsOffloadCallsBeforeStoppingExecutor) { release.set_value(); EXPECT_FALSE(read.get().has_value()); EXPECT_EQ(closed.get(), 0); + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); EXPECT_EQ(status, std::future_status::timeout); EXPECT_FALSE(connected); EXPECT_TRUE(response.has_value()); } +TEST_F(RealClientShutdownTest, + OffloadReadRpcRunsOffCoroRpcIoThreadAndJoinsOnTeardown) { + // Re-create the single-threaded offload RPC server with + // batch_get_offload_object registered so we exercise the real coro_rpc + // executor + coro_io::post + Yield resumption path end-to-end. + client->offload_rpc_server_->stop(); + client->offload_rpc_server_ = + std::make_unique(1, 0, "127.0.0.1"); + client->offload_rpc_server_ + ->register_handler<&RealClient::batch_get_offload_object>(client.get()); + client->offload_rpc_server_ + ->register_handler<&RealClient::release_offload_buffer>(client.get()); + client->offload_rpc_server_->async_start(); + ASSERT_FALSE(client->offload_rpc_server_->get_errc()); + + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); + std::promise release; + auto backend = std::make_shared( + client->file_storage_->config_, release.get_future().share()); + FileStorageShutdownTestPeer::SetBackend(*client->file_storage_, backend); + const auto port = client->offload_rpc_server_->port(); + + auto rpc_read = std::async(std::launch::async, [&] { + coro_rpc::coro_rpc_client rpc_client; + auto conn = async_simple::coro::syncAwait( + rpc_client.connect("127.0.0.1", std::to_string(port))); + if (conn) { + return tl::expected( + tl::unexpected(ErrorCode::RPC_FAIL)); + } + auto res = async_simple::coro::syncAwait( + rpc_client.call<&RealClient::batch_get_offload_object>( + std::vector{"blocked"}, std::vector{64})); + if (!res.has_value()) { + return tl::expected( + tl::unexpected(ErrorCode::RPC_FAIL)); + } + return res.value(); + }); + + auto entered = backend->entered.get_future().wait_for(5s); + if (entered != std::future_status::ready) { + release.set_value(); + rpc_read.wait(); + FAIL() << "RPC read did not reach the backend gate"; + } + EXPECT_TRUE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); + + // A second RPC on the same 1-thread server must succeed while BatchLoad + // is blocked on the offload read thread pool. + coro_rpc::coro_rpc_client probe; + auto connected = async_simple::coro::syncAwait( + probe.connect("127.0.0.1", std::to_string(port))); + auto probe_response = async_simple::coro::syncAwait( + probe.call<&RealClient::release_offload_buffer>(uint64_t{0})); + release.set_value(); + + auto rpc_result = rpc_read.get(); + EXPECT_FALSE(connected); + EXPECT_TRUE(probe_response.has_value()); + EXPECT_FALSE(rpc_result.has_value()); + if (!rpc_result.has_value()) { + EXPECT_EQ(rpc_result.error(), ErrorCode::FILE_READ_FAIL); + } + EXPECT_EQ(client->tearDownAll(), 0); + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); +} + TEST_F(RealClientShutdownTest, ReinitializationAcceptsOffloadCalls) { ASSERT_EQ(client->tearDownAll(), 0); ASSERT_TRUE(client->setup_internal(config)); @@ -208,6 +302,132 @@ TEST_F(RealClientShutdownTest, ReinitializationAcceptsOffloadCalls) { EXPECT_TRUE(inflight->ok()); } +TEST_F(RealClientShutdownTest, LocalStreamingEndToEndAndFallbackSemantics) { + // Register full offload RPC handlers so the fallback path exercises the + // real legacy offload RPC + TransferEngine path end-to-end. + client->offload_rpc_server_->stop(); + client->offload_rpc_server_ = + std::make_unique(1, 0, "127.0.0.1"); + client->offload_rpc_server_ + ->register_handler<&RealClient::batch_get_offload_object>(client.get()); + client->offload_rpc_server_ + ->register_handler<&RealClient::batch_get_offload_object_ranges>( + client.get()); + client->offload_rpc_server_ + ->register_handler<&RealClient::release_offload_buffer>(client.get()); + client->offload_rpc_server_->async_start(); + ASSERT_FALSE(client->offload_rpc_server_->get_errc()); + + FileStorageConfig stream_config = FileStorageConfig::FromEnvironment(); + stream_config.storage_filepath = path.string(); + stream_config.local_buffer_size = 2 * 1024 * 1024; + stream_config.streaming_read.enabled = true; + stream_config.streaming_read.use_uring = false; + stream_config.streaming_read.slot_bytes = 256 * 1024; + stream_config.streaming_read.slots = 2; + stream_config.streaming_read.max_fragments = 16; + + const std::string local_addr = + "127.0.0.1:" + std::to_string(client->offload_rpc_server_->port()); + client->local_rpc_addr = local_addr; + client->file_storage_ = std::make_shared( + stream_config, client->client_, local_addr); + ASSERT_TRUE(FileStorageShutdownTestPeer::Register(*client->file_storage_)); + auto storage_backend = + FileStorageShutdownTestPeer::Backend(*client->file_storage_); + ASSERT_TRUE(storage_backend->Init()); + + // Store an object larger than the entire 2 MiB staging arena plus a smaller + // object for the legacy fallback check directly in the local bucket + // backend. + const std::string key = "e2e-local-streaming-key"; + std::string payload(3 * 1024 * 1024 + 137, '\0'); + for (size_t i = 0; i < payload.size(); ++i) { + payload[i] = static_cast((i * 31) % 251); + } + const std::string fallback_key = "e2e-local-fallback-key"; + std::string fallback_payload(8192, '\0'); + for (size_t i = 0; i < fallback_payload.size(); ++i) { + fallback_payload[i] = static_cast((i * 17 + 5) % 251); + } + const TenantId tenant(client->client_->tenant_id()); + ASSERT_TRUE(storage_backend->BatchOffload( + {{tenant.MakeScopedKey(key), {{payload.data(), payload.size()}}}, + {tenant.MakeScopedKey(fallback_key), + {{fallback_payload.data(), fallback_payload.size()}}}}, + nullptr)); + + // 1) Happy path: local streaming copies the >2 MiB object without spawning + // the legacy offload RPC read thread pool. + std::vector out(payload.size(), '\0'); + std::unordered_map> req{ + {key, {{out.data(), out.size()}}}}; + auto ok = client->batch_get_into_offload_object_internal(local_addr, req); + ASSERT_TRUE(ok.has_value()) << ok.error(); + EXPECT_EQ(std::memcmp(out.data(), payload.data(), payload.size()), 0); + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); + + // 2) Range read through both batch_get_into_offload_object_internal and + // execute_ranged_read stays on local streaming without spawning the legacy + // read pool. + std::vector range_out(4096, '\0'); + std::unordered_map> range_req{ + {key, {{range_out.data(), range_out.size()}}}}; + RealClient::OffloadReadRange read_range{ + 1024 * 1024 + 77, static_cast(payload.size())}; + auto range_ok = client->batch_get_into_offload_object_internal( + local_addr, range_req, &read_range); + ASSERT_TRUE(range_ok.has_value()) << range_ok.error(); + EXPECT_EQ(std::memcmp(range_out.data(), payload.data() + 1024 * 1024 + 77, + range_out.size()), + 0); + std::vector ranged_direct_out(4096 + 64, '\0'); + auto ranged_direct = RealClientShutdownTestPeer::ExecuteLocalDiskRangedRead( + *client, key, ranged_direct_out.data(), /*dst_offset=*/32, + /*src_offset=*/2 * 1024 * 1024 + 19, /*size=*/4096, payload.size(), + local_addr); + ASSERT_TRUE(ranged_direct.has_value()) << ranged_direct.error(); + EXPECT_EQ(*ranged_direct, 4096); + EXPECT_EQ(std::memcmp(ranged_direct_out.data() + 32, + payload.data() + 2 * 1024 * 1024 + 19, 4096), + 0); + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); + + // 3) Direct error propagation: missing key fails directly with INVALID_KEY + // rather than falling back to the legacy RPC pool. + std::vector missing_out(64, '\0'); + std::unordered_map> missing_req{ + {"missing-key", {{missing_out.data(), missing_out.size()}}}}; + auto missing = + client->batch_get_into_offload_object_internal(local_addr, missing_req); + ASSERT_FALSE(missing.has_value()); + EXPECT_EQ(missing.error(), ErrorCode::INVALID_KEY); + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); + + // 4) Real legacy fallback: 32 disjoint 256-byte slices exceed + // max_fragments (16) so ReadLocalStreaming returns NO_AVAILABLE_HANDLE and + // RealClient falls back to the legacy offload RPC + TransferEngine path + // with disjoint destination writes (race-free under multi-lane TCP). + std::vector fallback_out(fallback_payload.size(), '\0'); + std::vector fallback_slices; + fallback_slices.reserve(32); + for (size_t i = 0; i < 32; ++i) { + fallback_slices.push_back({fallback_out.data() + i * 256, 256}); + } + std::unordered_map> fallback_req{ + {fallback_key, std::move(fallback_slices)}}; + auto fallback_ok = client->batch_get_into_offload_object_internal( + local_addr, fallback_req); + ASSERT_TRUE(fallback_ok.has_value()) << fallback_ok.error(); + EXPECT_TRUE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); + EXPECT_EQ(std::memcmp(fallback_out.data(), fallback_payload.data(), + fallback_payload.size()), + 0); + + EXPECT_EQ(client->tearDownAll(), 0); + EXPECT_FALSE(RealClientShutdownTestPeer::HasOffloadReadPool(*client)); +} + TEST(FileStorageShutdownTest, UnregistersStagingWithAnExternalTransferEngine) { testing::InProcMaster master; ASSERT_TRUE(master.Start(InProcMasterConfigBuilder().build())); diff --git a/mooncake-store/tests/ssd_pipeline_io_test.cpp b/mooncake-store/tests/ssd_pipeline_io_test.cpp new file mode 100644 index 00000000000..f8b875083e1 --- /dev/null +++ b/mooncake-store/tests/ssd_pipeline_io_test.cpp @@ -0,0 +1,224 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include "ssd_pipeline_io.h" + +#include + +#include +#include +#include +#include +#include + +namespace mooncake::ssd_offload { +namespace { +using namespace std::chrono_literals; + +struct Gate { + std::promise entered, release; + std::shared_future released = release.get_future().share(); + std::atomic signalled{false}; + void Wait() { + if (!signalled.exchange(true)) entered.set_value(); + released.wait(); + } +}; + +TEST(SsdExecutor, RejectsInvalidLimits) { + EXPECT_THROW(BoundedExecutor(0, 1), std::invalid_argument); + EXPECT_THROW(BoundedExecutor(1, 0), std::invalid_argument); +} + +TEST(SsdExecutor, WaitSubmitAppliesBackpressureAndDrainsShutdown) { + BoundedExecutor executor(1, 1); + Gate gate; + auto entered = gate.entered.get_future(); + ASSERT_TRUE(executor.WaitSubmit([&] { gate.Wait(); })); + ASSERT_EQ(entered.wait_for(10s), std::future_status::ready); + + std::promise attempted; + auto attempting = attempted.get_future(); + std::atomic finished{false}; + auto waiting = std::async(std::launch::async, [&] { + attempted.set_value(); + return executor.WaitSubmit([&] { finished.store(true); }); + }); + attempting.wait(); + EXPECT_EQ(waiting.wait_for(20ms), std::future_status::timeout); + gate.release.set_value(); + EXPECT_TRUE(waiting.get()); + executor.Shutdown(); + EXPECT_TRUE(finished.load()); + EXPECT_FALSE(executor.WaitSubmit([] {})); +} + +class MemorySource final : public ReadSource { + public: + explicit MemorySource(size_t size) : bytes(size) { + for (size_t i = 0; i < size; ++i) bytes[i] = std::byte(i % 251); + } + uint64_t file_bytes() const noexcept override { return bytes.size(); } + ReadResult ReadAt(std::span buffer, + uint64_t offset) noexcept override { + ++reads; + if (gate) gate->Wait(); + if (offset > bytes.size()) return {0, Error::kIoError}; + const size_t count = + std::min(buffer.size(), bytes.size() - offset); + std::memcpy(buffer.data(), bytes.data() + offset, count); + return {count, Error::kOk}; + } + std::vector bytes; + std::atomic reads{0}; + Gate* gate{nullptr}; +}; + +class CopyTarget final : public WriteTarget { + public: + explicit CopyTarget(size_t bytes) : bytes(bytes) {} + Error Write(const ReadChunk& chunk, SlotBuffer buffer) noexcept override { + ++writes; + for (const auto& fragment : chunk.fragments) { + const auto& target = fragment.destination; + if (target.destination_index != 0 || target.offset > bytes.size() || + target.length > bytes.size() - target.offset) + return Error::kTransferError; + std::memcpy(bytes.data() + target.offset, + buffer.data + fragment.buffer_offset, target.length); + } + return Error::kOk; + } + std::vector bytes; + std::atomic writes{0}; +}; + +struct Arena { + alignas(4096) std::array a{}, b{}; + std::vector buffers() { + return {{a.data(), a.size()}, {b.data(), b.size()}}; + } +}; + +ReadPlan Plan(size_t bytes) { + return BuildReadPlan({bytes, 0, 0, {{0, 0, bytes}}}, {4096, 1, 64}).plan; +} + +TEST(SsdPipelineIo, CopiesThroughRealWorkerCompletions) { + auto source = std::make_shared(12000); + auto target = std::make_shared(12000); + BoundedExecutor reads(2, 8), writes(2, 8); + Arena arena; + auto plan = Plan(12000); + std::vector chunk_sources(plan.chunks.size(), 0); + std::unique_ptr pipeline; + auto driver = std::make_unique( + std::vector>{source}, + std::move(chunk_sources), target, reads, writes, 2); + pipeline = std::make_unique(std::move(plan), arena.buffers(), + *driver); + ASSERT_EQ(pipeline->Start(), Error::kOk); + for (size_t count = 0; count < 6 && pipeline->inflight(); ++count) { + IoCompletion event; + ASSERT_TRUE(driver->WaitForEvent(event, 10s)); + if (event.stage == SlotStage::kReading) { + EXPECT_EQ( + pipeline->ReadDrained(event.token, event.bytes, event.result), + Error::kOk); + } else { + EXPECT_EQ(pipeline->WriteDrained(event.token, event.result), + Error::kOk); + } + } + EXPECT_EQ(pipeline->state(), PipelineState::kSucceeded); + EXPECT_EQ(target->bytes, source->bytes); + EXPECT_EQ(source->reads.load(), 3u); + EXPECT_EQ(target->writes.load(), 3u); +} + +TEST(SsdPipelineIo, ReadyEventCannotBeOverwrittenBeforeConsumption) { + auto source = std::make_shared(4096); + auto target = std::make_shared(4096); + BoundedExecutor reads(1, 4), writes(1, 4); + Arena arena; + auto chunk = Plan(4096).chunks[0]; + ThreadedPipelineDriver driver({source}, {0}, target, reads, writes, 1); + SlotToken token{0, 1, 0}; + ASSERT_TRUE(driver.SubmitRead(token, chunk, arena.buffers()[0])); + // Drain the single-worker read executor with a barrier task so the first + // task is guaranteed to have transitioned the slot record to State::kReady + // before testing that a duplicate SubmitRead is rejected. + std::promise barrier; + ASSERT_TRUE(reads.WaitSubmit([&] { barrier.set_value(); })); + ASSERT_EQ(barrier.get_future().wait_for(10s), std::future_status::ready); + auto next = token; + ++next.generation; + EXPECT_FALSE(driver.SubmitRead(next, chunk, arena.buffers()[0])); + IoCompletion event; + ASSERT_TRUE(driver.WaitForEvent(event, 10s)); + EXPECT_EQ(event.token.generation, 1u); + EXPECT_EQ(event.bytes, 4096u); + ASSERT_TRUE(driver.SubmitRead(next, chunk, arena.buffers()[0])); + ASSERT_TRUE(driver.WaitForEvent(event, 10s)); + EXPECT_EQ(event.token.generation, 2u); +} + +TEST(SsdPipelineIo, InlineWriteModeCopiesWithoutWriteThreadPool) { + auto source = std::make_shared(12000); + auto target = std::make_shared(12000); + BoundedExecutor reads(2, 8); + Arena arena; + auto plan = Plan(12000); + std::vector chunk_sources(plan.chunks.size(), 0); + std::unique_ptr pipeline; + auto driver = std::make_unique( + std::vector>{source}, + std::move(chunk_sources), target, reads, nullptr, 2); + pipeline = std::make_unique(std::move(plan), arena.buffers(), + *driver); + ASSERT_EQ(pipeline->Start(), Error::kOk); + for (size_t count = 0; count < 6 && pipeline->inflight(); ++count) { + IoCompletion event; + ASSERT_TRUE(driver->WaitForEvent(event, 10s)); + if (event.stage == SlotStage::kReading) { + EXPECT_EQ( + pipeline->ReadDrained(event.token, event.bytes, event.result), + Error::kOk); + } else { + EXPECT_EQ(pipeline->WriteDrained(event.token, event.result), + Error::kOk); + } + } + EXPECT_EQ(pipeline->state(), PipelineState::kSucceeded); + EXPECT_EQ(target->bytes, source->bytes); + EXPECT_EQ(source->reads.load(), 3u); + EXPECT_EQ(target->writes.load(), 3u); +} + +TEST(SsdPipelineIo, DestructorWaitsForRunningReadAndPinsSource) { + Gate gate; + auto entered = gate.entered.get_future(); + auto source = std::make_shared(4096); + source->gate = &gate; + std::weak_ptr weak_source = source; + auto target = std::make_shared(4096); + BoundedExecutor reads(1, 4), writes(1, 4); + Arena arena; + auto chunk = Plan(4096).chunks[0]; + auto driver = std::make_unique( + std::vector>{source}, + std::vector{0}, target, reads, writes, 1); + EXPECT_TRUE(driver->SubmitRead({0, 1, 0}, chunk, arena.buffers()[0])); + ASSERT_EQ(entered.wait_for(10s), std::future_status::ready); + source.reset(); + auto closing = + std::async(std::launch::async, + [driver = std::move(driver)]() mutable { driver.reset(); }); + EXPECT_EQ(closing.wait_for(20ms), std::future_status::timeout); + EXPECT_FALSE(weak_source.expired()); + gate.release.set_value(); + closing.get(); + EXPECT_TRUE(weak_source.expired()); +} + +} // namespace +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/tests/ssd_read_pipeline_test.cpp b/mooncake-store/tests/ssd_read_pipeline_test.cpp new file mode 100644 index 00000000000..c5948bd9f21 --- /dev/null +++ b/mooncake-store/tests/ssd_read_pipeline_test.cpp @@ -0,0 +1,399 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include "ssd_read_pipeline.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace mooncake::ssd_offload { +namespace { + +DestinationSlice Destination(uint64_t offset, uint64_t length, + size_t index = 0) { + return {index, offset, length}; +} + +PlanResult Plan(uint64_t bytes, uint64_t value_offset = 0, + size_t max_chunks = 64) { + return BuildReadPlan({bytes, value_offset, 0, {Destination(0, bytes)}}, + {4096, 4096, max_chunks}); +} + +class RecordingDriver final : public PipelineDriver { + public: + struct Submission { + SlotToken token; + const ReadChunk* chunk; + SlotBuffer buffer; + }; + bool SubmitRead(const SlotToken& token, const ReadChunk& chunk, + SlotBuffer buffer) noexcept override { + if (reject_read || reads.size() == reject_read_after) return false; + reads.push_back({token, &chunk, buffer}); + return true; + } + bool SubmitWrite(const SlotToken& token, const ReadChunk& chunk, + SlotBuffer buffer) noexcept override { + if (reject_write) return false; + writes.push_back({token, &chunk, buffer}); + return true; + } + std::vector reads, writes; + bool reject_read{false}, reject_write{false}; + size_t reject_read_after{std::numeric_limits::max()}; +}; + +struct Arena { + alignas(4096) std::array first{}, second{}; + std::vector Buffers() { + return {{first.data(), first.size()}, {second.data(), second.size()}}; + } +}; + +TEST(SsdReadPlan, SplitsUnalignedValueAcrossDestinationSlices) { + auto result = BuildReadPlan( + {12000, 13, 0, {Destination(100, 6000, 0), Destination(200, 6000, 1)}}, + {4096, 4096, 64}); + ASSERT_EQ(result.error, Error::kOk); + ASSERT_EQ(result.plan.chunks.size(), 3u); + EXPECT_EQ(result.plan.payload_bytes, 12000u); + EXPECT_EQ(result.plan.io_bytes, 12288u); + const auto& first = result.plan.chunks[0]; + EXPECT_EQ(first.file_offset, 0u); + EXPECT_EQ(first.payload_offset, 13u); + EXPECT_EQ(first.payload_bytes, 4083u); + ASSERT_EQ(first.fragments.size(), 1u); + EXPECT_EQ(first.fragments[0].buffer_offset, 13u); + EXPECT_EQ(first.fragments[0].destination.offset, 100u); + EXPECT_EQ(first.fragments[0].destination.length, 4083u); + const auto& second = result.plan.chunks[1]; + ASSERT_EQ(second.fragments.size(), 2u); + EXPECT_EQ(second.fragments[0].destination.offset, 4183u); + EXPECT_EQ(second.fragments[0].destination.length, 1917u); + EXPECT_EQ(second.fragments[1].destination.destination_index, 1u); + EXPECT_EQ(second.fragments[1].destination.offset, 200u); + EXPECT_EQ(second.fragments[1].buffer_offset, 1917u); + EXPECT_EQ(second.fragments[1].destination.length, 2179u); + EXPECT_EQ(result.plan.chunks[2].source_offset, 8179u); +} + +TEST(SsdReadPlan, SupportsBufferedRangeAndBoundsLimits) { + auto buffered = + BuildReadPlan({100, 7, 80, {Destination(3, 17)}}, {8, 1, 64}); + ASSERT_EQ(buffered.error, Error::kOk); + ASSERT_EQ(buffered.plan.chunks.size(), 3u); + EXPECT_EQ(buffered.plan.chunks[0].file_offset, 87u); + EXPECT_EQ(buffered.plan.payload_bytes, 17u); + EXPECT_EQ(buffered.plan.io_bytes, 17u); + + auto limited_chunks = Plan(8192, 13, 2); + EXPECT_EQ(limited_chunks.error, Error::kPlanLimit); + EXPECT_TRUE(limited_chunks.plan.chunks.empty()); + + auto limited_frags = BuildReadPlan({8192, 0, 0, {Destination(0, 8192)}}, + {4096, 4096, 64, 1}); + EXPECT_EQ(limited_frags.error, Error::kPlanLimit); + EXPECT_TRUE(limited_frags.plan.chunks.empty()); + + auto empty = Plan(0); + ASSERT_EQ(empty.error, Error::kOk); + EXPECT_TRUE(empty.plan.chunks.empty()); + EXPECT_EQ(empty.plan.io_bytes, 0u); +} + +TEST(SsdReadPlan, RejectsOverflowOverlapAndInvalidOptions) { + EXPECT_EQ( + BuildReadPlan({10, 0, 8, {Destination(0, 3)}}, {4096, 4096, 64}).error, + Error::kInvalidArgument); + EXPECT_EQ(BuildReadPlan({10, 0, 0, {Destination(UINT64_MAX, 2)}}, + {4096, 4096, 64}) + .error, + Error::kOverflow); + EXPECT_EQ(Plan(1, static_cast(INT64_MAX)).error, + Error::kOverflow); + EXPECT_EQ( + BuildReadPlan({100, 0, 0, {Destination(10, 10), Destination(15, 10)}}, + {4096, 1, 64}) + .error, + Error::kInvalidArgument); + EXPECT_EQ( + BuildReadPlan({100, 0, 0, {Destination(10, 10), Destination(20, 10)}}, + {4096, 1, 64}) + .error, + Error::kOk); + for (const auto options : + {PlanOptions{0, 4096, 64}, PlanOptions{4096, 0, 64}, + PlanOptions{4096, 3, 64}, PlanOptions{4097, 4096, 64}, + PlanOptions{4096, 4096, 0}}) { + EXPECT_EQ(BuildReadPlan({1, 0, 0, {Destination(0, 1)}}, options).error, + Error::kInvalidArgument); + } +} + +TEST(UringReadClassifier, HandlesFullShortEofRetryBudgetAndErrors) { + // Exact full read succeeds with no retry. + auto step = ClassifyUringReadResult(4096, 0, 4096, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.next_done, 4096u); + EXPECT_EQ(step.next_retries, 0u); + EXPECT_EQ(step.error, Error::kOk); + EXPECT_EQ(step.sys_errno, 0); + + // Partial read retries from advanced offset and resets transient retries. + step = ClassifyUringReadResult(1500, 0, 4096, 2); + EXPECT_TRUE(step.retry); + EXPECT_EQ(step.next_done, 1500u); + EXPECT_EQ(step.next_retries, 0u); + EXPECT_EQ(step.error, Error::kOk); + + // Remaining bytes finish without another retry. + step = ClassifyUringReadResult(2596, 1500, 4096, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.next_done, 4096u); + EXPECT_EQ(step.error, Error::kOk); + + // EOF returns partial bytes accumulated so far with kOk (ReadPipeline + // checks payload coverage). + step = ClassifyUringReadResult(0, 1500, 4096, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.next_done, 1500u); + EXPECT_EQ(step.error, Error::kOk); + EXPECT_EQ(step.sys_errno, 0); + + // Transient -EINTR and -EAGAIN retry up to max_retries, then fail with + // preserved errno. + for (int err : {EINTR, EAGAIN}) { + unsigned retries = 0; + for (unsigned attempt = 0; attempt < 3; ++attempt) { + step = ClassifyUringReadResult(-err, 512, 4096, retries, 3); + EXPECT_TRUE(step.retry); + EXPECT_EQ(step.next_done, 512u); + EXPECT_EQ(step.next_retries, attempt + 1); + EXPECT_EQ(step.error, Error::kOk); + retries = step.next_retries; + } + step = ClassifyUringReadResult(-err, 512, 4096, retries, 3); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.next_done, 512u); + EXPECT_EQ(step.error, Error::kIoError); + EXPECT_EQ(step.sys_errno, err); + } + + // Permanent negative errno fails immediately with errno preserved. + step = ClassifyUringReadResult(-EIO, 0, 4096, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.error, Error::kIoError); + EXPECT_EQ(step.sys_errno, EIO); + + // INT_MIN does not overflow negation. + step = ClassifyUringReadResult(std::numeric_limits::min(), 0, 4096, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.error, Error::kIoError); + EXPECT_EQ(step.sys_errno, 0); + + // Over-long completion or invalid done >= requested fails closed. + step = ClassifyUringReadResult(3000, 2000, 4096, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.error, Error::kIoError); + step = ClassifyUringReadResult(-EINTR, 0, 0, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.error, Error::kIoError); + step = ClassifyUringReadResult(10, 5000, 4096, 0); + EXPECT_FALSE(step.retry); + EXPECT_EQ(step.error, Error::kIoError); +} + +TEST(SsdReadPipeline, StreamsRefillsAndRejectsStaleEvents) { + Arena arena; + RecordingDriver driver; + auto plan = Plan(12000); + ASSERT_EQ(plan.error, Error::kOk); + ReadPipeline pipeline(std::move(plan.plan), arena.Buffers(), driver); + ASSERT_EQ(pipeline.Start(), Error::kOk); + ASSERT_EQ(driver.reads.size(), 2u); + EXPECT_EQ(pipeline.inflight(), 2u); + + auto first = driver.reads[0].token; + auto second = driver.reads[1].token; + EXPECT_EQ(pipeline.ReadDrained(first, 4096), Error::kOk); + EXPECT_EQ(pipeline.ReadDrained(first, 4096), Error::kStaleEvent); + ASSERT_EQ(driver.writes.size(), 1u); + EXPECT_EQ(pipeline.ReadDrained(second, 4096), Error::kOk); + EXPECT_EQ(pipeline.WriteDrained(first), Error::kOk); + EXPECT_EQ(pipeline.WriteDrained(first), Error::kStaleEvent); + ASSERT_EQ(driver.reads.size(), 3u); + + auto third = driver.reads[2].token; + EXPECT_EQ(third.slot_index, first.slot_index); + EXPECT_GT(third.generation, first.generation); + EXPECT_EQ(pipeline.ReadDrained(third, 3808), Error::kOk); + EXPECT_EQ(pipeline.WriteDrained(second), Error::kOk); + EXPECT_EQ(pipeline.WriteDrained(third), Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kSucceeded); + EXPECT_EQ(pipeline.inflight(), 0u); + EXPECT_EQ(pipeline.Start(), Error::kInvalidState); +} + +TEST(SsdReadPipeline, DrainsInflightSlotsOnReadAndWriteFailures) { + // Short read drains sibling read without issuing writes. + { + Arena arena; + RecordingDriver driver; + ReadPipeline pipeline(Plan(8192, 13).plan, arena.Buffers(), driver); + ASSERT_EQ(pipeline.Start(), Error::kOk); + EXPECT_EQ(pipeline.ReadDrained(driver.reads[0].token, 4095), + Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kDraining); + EXPECT_TRUE(driver.writes.empty()); + EXPECT_EQ(pipeline.ReadDrained(driver.reads[1].token, 4096), + Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kFailed); + EXPECT_EQ(pipeline.error(), Error::kIoError); + } + // Partial admission failure retains already accepted slot until drained. + { + Arena arena; + RecordingDriver driver; + driver.reject_read_after = 1; + ReadPipeline pipeline(Plan(8192).plan, arena.Buffers(), driver); + EXPECT_EQ(pipeline.Start(), Error::kIoError); + EXPECT_EQ(pipeline.state(), PipelineState::kDraining); + EXPECT_EQ(pipeline.inflight(), 1u); + EXPECT_EQ(pipeline.ReadDrained(driver.reads[0].token, 4096), + Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kFailed); + EXPECT_EQ(pipeline.inflight(), 0u); + } + // Write rejection or transfer error drains sibling slot without refilling. + { + Arena arena; + RecordingDriver driver; + driver.reject_write = true; + ReadPipeline pipeline(Plan(8192).plan, arena.Buffers(), driver); + ASSERT_EQ(pipeline.Start(), Error::kOk); + EXPECT_EQ(pipeline.ReadDrained(driver.reads[0].token, 4096), + Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kDraining); + EXPECT_EQ(pipeline.ReadDrained(driver.reads[1].token, 4096), + Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kFailed); + EXPECT_EQ(pipeline.error(), Error::kTransferError); + } + { + Arena arena; + RecordingDriver driver; + ReadPipeline pipeline(Plan(12000).plan, arena.Buffers(), driver); + ASSERT_EQ(pipeline.Start(), Error::kOk); + ASSERT_EQ(pipeline.ReadDrained(driver.reads[0].token, 4096), + Error::kOk); + ASSERT_EQ(pipeline.ReadDrained(driver.reads[1].token, 4096), + Error::kOk); + EXPECT_EQ(pipeline.WriteDrained(driver.writes[0].token, + Error::kTransferError), + Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kDraining); + EXPECT_EQ(driver.reads.size(), 2u); + EXPECT_EQ(pipeline.WriteDrained(driver.writes[1].token), Error::kOk); + EXPECT_EQ(pipeline.state(), PipelineState::kFailed); + } +} + +TEST(SsdReadPipeline, RejectsInvalidArenaOrTamperedPlanAndHandlesEmptyPlan) { + Arena arena; + for (auto buffers : + {std::vector{}, std::vector{{nullptr, 4096}}, + std::vector{{arena.first.data(), 1}}, + std::vector{{arena.first.data() + 1, 4096}}, + std::vector{{arena.first.data(), 4096}, + {arena.first.data(), 4096}}}) { + RecordingDriver driver; + ReadPipeline pipeline(Plan(1).plan, buffers, driver); + EXPECT_EQ(pipeline.Start(), Error::kInvalidArgument); + EXPECT_TRUE(driver.reads.empty()); + } + for (size_t change = 0; change < 3; ++change) { + auto plan = Plan(8192).plan; + if (change == 0) + ++plan.chunks[0].fragments[0].buffer_offset; + else if (change == 1) + --plan.payload_bytes; + else + plan.chunks[0].payload_bytes = 8192; + RecordingDriver driver; + ReadPipeline pipeline(std::move(plan), arena.Buffers(), driver); + EXPECT_EQ(pipeline.Start(), Error::kInvalidArgument) << change; + EXPECT_TRUE(driver.reads.empty()) << change; + } + RecordingDriver driver; + ReadPipeline empty(Plan(0).plan, {}, driver); + EXPECT_EQ(empty.Start(), Error::kOk); + EXPECT_EQ(empty.state(), PipelineState::kSucceeded); + EXPECT_TRUE(driver.reads.empty()); +} + +TEST(SsdReadPipeline, RestoresRealFileAcrossSlicesWithOutOfOrderCompletions) { + char path[] = "/tmp/mooncake-ssd-pipeline-XXXXXX"; + const int fd = mkstemp(path); + ASSERT_GE(fd, 0); + unlink(path); + std::vector source(12013); + for (size_t i = 0; i < source.size(); ++i) source[i] = std::byte(i % 251); + ASSERT_EQ(write(fd, source.data(), source.size()), + static_cast(source.size())); + + auto plan = BuildReadPlan( + {12000, 13, 0, {Destination(5, 6000, 0), Destination(7, 6000, 1)}}, + {4096, 4096, 64}); + ASSERT_EQ(plan.error, Error::kOk); + Arena arena; + RecordingDriver driver; + std::array first{}, second{}; + ReadPipeline pipeline(std::move(plan.plan), arena.Buffers(), driver); + ASSERT_EQ(pipeline.Start(), Error::kOk); + + size_t read_cursor = 0, write_cursor = 0; + while (pipeline.state() == PipelineState::kRunning) { + const size_t read_end = driver.reads.size(); + for (size_t i = read_end; i > read_cursor; --i) { + const auto entry = driver.reads[i - 1]; + const auto bytes = + pread(fd, entry.buffer.data, entry.chunk->read_bytes, + static_cast(entry.chunk->file_offset)); + ASSERT_GE(bytes, 0); + ASSERT_EQ(pipeline.ReadDrained(entry.token, bytes), Error::kOk); + } + read_cursor = read_end; + const size_t write_end = driver.writes.size(); + for (size_t i = write_end; i > write_cursor; --i) { + const auto entry = driver.writes[i - 1]; + for (const auto& fragment : entry.chunk->fragments) { + auto& destination = fragment.destination.destination_index == 0 + ? first + : second; + ASSERT_LE( + fragment.destination.offset + fragment.destination.length, + destination.size()); + std::memcpy(destination.data() + fragment.destination.offset, + entry.buffer.data + fragment.buffer_offset, + fragment.destination.length); + } + ASSERT_EQ(pipeline.WriteDrained(entry.token), Error::kOk); + } + write_cursor = write_end; + } + close(fd); + ASSERT_EQ(pipeline.state(), PipelineState::kSucceeded); + EXPECT_EQ(std::memcmp(first.data() + 5, source.data() + 13, 6000), 0); + EXPECT_EQ(std::memcmp(second.data() + 7, source.data() + 6013, 6000), 0); + EXPECT_EQ(first[4], std::byte{0}); + EXPECT_EQ(second[6007], std::byte{0}); +} + +} // namespace +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/tests/ssd_read_source_test.cpp b/mooncake-store/tests/ssd_read_source_test.cpp new file mode 100644 index 00000000000..225442994db --- /dev/null +++ b/mooncake-store/tests/ssd_read_source_test.cpp @@ -0,0 +1,132 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +#include "ssd_read_source.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace mooncake::ssd_offload { +namespace { + +class SourceFile { + public: + SourceFile() { + char name[] = "/tmp/mooncake-ssd-source-XXXXXX"; + fd = mkstemp(name); + path = name; + bytes.resize(12017); + for (size_t i = 0; i < bytes.size(); ++i) bytes[i] = std::byte(i % 251); + if (fd >= 0) written = write(fd, bytes.data(), bytes.size()); + } + ~SourceFile() { + if (fd >= 0) close(fd); + unlink(path.c_str()); + } + int fd{-1}; + ssize_t written{-1}; + std::string path; + std::vector bytes; +}; + +TEST(SsdReadSource, ReadsRealFileAndExposesBlockingNativeFd) { + SourceFile file; + ASSERT_GE(file.fd, 0); + ASSERT_EQ(file.written, static_cast(file.bytes.size())); + auto result = OpenPosixReadSource(file.path, file.bytes.size()); + ASSERT_EQ(result.error, Error::kOk); + ASSERT_TRUE(result.source); + ASSERT_TRUE(result.source->native_read_fd()); + EXPECT_EQ(fcntl(*result.source->native_read_fd(), F_GETFL) & O_NONBLOCK, 0); + EXPECT_EQ(result.source->file_bytes(), file.bytes.size()); + std::array buffer{}; + auto read = result.source->ReadAt(buffer, 617); + ASSERT_EQ(read.error, Error::kOk); + ASSERT_EQ(read.bytes, buffer.size()); + EXPECT_EQ( + std::memcmp(buffer.data(), file.bytes.data() + 617, buffer.size()), 0); +} + +TEST(SsdReadSource, ReportsShortReadAtEof) { + SourceFile file; + auto result = OpenPosixReadSource(file.path, file.bytes.size()); + ASSERT_EQ(result.error, Error::kOk); + std::array buffer{}; + auto read = result.source->ReadAt(buffer, file.bytes.size() - 5); + EXPECT_EQ(read.error, Error::kOk); + EXPECT_EQ(read.bytes, 5u); + EXPECT_EQ(std::memcmp(buffer.data(), + file.bytes.data() + file.bytes.size() - 5, 5), + 0); +} + +TEST(SsdReadSource, RejectsShortFileDirectoryAndMissingPath) { + SourceFile file; + EXPECT_EQ(OpenPosixReadSource(file.path, file.bytes.size() + 1).error, + Error::kInvalidArgument); + const auto directory = file.path + ".directory"; + std::filesystem::create_directory(directory); + EXPECT_EQ(OpenPosixReadSource(directory, 1).error, Error::kInvalidArgument); + std::filesystem::remove(directory); + EXPECT_EQ(OpenPosixReadSource(file.path + ".missing", 1).error, + Error::kIoError); +} + +TEST(SsdReadSource, PinsFileAndLifetimeAfterUnlink) { + SourceFile file; + auto destroyed = std::make_shared>(false); + auto lifetime = std::shared_ptr(new int(0), [destroyed](void* value) { + delete static_cast(value); + destroyed->store(true); + }); + auto result = OpenPosixReadSource(file.path, file.bytes.size(), lifetime); + ASSERT_EQ(result.error, Error::kOk); + lifetime.reset(); + ASSERT_EQ(unlink(file.path.c_str()), 0); + EXPECT_FALSE(destroyed->load()); + std::array buffer{}; + EXPECT_EQ(result.source->ReadAt(buffer, 17).bytes, buffer.size()); + EXPECT_EQ(std::memcmp(buffer.data(), file.bytes.data() + 17, buffer.size()), + 0); + result.source.reset(); + EXPECT_TRUE(destroyed->load()); +} + +TEST(SsdReadSource, ChecksSignedOffsetsBeforeCallingPosix) { + SourceFile file; + auto result = OpenPosixReadSource(file.path, file.bytes.size()); + ASSERT_EQ(result.error, Error::kOk); + std::array buffer{}; + EXPECT_EQ(result.source->ReadAt(buffer, UINT64_MAX).error, + Error::kOverflow); + EXPECT_EQ(result.source->ReadAt(buffer, INT64_MAX).error, Error::kOverflow); + EXPECT_EQ(result.source->ReadAt({}, 0).bytes, 0u); +} + +TEST(SsdReadSource, RejectsFifoWithoutWaitingForAWriter) { + SourceFile file; + const auto fifo = file.path + ".fifo"; + ASSERT_EQ(mkfifo(fifo.c_str(), 0600), 0); + auto opening = std::async(std::launch::async, + [&] { return OpenPosixReadSource(fifo, 0); }); + const auto status = opening.wait_for(std::chrono::seconds(10)); + EXPECT_EQ(status, std::future_status::ready); + if (status != std::future_status::ready) { + const int writer = open(fifo.c_str(), O_WRONLY); + if (writer >= 0) close(writer); + } + EXPECT_EQ(opening.get().error, Error::kInvalidArgument); + unlink(fifo.c_str()); +} + +} // namespace +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/tests/ssd_uring_read_executor_contract_test.cpp b/mooncake-store/tests/ssd_uring_read_executor_contract_test.cpp new file mode 100644 index 00000000000..62b61b84743 --- /dev/null +++ b/mooncake-store/tests/ssd_uring_read_executor_contract_test.cpp @@ -0,0 +1,698 @@ +// Copyright 2026 KVCache.AI +// Licensed under the Apache License, Version 2.0. +// Real-kernel contract tests for UringReadExecutor and UringPipelineDriver. +#include "ssd_uring_pipeline.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct Observation { + std::atomic init_calls{0}, init_ok{0}, exits{0}, eventfds{0}; + std::atomic submit_calls{0}, submit_ok{0}, poll_calls{0}; + size_t fail_init_at{0}, fail_eventfd_at{0}; + std::atomic fail_submit_at{0}; + std::atomic fail_submit_rc{0}; + std::atomic fail_poll_at{0}; + std::atomic fail_poll_errno{0}; + std::atomic inject_ring_revents{0}; + std::atomic inject_signal_revents{0}; +}; +std::atomic observed{nullptr}; +struct Observe { + explicit Observe(Observation& value) { observed.store(&value); } + ~Observe() { observed.store(nullptr); } +}; +} // namespace + +extern "C" int __real_io_uring_queue_init(unsigned, io_uring*, unsigned); +extern "C" void __real_io_uring_queue_exit(io_uring*); +extern "C" int __real_io_uring_submit(io_uring*); +extern "C" int __real_poll(pollfd*, nfds_t, int); +extern "C" int __real_eventfd(unsigned, int); + +extern "C" int __wrap_io_uring_queue_init(unsigned depth, io_uring* ring, + unsigned flags) { + auto* observation = observed.load(); + if (observation && ++observation->init_calls == observation->fail_init_at) + return -ENOMEM; + const int result = __real_io_uring_queue_init(depth, ring, flags); + if (observation && result == 0) ++observation->init_ok; + return result; +} +extern "C" void __wrap_io_uring_queue_exit(io_uring* ring) { + __real_io_uring_queue_exit(ring); + if (auto* observation = observed.load()) ++observation->exits; +} +extern "C" int __wrap_io_uring_submit(io_uring* ring) { + if (auto* observation = observed.load()) { + const size_t call = ++observation->submit_calls; + const size_t target = observation->fail_submit_at.load(); + if (target != 0 && call >= target) { + return observation->fail_submit_rc.load(); + } + const int rc = __real_io_uring_submit(ring); + if (rc > 0) observation->submit_ok.fetch_add(size_t(rc)); + return rc; + } + return __real_io_uring_submit(ring); +} +extern "C" int __wrap_poll(pollfd* fds, nfds_t nfds, int timeout) { + if (auto* observation = observed.load()) { + if (nfds == 2) { + const size_t call = ++observation->poll_calls; + const size_t target = observation->fail_poll_at.load(); + if (target != 0 && call >= target) { + const int err = observation->fail_poll_errno.load(); + if (err != 0) { + errno = err; + return -1; + } + const short ring_ev = observation->inject_ring_revents.load(); + const short sig_ev = observation->inject_signal_revents.load(); + if (ring_ev != 0 && fds[0].fd >= 0) { + fds[0].revents = ring_ev; + fds[1].revents = 0; + return 1; + } + if (sig_ev != 0 && fds[1].fd >= 0) { + fds[0].revents = 0; + fds[1].revents = sig_ev; + return 1; + } + } + } + } + return __real_poll(fds, nfds, timeout); +} +extern "C" int __wrap_eventfd(unsigned initial, int flags) { + auto* observation = observed.load(); + if (observation && + ++observation->eventfds == observation->fail_eventfd_at) { + errno = EMFILE; + return -1; + } + return __real_eventfd(initial, flags); +} + +namespace mooncake::ssd_offload { +namespace { +using namespace std::chrono_literals; + +constexpr size_t kSlot = 4096; +constexpr size_t kPayload = 30000; +constexpr size_t kPrefix = 37; +constexpr size_t kFirst = 7777; + +struct File { + char path[64] = "/tmp/mooncake_uring_executor_XXXXXX"; + std::vector bytes; + explicit File(size_t salt) : bytes(kPayload + kPrefix) { + for (size_t i = 0; i < bytes.size(); ++i) + bytes[i] = std::byte((i * 37 + i / 251 + salt) % 256); + const int fd = mkstemp(path); + if (fd < 0) throw std::runtime_error("mkstemp"); + size_t done = 0; + while (done < bytes.size()) { + const auto result = + ::write(fd, bytes.data() + done, bytes.size() - done); + if (result < 0 && errno == EINTR) continue; + if (result <= 0) { + close(fd); + unlink(path); + throw std::runtime_error("fixture write"); + } + done += size_t(result); + } + close(fd); + } + ~File() { unlink(path); } +}; + +struct Arena { + std::byte* data{nullptr}; + size_t count; + explicit Arena(size_t count = 2) : count(count) { + void* value = nullptr; + if (posix_memalign(&value, kSlot, count * kSlot) != 0) + throw std::bad_alloc(); + data = static_cast(value); + std::memset(data, 0xA5, count * kSlot); + } + ~Arena() { free(data); } + std::vector buffers() const { + std::vector result; + for (size_t i = 0; i < count; ++i) + result.push_back({data + i * kSlot, kSlot}); + return result; + } +}; + +struct GateState { + std::mutex mutex; + std::condition_variable changed; + size_t entered{0}; + bool open{false}; + void Block() { + std::unique_lock lock(mutex); + ++entered; + changed.notify_all(); + changed.wait(lock, [&] { return open; }); + } + bool Wait(size_t count = 1) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, 10s, [&] { return entered >= count; }); + } + void Open() { + std::lock_guard lock(mutex); + open = true; + changed.notify_all(); + } +}; + +struct ReleaseGate { + std::shared_ptr state; + ~ReleaseGate() { state->Open(); } +}; + +struct Target final : WriteTarget { + std::vector bytes = + std::vector(64 + kPayload + 97 + 64, std::byte{0xA5}); + std::shared_ptr gate; + Error Write(const ReadChunk& chunk, SlotBuffer slot) noexcept override { + if (gate) gate->Block(); + for (const auto& fragment : chunk.fragments) { + std::memcpy(bytes.data() + fragment.destination.offset, + slot.data + fragment.buffer_offset, + size_t(fragment.destination.length)); + } + return Error::kOk; + } +}; + +ReadPlan MakePlan() { + return BuildReadPlan( + {kPayload, + kPrefix, + 0, + {{0, 64, kFirst}, {0, 64 + kFirst + 97, kPayload - kFirst}}}, + {kSlot, 1, 32}) + .plan; +} + +std::shared_ptr OpenSource(const File& file) { + return OpenPosixReadSource(file.path, file.bytes.size()).source; +} + +std::vector Expected(const File& file) { + std::vector result(64 + kPayload + 97 + 64, std::byte{0xA5}); + std::copy_n(file.bytes.begin() + kPrefix, kFirst, result.begin() + 64); + std::copy(file.bytes.begin() + kPrefix + kFirst, file.bytes.end(), + result.begin() + 64 + kFirst + 97); + return result; +} + +bool Drain(ReadPipeline& pipeline, PipelineDriver& driver) { + const auto until = std::chrono::steady_clock::now() + 10s; + while (pipeline.inflight() && std::chrono::steady_clock::now() < until) { + IoCompletion completion; + if (!driver.WaitForEvent(completion, 50ms)) continue; + if (completion.stage == SlotStage::kReading) { + EXPECT_EQ(pipeline.ReadDrained(completion.token, completion.bytes, + completion.result), + Error::kOk); + } else { + EXPECT_EQ(completion.stage, SlotStage::kWriting); + EXPECT_EQ( + pipeline.WriteDrained(completion.token, completion.result), + Error::kOk); + } + } + return pipeline.inflight() == 0; +} + +struct DriverBeforePlanRelease { + std::unique_ptr& driver; + ~DriverBeforePlanRelease() { driver.reset(); } +}; + +size_t OpenFdCount() { + return size_t( + std::distance(std::filesystem::directory_iterator("/proc/self/fd"), + std::filesystem::directory_iterator{})); +} + +bool KernelUringAvailable() { + io_uring ring{}; + if (__real_io_uring_queue_init(2, &ring, 0) < 0) return false; + io_uring_probe* probe = io_uring_get_probe_ring(&ring); + bool supported = + probe && io_uring_opcode_supported(probe, IORING_OP_READ) != 0; + if (probe) { +#if defined(IO_URING_VERSION_MAJOR) && IO_URING_VERSION_MAJOR >= 2 + io_uring_free_probe(probe); +#else + std::free(probe); +#endif + } + if (supported) { + auto* sqe = io_uring_get_sqe(&ring); + if (!sqe) { + supported = false; + } else { + io_uring_prep_nop(sqe); + int enter_rc; + do { + enter_rc = io_uring_submit_and_wait(&ring, 1); + } while (enter_rc == -EINTR); + io_uring_cqe* cqe = nullptr; + if (enter_rc < 0 || io_uring_peek_cqe(&ring, &cqe) != 0) { + supported = false; + } else { + supported = cqe->res >= 0; + io_uring_cqe_seen(&ring, cqe); + } + } + } + __real_io_uring_queue_exit(&ring); + return supported; +} + +class PersistentKernel : public testing::TestWithParam {}; + +TEST_P(PersistentKernel, ReusesWorkerRingsAcrossRequestsAndVerifiesPayload) { + if (!KernelUringAvailable()) GTEST_SKIP() << "io_uring unavailable"; + const size_t workers = GetParam(); + Observation observation; + Observe scope(observation); + auto reader = UringReadExecutor::Create(workers, 8); + ASSERT_TRUE(reader); + EXPECT_TRUE(reader->healthy()); + BoundedExecutor writes(2, 8); + + for (size_t request = 1; request <= 3; ++request) { + File file(request * 71); + auto source = OpenSource(file); + ASSERT_TRUE(source); + auto plan = MakePlan(); + std::vector chunk_sources(plan.chunks.size(), 0); + auto target = std::make_shared(); + Arena arena; + auto made = UringPipelineDriver::Create( + {source}, chunk_sources, target, reader, writes, arena.buffers()); + ASSERT_EQ(made.error, Error::kOk); + ASSERT_TRUE(made.driver); + ReadPipeline pipeline(std::move(plan), arena.buffers(), *made.driver); + DriverBeforePlanRelease cleanup{made.driver}; + ASSERT_EQ(pipeline.Start(), Error::kOk); + ASSERT_TRUE(Drain(pipeline, *made.driver)); + EXPECT_EQ(pipeline.state(), PipelineState::kSucceeded); + EXPECT_EQ(target->bytes, Expected(file)); + EXPECT_EQ(observation.init_ok.load(), workers); + EXPECT_EQ(observation.exits.load(), 0u); + } + reader->Shutdown(); + reader.reset(); + EXPECT_EQ(observation.init_calls.load(), workers); + EXPECT_EQ(observation.exits.load(), workers); +} + +INSTANTIATE_TEST_SUITE_P(OneTwoFourWorkers, PersistentKernel, + testing::Values(size_t{1}, size_t{2}, size_t{4})); + +TEST(SsdUringReadExecutorContract, + ConcurrentDriversWithIdenticalTokensDoNotCrossDeliver) { + if (!KernelUringAvailable()) GTEST_SKIP() << "io_uring unavailable"; + File first(11), second(191); + auto source_a = OpenSource(first), source_b = OpenSource(second); + ASSERT_TRUE(source_a && source_b); + Arena arena_a(1), arena_b(1); + auto target_a = std::make_shared(), + target_b = std::make_shared(); + BoundedExecutor writes(2, 8); + auto reader = UringReadExecutor::Create(2, 8); + ASSERT_TRUE(reader); + auto a = UringPipelineDriver::Create({source_a}, {0}, target_a, reader, + writes, arena_a.buffers()); + auto b = UringPipelineDriver::Create({source_b}, {0}, target_b, reader, + writes, arena_b.buffers()); + ASSERT_TRUE(a.driver && b.driver); + auto chunk_a = MakePlan().chunks.front(); + auto chunk_b = chunk_a; + const SlotToken token{0, 1, 0}; + DriverBeforePlanRelease ca{a.driver}, cb{b.driver}; + ASSERT_TRUE(a.driver->SubmitRead(token, chunk_a, arena_a.buffers()[0])); + ASSERT_TRUE(b.driver->SubmitRead(token, chunk_b, arena_b.buffers()[0])); + for (auto* pair : {&b, &a}) { + IoCompletion event; + ASSERT_TRUE(pair->driver->WaitForEvent(event, 10s)); + EXPECT_EQ(event.stage, SlotStage::kReading); + EXPECT_EQ(event.result, Error::kOk); + } + EXPECT_EQ(std::memcmp(arena_a.data, first.bytes.data() + kPrefix, kSlot), + 0); + EXPECT_EQ(std::memcmp(arena_b.data, second.bytes.data() + kPrefix, kSlot), + 0); +} + +TEST(SsdUringReadExecutorContract, + BlockedWriteHoldsSlotAndDestructorWhileSiblingCompletes) { + if (!KernelUringAvailable()) GTEST_SKIP() << "io_uring unavailable"; + File first(27), second(163); + Arena arena_a(1), arena_b(1); + BoundedExecutor writes(2, 8); + auto reader = UringReadExecutor::Create(2, 8); + ASSERT_TRUE(reader); + auto gate = std::make_shared(); + auto target_a = std::make_shared(), + target_b = std::make_shared(); + target_a->gate = gate; + auto plan_b = MakePlan(); + std::vector chunk_sources_b(plan_b.chunks.size(), 0); + auto a = UringPipelineDriver::Create({OpenSource(first)}, {0}, target_a, + reader, writes, arena_a.buffers()); + auto b = UringPipelineDriver::Create({OpenSource(second)}, chunk_sources_b, + target_b, reader, writes, + arena_b.buffers()); + ASSERT_TRUE(a.driver && b.driver); + auto chunk = MakePlan().chunks.front(); + const SlotToken token{0, 1, 0}; + ReadPipeline pipeline_b(std::move(plan_b), arena_b.buffers(), *b.driver); + DriverBeforePlanRelease ca{a.driver}, cb{b.driver}; + ReleaseGate release{gate}; + + ASSERT_TRUE(a.driver->SubmitRead(token, chunk, arena_a.buffers()[0])); + IoCompletion event; + ASSERT_TRUE(a.driver->WaitForEvent(event, 10s)); + ASSERT_EQ(event.result, Error::kOk); + ASSERT_TRUE(a.driver->SubmitWrite(token, chunk, arena_a.buffers()[0])); + ASSERT_TRUE(gate->Wait()); + EXPECT_FALSE(a.driver->SubmitRead({0, 2, 0}, chunk, arena_a.buffers()[0])); + ASSERT_EQ(pipeline_b.Start(), Error::kOk); + ASSERT_TRUE(Drain(pipeline_b, *b.driver)); + EXPECT_EQ(pipeline_b.state(), PipelineState::kSucceeded); + EXPECT_EQ(target_b->bytes, Expected(second)); + + auto closing = std::async(std::launch::async, [&] { a.driver.reset(); }); + EXPECT_EQ(closing.wait_for(20ms), std::future_status::timeout); + gate->Open(); + ASSERT_EQ(closing.wait_for(10s), std::future_status::ready); + closing.get(); +} + +TEST(SsdUringReadExecutorContract, + BackpressureAndShutdownCoverClosureDestructionAndCallbackExceptions) { + if (!KernelUringAvailable()) GTEST_SKIP() << "io_uring unavailable"; + File file(51); + auto source = OpenSource(file); + ASSERT_TRUE(source); + Arena arena(1); + auto reader = UringReadExecutor::Create(1, 1); + ASSERT_TRUE(reader); + + auto gate = std::make_shared(); + ReleaseGate release{gate}; + auto callback_gate = std::make_shared(); + ReleaseGate release_callback{callback_gate}; + struct Held { + std::shared_ptr gate; + bool armed{false}; + ~Held() { + if (armed) gate->Block(); + } + }; + auto held = std::make_shared(); + held->gate = gate; + ASSERT_TRUE(reader->WaitSubmit( + source, *source->native_read_fd(), {arena.data, kSlot}, 0, + [held, callback_gate](ReadResult) { + callback_gate->Block(); + throw std::runtime_error("caller callback"); + })); + held->armed = true; + held.reset(); + callback_gate->Open(); + ASSERT_TRUE(gate->Wait()); + + // Credit is still held while the callback closure is destroying. + auto done = std::make_shared>(); + auto finished = done->get_future(); + auto waiter = std::async(std::launch::async, [&] { + return reader->WaitSubmit( + source, *source->native_read_fd(), {arena.data, kSlot}, 0, + [done](ReadResult value) { done->set_value(value); }); + }); + EXPECT_EQ(waiter.wait_for(20ms), std::future_status::timeout); + gate->Open(); + ASSERT_EQ(waiter.wait_for(10s), std::future_status::ready); + EXPECT_TRUE(waiter.get()); + ASSERT_EQ(finished.wait_for(10s), std::future_status::ready); + EXPECT_EQ(finished.get().error, Error::kOk); + + reader->Shutdown(); + EXPECT_FALSE(reader->healthy()); + EXPECT_FALSE(reader->WaitSubmit(source, *source->native_read_fd(), + {arena.data, kSlot}, 0, [](ReadResult) {})); +} + +TEST(SsdUringReadExecutorContract, + InvalidArgsAndPartialStartupFailureLeakNoFdsOrRings) { + Observation observation; + { + Observe scope(observation); + EXPECT_FALSE(UringReadExecutor::Create(0, 1)); + EXPECT_FALSE(UringReadExecutor::Create(1, 0)); + EXPECT_FALSE(UringReadExecutor::Create(65, 8)); + EXPECT_FALSE(UringReadExecutor::Create(2, 65537)); + EXPECT_EQ(observation.init_calls.load(), 0u); + EXPECT_EQ(observation.eventfds.load(), 0u); + } + if (!KernelUringAvailable()) GTEST_SKIP() << "io_uring unavailable"; + for (bool fail_wakeup : {false, true}) { + Observation partial; + Observe scope(partial); + if (fail_wakeup) + partial.fail_eventfd_at = 2; + else + partial.fail_init_at = 2; + const auto before = OpenFdCount(); + EXPECT_FALSE(UringReadExecutor::Create(4, 8)); + EXPECT_EQ(partial.init_ok.load(), partial.exits.load()); + EXPECT_GE(partial.init_ok.load(), 1u); + EXPECT_EQ(OpenFdCount(), before); + } +} + +struct PipeReadSource final : ReadSource { + int rfd{-1}; + int wfd{-1}; + PipeReadSource() { + int fds[2] = {-1, -1}; + if (pipe2(fds, O_CLOEXEC) != 0) throw std::runtime_error("pipe2"); + rfd = fds[0]; + wfd = fds[1]; + } + ~PipeReadSource() override { + if (rfd >= 0) close(rfd); + if (wfd >= 0) close(wfd); + } + uint64_t file_bytes() const noexcept override { return 4096; } + ReadResult ReadAt(std::span, uint64_t) noexcept override { + return {0, Error::kNotSupported, 0}; + } + std::optional native_read_fd() const noexcept override { return rfd; } + void WriteBytes(std::byte fill, size_t n) const { + std::vector buf(n, fill); + size_t off = 0; + while (off < n) { + const ssize_t written = ::write(wfd, buf.data() + off, n - off); + if (written < 0 && errno == EINTR) continue; + ASSERT_GT(written, 0); + off += size_t(written); + } + } +}; + +template +bool WaitUntil(Predicate&& pred, std::chrono::milliseconds timeout = 5000ms) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + if (pred()) return true; + std::this_thread::sleep_for(1ms); + } + return pred(); +} + +TEST(SsdUringReadExecutorContract, + PermanentSubmitFailureFailsUnsubmittedAndDrainsSubmittedSafely) { + if (!KernelUringAvailable()) GTEST_SKIP() << "io_uring unavailable"; + + // Case 1: permanent io_uring_submit error with no prior submitted ops. + { + File file(91); + auto source = OpenSource(file); + ASSERT_TRUE(source); + Arena arena(1); + Observation observation; + Observe scope(observation); + auto reader = UringReadExecutor::Create(1, 4); + ASSERT_TRUE(reader); + observation.fail_submit_rc.store(-EACCES); + observation.fail_submit_at.store(1); + + auto done = std::make_shared>(); + auto future = done->get_future(); + ASSERT_TRUE(reader->WaitSubmit( + source, *source->native_read_fd(), {arena.data, kSlot}, 0, + [done](ReadResult r) { done->set_value(r); })); + ASSERT_EQ(future.wait_for(5s), std::future_status::ready); + const auto res = future.get(); + EXPECT_EQ(res.error, Error::kIoError); + EXPECT_EQ(res.sys_errno, EACCES); + EXPECT_FALSE(reader->healthy()); + reader->Shutdown(); + reader.reset(); + EXPECT_EQ(observation.exits.load(), 1u); + } + + // Case 2: one op is actively in flight in the kernel when a second op hits + // a permanent io_uring_submit failure. The unsubmitted op must fail + // immediately while the already-submitted op stays pinned (and the ring + // stays alive) until its real CQE arrives, preventing kernel DMA UAF. + { + auto pipe_source = std::make_shared(); + File file(97); + auto file_source = OpenSource(file); + ASSERT_TRUE(file_source); + Arena arena(2); + Observation observation; + Observe scope(observation); + auto reader = UringReadExecutor::Create(1, 4); + ASSERT_TRUE(reader); + + auto op1_done = std::make_shared>(); + auto op1_future = op1_done->get_future(); + ASSERT_TRUE(reader->WaitSubmit( + pipe_source, *pipe_source->native_read_fd(), {arena.data, 16}, 0, + [op1_done](ReadResult r) { op1_done->set_value(r); })); + ASSERT_TRUE( + WaitUntil([&] { return observation.submit_ok.load() >= 1u; })); + // If kernel immediately rejected pipe read at offset 0, skip only this + // sub-case cleanly rather than asserting on a completed op. + if (op1_future.wait_for(20ms) == std::future_status::timeout) { + observation.fail_submit_rc.store(-EACCES); + observation.fail_submit_at.store(observation.submit_calls.load() + + 1); + + auto op2_done = std::make_shared>(); + auto op2_future = op2_done->get_future(); + ASSERT_TRUE(reader->WaitSubmit( + file_source, *file_source->native_read_fd(), + {arena.data + kSlot, kSlot}, 0, + [op2_done](ReadResult r) { op2_done->set_value(r); })); + ASSERT_EQ(op2_future.wait_for(5s), std::future_status::ready); + const auto res2 = op2_future.get(); + EXPECT_EQ(res2.error, Error::kIoError); + EXPECT_EQ(res2.sys_errno, EACCES); + EXPECT_FALSE(reader->healthy()); + // The in-flight op1 must NOT be prematurely failed or its ring + // torn down while the kernel still holds op1's buffer. + EXPECT_EQ(op1_future.wait_for(50ms), std::future_status::timeout); + EXPECT_EQ(observation.exits.load(), 0u); + + pipe_source->WriteBytes(std::byte{0x42}, 16); + ASSERT_EQ(op1_future.wait_for(5s), std::future_status::ready); + const auto res1 = op1_future.get(); + EXPECT_EQ(res1.error, Error::kOk); + EXPECT_EQ(res1.bytes, 16u); + for (size_t i = 0; i < 16; ++i) { + EXPECT_EQ(arena.data[i], std::byte{0x42}); + } + } else { + pipe_source->WriteBytes(std::byte{0x42}, 16); + } + reader->Shutdown(); + reader.reset(); + EXPECT_EQ(observation.exits.load(), 1u); + } +} + +TEST(SsdUringReadExecutorContract, + PollErrorsDrainInFlightSubmittedOpsWithoutRingTeardownUaf) { + if (!KernelUringAvailable()) GTEST_SKIP() << "io_uring unavailable"; + enum class PollFault { kErrnoEio, kEventfdErr, kRingFdErr }; + for (PollFault fault : {PollFault::kErrnoEio, PollFault::kEventfdErr, + PollFault::kRingFdErr}) { + auto pipe_source = std::make_shared(); + Arena arena(1); + Observation observation; + Observe scope(observation); + auto reader = UringReadExecutor::Create(1, 4); + ASSERT_TRUE(reader); + + auto op_done = std::make_shared>(); + auto op_future = op_done->get_future(); + ASSERT_TRUE(reader->WaitSubmit( + pipe_source, *pipe_source->native_read_fd(), {arena.data, 16}, 0, + [op_done](ReadResult r) { op_done->set_value(r); })); + ASSERT_TRUE( + WaitUntil([&] { return observation.submit_ok.load() >= 1u; })); + if (op_future.wait_for(20ms) != std::future_status::timeout) { + pipe_source->WriteBytes(std::byte{0x5A}, 16); + reader->Shutdown(); + reader.reset(); + continue; + } + + // Wait until worker enters poll() for the in-flight op, then inject + // the poll error on the next poll call and wake via Shutdown/eventfd. + if (fault == PollFault::kErrnoEio) { + observation.fail_poll_errno.store(EIO); + } else if (fault == PollFault::kEventfdErr) { + observation.inject_signal_revents.store(POLLERR); + } else { + observation.inject_ring_revents.store(POLLERR); + } + observation.fail_poll_at.store(observation.poll_calls.load() + 1); + // Submit a second op (or let 100ms poll timeout expire) so the worker + // invokes poll() and hits the injected fault. + ASSERT_TRUE(WaitUntil([&] { return !reader->healthy(); })); + // The ring must NOT have exited and op must NOT have completed before + // the kernel finishes writing into arena.data. + EXPECT_EQ(op_future.wait_for(50ms), std::future_status::timeout); + EXPECT_EQ(observation.exits.load(), 0u); + + pipe_source->WriteBytes(std::byte{0x5A}, 16); + ASSERT_EQ(op_future.wait_for(5s), std::future_status::ready); + const auto res = op_future.get(); + EXPECT_EQ(res.error, Error::kOk); + EXPECT_EQ(res.bytes, 16u); + for (size_t i = 0; i < 16; ++i) { + EXPECT_EQ(arena.data[i], std::byte{0x5A}); + } + reader->Shutdown(); + reader.reset(); + EXPECT_EQ(observation.exits.load(), 1u); + } +} + +} // namespace +} // namespace mooncake::ssd_offload diff --git a/mooncake-store/tests/storage_backend_test.cpp b/mooncake-store/tests/storage_backend_test.cpp index ee3aca87c9a..176d8b67933 100644 --- a/mooncake-store/tests/storage_backend_test.cpp +++ b/mooncake-store/tests/storage_backend_test.cpp @@ -7726,4 +7726,81 @@ TEST_F(StorageBackendTest, BucketIndexGrowthPreservesRollbackAndRecovery) { EXPECT_EQ(recovered.GetStoreMetadata()->total_keys, keys_per_bucket); } +TEST_F(StorageBackendTest, AcquireReadSourcesPinsBucketAgainstEviction) { + for (auto policy : + {BucketEvictionPolicy::FIFO, BucketEvictionPolicy::LRU}) { + const std::string sub = + data_path + + (policy == BucketEvictionPolicy::FIFO ? "/fifo_pin" : "/lru_pin"); + ASSERT_TRUE(fs::create_directories(sub)); + FileStorageConfig config; + config.storage_filepath = sub; + BucketBackendConfig bucket_config; + bucket_config.eviction_policy = policy; + bucket_config.bucket_size_limit = 4096; + // Two 4096-byte buckets (~8.3 KiB with metadata) fit under 10000 bytes, + // while a third bucket (~12.4 KiB) deterministically forces eviction. + bucket_config.max_total_size = 10000; + BucketStorageBackend backend(config, bucket_config); + ASSERT_TRUE(backend.Init()); + + std::string val_a(4096, 'a'), val_b(4096, 'b'), val_c(4096, 'c'), + val_d(4096, 'd'); + ASSERT_TRUE(backend.BatchOffload( + {{"pin_a", {{val_a.data(), val_a.size()}}}}, nullptr)); + ASSERT_TRUE(backend.BatchOffload( + {{"pin_b", {{val_b.data(), val_b.size()}}}}, nullptr)); + + // Pin the first bucket with AcquireReadSources. For LRU, read pin_b + // after pinning pin_a so pin_a remains the oldest bucket under both + // FIFO and LRU; eviction triggered by the third bucket must skip the + // read-pinned pin_a bucket and evict pin_b instead. + auto pinned_a = backend.AcquireReadSources({{"pin_a", val_a.size()}}, + [](size_t) { return true; }); + ASSERT_TRUE(pinned_a.has_value()); + if (policy == BucketEvictionPolicy::LRU) { + std::string tmp_b(val_b.size(), '\0'); + std::unordered_map load_b{ + {"pin_b", {tmp_b.data(), tmp_b.size()}}}; + ASSERT_TRUE(backend.BatchLoad(load_b)); + EXPECT_EQ(tmp_b, val_b); + } + + std::vector evicted_keys; + auto third = backend.BatchOffload( + {{"pin_c", {{val_c.data(), val_c.size()}}}}, nullptr, + [&](const std::vector& keys) + -> tl::expected { + evicted_keys.insert(evicted_keys.end(), keys.begin(), + keys.end()); + return {}; + }); + ASSERT_TRUE(third.has_value()); + EXPECT_EQ(evicted_keys, std::vector{"pin_b"}); + EXPECT_TRUE(*backend.IsExist("pin_a")); + EXPECT_FALSE(*backend.IsExist("pin_b")); + EXPECT_TRUE(*backend.IsExist("pin_c")); + + // When every bucket is read-pinned, eviction cannot free space and must + // fail fast with FILE_WRITE_FAIL rather than stalling in + // FinalizeEviction. + auto pinned_c = backend.AcquireReadSources({{"pin_c", val_c.size()}}, + [](size_t) { return true; }); + ASSERT_TRUE(pinned_c.has_value()); + const auto start = std::chrono::steady_clock::now(); + auto fourth = backend.BatchOffload( + {{"pin_d", {{val_d.data(), val_d.size()}}}}, nullptr); + const auto elapsed = std::chrono::steady_clock::now() - start; + ASSERT_FALSE(fourth.has_value()); + EXPECT_EQ(fourth.error(), ErrorCode::FILE_WRITE_FAIL); + EXPECT_LT(elapsed, std::chrono::seconds(2)); + EXPECT_TRUE(*backend.IsExist("pin_a")); + EXPECT_TRUE(*backend.IsExist("pin_c")); + EXPECT_FALSE(*backend.IsExist("pin_d")); + + pinned_c->sources.clear(); + pinned_a->sources.clear(); + } +} + } // namespace mooncake::test