From 1e752da590096a1b9ffe91e9963c3b8fcd037441 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 1 Dec 2026 10:15:03 +0300 Subject: [PATCH] feat(io): add positional File workers, sync, bounded shutdown core, and epoll D1 fixes (S-IO-03) --- include/Void/IO/Detail/Backend.hpp | 51 + include/Void/IO/Driver.hpp | 53 + include/Void/IO/File.hpp | 198 +++ include/Void/IO/Types.hpp | 30 + src/IO/EpollDriver.cpp | 1859 +++++++++++++++++++----- src/IO/FileWorkers.cpp | 743 ++++++++++ src/IO/FileWorkers.hpp | 267 ++++ tests/standalone/IO/IoFile.cpp | 2124 ++++++++++++++++++++++++++++ 8 files changed, 5000 insertions(+), 325 deletions(-) create mode 100644 include/Void/IO/File.hpp create mode 100644 src/IO/FileWorkers.cpp create mode 100644 src/IO/FileWorkers.hpp create mode 100644 tests/standalone/IO/IoFile.cpp diff --git a/include/Void/IO/Detail/Backend.hpp b/include/Void/IO/Detail/Backend.hpp index 2249ec2..e536730 100644 --- a/include/Void/IO/Detail/Backend.hpp +++ b/include/Void/IO/Detail/Backend.hpp @@ -3,15 +3,19 @@ #include #include #include +#include #include #include #include #include #include +#include +#include #include #include #include +#include #include namespace Void::IO @@ -23,6 +27,7 @@ namespace detail { class StreamState; +class FileState; enum class Direction { read, @@ -73,6 +78,52 @@ public: [[nodiscard]] virtual Void::Result::Result shutdown_and_join() = 0; [[nodiscard]] virtual DriverTelemetry telemetry() const noexcept = 0; + // ── Positional files (bounded worker pool shared by every backend) ────── + [[nodiscard]] virtual Void::Result::Result> + open_file(const std::filesystem::path& path, const FileOpenOptions& options) = 0; + [[nodiscard]] virtual Void::Result::Result> + adopt_file_fd(int fd) = 0; + [[nodiscard]] virtual Void::Result::Result start_file_workers() = 0; + [[nodiscard]] virtual Void::Result::Result + run_file_work(std::size_t max_requests) = 0; + + [[nodiscard]] virtual Void::Result::Result>> + submit_file_read(const std::shared_ptr& file, + std::uint64_t offset, + std::span buf, + Async::OperationOptions options) = 0; + [[nodiscard]] virtual Void::Result::Result>> + submit_file_write(const std::shared_ptr& file, + std::uint64_t offset, + std::span buf, + Async::OperationOptions options) = 0; + [[nodiscard]] virtual Void::Result::Result>> + submit_file_sync(const std::shared_ptr& file, + SyncMode mode, + Async::OperationOptions options) = 0; + [[nodiscard]] virtual Void::Result::Result>> + submit_file_close(const std::shared_ptr& file, + Async::OperationOptions options) = 0; + + // ── Bounded shutdown core ──────────────────────────────────────────────── + // Idempotent: closes admission, cancels queued requests and records stop + // intent for active ones, then wakes the poller. Never completes, + // dispatches or frees anything itself. + virtual void begin_shutdown() noexcept = 0; + // Drives shutdown until complete, the injected-clock deadline passes or + // `stop` fires; the latter two return the current report with + // complete == false (not an error). Returns + // Async::make_async_error(AdmissionError::self_join) on one of this + // backend's file workers or inside one of its poll turns. + [[nodiscard]] virtual Void::Result::Result advance_shutdown( + std::optional deadline, + std::stop_token stop) = 0; + [[nodiscard]] virtual bool shutdown_complete() const noexcept = 0; + // No owned operations, file requests or in-flight syscalls remain. + [[nodiscard]] virtual bool quiescent() const noexcept = 0; + // Driver::~Driver only: begin + advance to completion (blocking). + virtual void teardown_blocking() noexcept = 0; + // Mock inspection / test-only control hooks (returns nullptr on non-mock backends). [[nodiscard]] virtual class MockBackend* as_mock() noexcept { return nullptr; } }; diff --git a/include/Void/IO/Driver.hpp b/include/Void/IO/Driver.hpp index e2986aa..078c33b 100644 --- a/include/Void/IO/Driver.hpp +++ b/include/Void/IO/Driver.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -9,10 +10,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include @@ -56,6 +59,22 @@ private: detail::MockBackend* backend_{nullptr}; }; +// True on any Driver's file-worker thread (never on poll or executor threads). +[[nodiscard]] bool is_io_worker_thread() noexcept; + +// The Driver owns no thread except its optional file workers. One thread at a +// time runs a poll_once turn (the poll owner); a concurrent or reentrant +// poll_once returns IoErrorCode::busy without touching any descriptor. +// +// Lifetime rules: +// - The executor must outlive the Driver. Resume tickets produced by +// shutdown/teardown are dispatched to it after poll ownership is released, +// so an owned executor must not be joined before Driver teardown. +// - ~Driver is the only blocking teardown: it begins shutdown, waits for +// in-flight syscalls and file requests, joins file workers, closes file and +// operation descriptors and delivers every pending result exactly once. +// Destroying a Driver on one of its file workers or inside one of its poll +// turns is a programmer error: it prints a diagnostic and terminates. class Driver { public: @@ -92,9 +111,43 @@ public: std::optional max_wait = std::chrono::nanoseconds{0}); void wake() noexcept; + // Equivalent to begin_shutdown(). void request_stop() noexcept; + // Blocks until shutdown is complete (shutdown with no deadline or stop). + // Returns self_join on a file worker or inside a poll turn of this Driver. [[nodiscard]] Void::Result::Result shutdown_and_join(); + // ── Positional files ───────────────────────────────────────────────────── + [[nodiscard]] Void::Result::Result open_file( + const std::filesystem::path& path, FileOpenOptions options = {}); + // Takes ownership of `fd` only on success. + [[nodiscard]] Void::Result::Result adopt_file_fd(int fd); + // Starts IoLimits::file_workers threads once (0 = none, manual stepping). + // A second call is invalid_argument; after shutdown begins it is closed; a + // failed start joins the workers already started and may be retried. + [[nodiscard]] Void::Result::Result start_file_workers(); + // Runs up to `max_requests` queued file syscalls on the calling thread and + // queues their results for the next poll turn; busy while workers run. + [[nodiscard]] Void::Result::Result run_file_work(std::size_t max_requests = 1); + + // ── Bounded shutdown ───────────────────────────────────────────────────── + // Idempotent; closes admission, cancels queued requests, records stop + // intent for active ones and wakes the poller. Never blocks or frees. + void begin_shutdown() noexcept { backend_->begin_shutdown(); } + // Advances shutdown until complete, or until options.deadline (judged by + // clock()) or options.stop, which return complete == false with every + // listed resource retained. Repeatable. + [[nodiscard]] Void::Result::Result shutdown( + Async::OperationOptions options) + { + return backend_->advance_shutdown(options.deadline, std::move(options.stop)); + } + [[nodiscard]] bool quiescent() const noexcept { return backend_->quiescent(); } + [[nodiscard]] bool shutdown_complete() const noexcept + { + return backend_->shutdown_complete(); + } + private: Driver(std::shared_ptr backend, std::shared_ptr buffer_tracker) noexcept; diff --git a/include/Void/IO/File.hpp b/include/Void/IO/File.hpp new file mode 100644 index 0000000..cecb717 --- /dev/null +++ b/include/Void/IO/File.hpp @@ -0,0 +1,198 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::IO +{ + +// Flags for Driver::open_file. read+write maps to O_RDWR, write-only to +// O_WRONLY and read-only to O_RDONLY; neither read nor write, truncate without +// write, or exclusive without create is invalid_argument. O_CLOEXEC is always +// set and open(2) runs on the calling thread with ordinary path semantics. +struct FileOpenOptions { + bool read{true}; + bool write{false}; + bool create{false}; + bool truncate{false}; + bool exclusive{false}; + std::uint32_t mode{0600}; +}; + +enum class SyncMode : std::uint8_t { + data, // fdatasync + full // fsync +}; + +// Result of one positional-file syscall: on success `error == 0` and `value` +// holds the byte count (0 for sync/close); on failure `error` is the errno. +struct FileSyscallResult { + std::int64_t value{0}; + int error{0}; +}; + +// Injectable syscall shim used by the Driver's file workers. The base class +// is the native implementation (one syscall per call, no EINTR retry; the +// Driver retries EINTR). An override runs on file workers or inside +// Driver::run_file_work(); it must not call Driver, Executor or File APIs, and +// it must outlive Driver teardown (teardown closes remaining fds through it). +class FileSyscalls +{ +public: + virtual ~FileSyscalls() = default; + + [[nodiscard]] virtual FileSyscallResult pread( + int fd, std::span buf, std::uint64_t offset) noexcept; + [[nodiscard]] virtual FileSyscallResult pwrite( + int fd, std::span buf, std::uint64_t offset) noexcept; + [[nodiscard]] virtual FileSyscallResult sync(int fd, SyncMode mode) noexcept; + [[nodiscard]] virtual FileSyscallResult close(int fd) noexcept; + + [[nodiscard]] static FileSyscalls& native() noexcept; +}; + +namespace detail +{ +class FileState; +} // namespace detail + +// Move-only handle to a positional file owned by a Driver. Requests run on +// the Driver's bounded file workers (or Driver::run_file_work) and are +// delivered only by a poll turn. +// +// - Writes and syncs on one File run in admission order, one at a time; reads +// may run concurrently and are unordered relative to writes. +// - A queued request that is stopped or expires completes cancelled/timeout +// without a syscall. An active request keeps its buffer and reports the +// syscall's actual outcome even after stop or expiry. +// - Dropping a File with requests in flight defers the close until they have +// been delivered; the close never blocks the dropping thread. +// - Unlike ByteStream::close_and_join (which consumes the stream at once), +// File::close_and_join waits for the file's queued and active requests, +// never cancels them, and invalidates the File only on success. On deadline +// or stop it returns incomplete_shutdown and the File stays valid but +// closing (new requests fail with closed; a repeated call waits again). +// - After Driver teardown every request fails with closed without a syscall +// and close_and_join succeeds immediately. +class File +{ +public: + File() noexcept; + File(File&& other) noexcept; + File& operator=(File&& other) noexcept; + ~File(); + + File(const File&) = delete; + File& operator=(const File&) = delete; + + [[nodiscard]] bool valid() const noexcept { return state_ != nullptr; } + [[nodiscard]] DescriptorId id() const noexcept; + + [[nodiscard]] Coro::Task> read_at( + std::uint64_t offset, std::span buf, Async::OperationOptions options = {}); + [[nodiscard]] Coro::Task> write_at( + std::uint64_t offset, std::span buf, Async::OperationOptions options = {}); + + [[nodiscard]] Coro::Task> read_at_owned( + std::uint64_t offset, BufferLease& lease, Async::OperationOptions options = {}) + { + auto res = co_await read_at(offset, lease.writable(), std::move(options)); + if (res.has_value()) { + lease.set_valid_bytes(res->bytes); + } + co_return res; + } + + [[nodiscard]] Coro::Task> write_at_owned( + std::uint64_t offset, const BufferLease& lease, Async::OperationOptions options = {}) + { + co_return co_await write_at(offset, lease.readable(), std::move(options)); + } + + [[nodiscard]] Coro::Task> sync( + SyncMode mode = SyncMode::full, Async::OperationOptions options = {}); + [[nodiscard]] Coro::Task> close_and_join( + Async::OperationOptions options = {}); + +private: + friend class Driver; // the only producer of open Files + + explicit File(std::shared_ptr state) noexcept; + + void release_handle() noexcept; + + std::shared_ptr state_{}; +}; + +// Composed positional transfers mirroring read_exact/write_all: the offset +// advances with each chunk and one deadline/stop applies to the whole call. +[[nodiscard]] inline Coro::Task> + read_exact_at(File& file, + std::uint64_t offset, + std::span buf, + Async::OperationOptions options = {}) +{ + std::size_t total = 0; + while (total < buf.size()) { + if (options.stop.stop_requested()) { + co_return std::unexpected{ComposedTransferError{ + total, + false, + make_io_error(IoErrorCode::cancelled, "read_exact_at stopped before completion")}}; + } + const auto chunk = co_await file.read_at(offset + total, buf.subspan(total), options); + if (!chunk.has_value()) { + co_return std::unexpected{ComposedTransferError{total, false, chunk.error()}}; + } + total += chunk->bytes; + if (total < buf.size() && chunk->eof) { + co_return std::unexpected{ComposedTransferError{ + total, + true, + make_io_error(IoErrorCode::eof, "Unexpected EOF before read_exact_at finished")}}; + } + } + co_return total; +} + +[[nodiscard]] inline Coro::Task> + write_all_at(File& file, + std::uint64_t offset, + std::span buf, + Async::OperationOptions options = {}) +{ + std::size_t total = 0; + while (total < buf.size()) { + if (options.stop.stop_requested()) { + co_return std::unexpected{ComposedTransferError{ + total, + false, + make_io_error(IoErrorCode::cancelled, "write_all_at stopped before completion")}}; + } + const auto chunk = co_await file.write_at(offset + total, buf.subspan(total), options); + if (!chunk.has_value()) { + co_return std::unexpected{ComposedTransferError{total, false, chunk.error()}}; + } + if (chunk->bytes == 0) { + // A zero-byte pwrite with bytes remaining makes no progress; report + // it instead of looping. + co_return std::unexpected{ComposedTransferError{ + total, + false, + make_io_error(IoErrorCode::os_error, "pwrite made no progress in write_all_at")}}; + } + total += chunk->bytes; + } + co_return total; +} + +} // namespace Void::IO diff --git a/include/Void/IO/Types.hpp b/include/Void/IO/Types.hpp index bd2c93f..fbada2a 100644 --- a/include/Void/IO/Types.hpp +++ b/include/Void/IO/Types.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -120,6 +121,11 @@ struct IoLimits { IoErrorCode::invalid_argument, "IoLimits descriptor, operation, control, and turn bounds must be non-zero")}; } + if (limits.max_file_queue == 0) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, + "IoLimits max_file_queue must be non-zero")}; + } return {}; } @@ -129,9 +135,18 @@ enum class BackendPreference { mock }; +class FileSyscalls; + struct BackendOptions { IoLimits limits{}; BackendPreference preference{BackendPreference::auto_native}; + // Borrowed positional-file syscall shim (nullptr = FileSyscalls::native()). + // It runs on file workers or in run_file_work(), must not call Driver, + // Executor or File APIs, and must outlive Driver teardown. + FileSyscalls* file_syscalls{nullptr}; + // Called before each file worker thread is created with its index; an + // error aborts start_file_workers() exactly like a thread-creation failure. + std::function(std::size_t)> before_file_worker_start{}; }; struct DescriptorId { @@ -150,6 +165,21 @@ struct DriverTelemetry { std::uint64_t turns{0}; std::uint64_t wakeups{0}; std::uint64_t stale_events_ignored{0}; + std::size_t queued_file_requests{0}; + std::size_t active_file_requests{0}; + std::size_t file_workers_running{0}; + // Cancel/expiry/shutdown paths that met an already-retired op and skipped it. + std::uint64_t duplicate_completions_ignored{0}; +}; + +// Snapshot returned by Driver::shutdown(). `complete == false` means the +// bounded call expired (deadline or stop) and everything listed is retained. +struct DriverShutdownReport { + bool complete{false}; + std::size_t pending_operations{0}; + std::size_t active_file_requests{0}; + std::size_t open_descriptors{0}; + std::size_t retained_buffer_bytes{0}; }; namespace detail diff --git a/src/IO/EpollDriver.cpp b/src/IO/EpollDriver.cpp index c6c982b..7c3b729 100644 --- a/src/IO/EpollDriver.cpp +++ b/src/IO/EpollDriver.cpp @@ -1,24 +1,36 @@ #include +#include "FileWorkers.hpp" + #include #include #include #include +#include +#include #include +#include +#include +#include #include #include #include +#include #include #include #include +#if defined(__unix__) || defined(__APPLE__) +#include +#include +#endif + #ifdef __linux__ #include #include #include #include #include -#include #endif namespace Void::IO::detail @@ -87,6 +99,55 @@ void dispatch_tickets(std::vector& tickets) } tickets.clear(); } + +// Per-thread stack of the backends whose poll turn (or shutdown slice) the +// thread is running. A stack (not a single pointer) keeps nested turns of +// other drivers correct and detects reentrancy at any depth. +struct PollFrame { + const void* backend{nullptr}; + const PollFrame* prev{nullptr}; +}; + +thread_local const PollFrame* tl_poll_frames = nullptr; + +[[nodiscard]] bool in_poll_turn_of(const void* backend) noexcept +{ + for (const PollFrame* f = tl_poll_frames; f != nullptr; f = f->prev) { + if (f->backend == backend) { + return true; + } + } + return false; +} + +class PollFrameGuard +{ +public: + explicit PollFrameGuard(const void* backend) noexcept + : frame_{backend, tl_poll_frames} + { + tl_poll_frames = &frame_; + } + + ~PollFrameGuard() + { + tl_poll_frames = frame_.prev; + } + + PollFrameGuard(const PollFrameGuard&) = delete; + PollFrameGuard& operator=(const PollFrameGuard&) = delete; + +private: + PollFrame frame_; +}; + +#if defined(__unix__) || defined(__APPLE__) +constexpr std::uint64_t kFileOffsetMax = + static_cast(std::numeric_limits::max()); +#else +constexpr std::uint64_t kFileOffsetMax = + static_cast(std::numeric_limits::max()); +#endif } // namespace class BaseBackend; @@ -107,6 +168,8 @@ struct PendingOp : public std::enable_shared_from_this { std::optional deadline{}; std::shared_ptr> op_state{}; std::atomic cancel_queued{false}; + // Guarded by mu_. Epoll sets it around its syscall; the mock sets it while + // a MockController token holds the request. bool in_execution{false}; bool retired{false}; std::uint64_t mock_token{0}; @@ -127,6 +190,10 @@ struct DescriptorSlot { bool eof_seen{false}; bool epoll_registered{false}; bool epoll_out_armed{false}; + // S5: a File occupies a slot with fd == -1; socket paths skip it and the + // file descriptor lives only in FileState. + bool is_file{false}; + std::shared_ptr file{}; std::shared_ptr active_read{}; std::shared_ptr active_write{}; std::vector close_waiters{}; @@ -138,12 +205,20 @@ public: BaseBackend(Async::Executor& executor, IoLimits limits, const Void::Time::MonotonicClock& clock, - std::shared_ptr buffer_tracker) + std::shared_ptr buffer_tracker, + FileSyscalls* file_syscalls, + std::function(std::size_t)> worker_hook) : executor_(executor) , limits_(limits) , clock_(clock) , buffer_tracker_(std::move(buffer_tracker)) + , file_syscalls_(file_syscalls != nullptr ? file_syscalls : &FileSyscalls::native()) + , worker_hook_(std::move(worker_hook)) + , files_(std::make_shared(limits.max_file_queue, file_syscalls_)) + , workers_(files_) { + files_->waker = &BaseBackend::wake_trampoline; + files_->waker_ctx = this; } [[nodiscard]] const IoLimits& limits() const noexcept override { return limits_; } @@ -160,6 +235,9 @@ public: } { std::lock_guard lk{mu_}; + if (shut_down_.load(std::memory_order_acquire)) { + return; + } cancel_queue_.push_back(op); } wake(); @@ -205,6 +283,7 @@ public: std::lock_guard lk{mu_}; if (!did.valid() || did.slot >= slots_.size() || !slots_[did.slot].in_use || + slots_[did.slot].is_file || slots_[did.slot].id.generation != did.generation) { immediate_complete = true; } else { @@ -254,6 +333,7 @@ public: std::lock_guard lk{mu_}; if (id.slot < slots_.size() && slots_[id.slot].in_use && + !slots_[id.slot].is_file && slots_[id.slot].id.generation == id.generation) { auto& slot = slots_[id.slot]; slot.closing = true; @@ -279,10 +359,10 @@ public: } } + // S7: request_stop() is begin_shutdown(). void request_stop() noexcept override { - stopping_.store(true, std::memory_order_release); - wake(); + begin_shutdown(); } [[nodiscard]] DriverTelemetry telemetry() const noexcept override @@ -296,9 +376,343 @@ public: t.turns = turns_.load(std::memory_order_acquire); t.wakeups = wakeups_.load(std::memory_order_acquire); t.stale_events_ignored = stale_events_ignored_.load(std::memory_order_acquire); + t.queued_file_requests = files_->queued_count.load(std::memory_order_acquire); + t.active_file_requests = files_->active_count.load(std::memory_order_acquire); + t.file_workers_running = files_->running_count.load(std::memory_order_acquire); + t.duplicate_completions_ignored = + duplicate_completions_ignored_.load(std::memory_order_acquire); return t; } + // ── Poll ownership ─────────────────────────────────────────────────────── + + [[nodiscard]] Void::Result::Result + poll_once(std::optional max_wait) final + { + if (in_poll_turn_of(this)) { + return std::unexpected{make_io_error( + IoErrorCode::busy, "poll_once called from inside this Driver's poll turn")}; + } + if (shut_down_.load(std::memory_order_acquire)) { + return std::size_t{0}; + } + if (shutdown_waiting_.load(std::memory_order_acquire) != 0) { + return std::unexpected{make_io_error( + IoErrorCode::busy, "IO Driver shutdown owns the poll")}; + } + std::unique_lock lk{poll_mu_, std::try_to_lock}; + if (!lk.owns_lock()) { + return std::unexpected{make_io_error( + IoErrorCode::busy, "Another thread is running a poll_once turn")}; + } + if (shut_down_.load(std::memory_order_acquire)) { + return std::size_t{0}; + } + PollFrameGuard guard{this}; + turns_.fetch_add(1, std::memory_order_acq_rel); + return run_turn(max_wait); + } + + // ── Positional files ───────────────────────────────────────────────────── + + [[nodiscard]] Void::Result::Result> + open_file(const std::filesystem::path& path, const FileOpenOptions& options) override + { + if (auto v = validate_file_open_options(options); !v.has_value()) { + return std::unexpected{std::move(v.error())}; + } + auto reserved = reserve_file_slot(); + if (!reserved.has_value()) { + return std::unexpected{std::move(reserved.error())}; + } + auto fd = open_file_native(path, options); + if (!fd.has_value()) { + release_reserved_file_slot(*reserved); + return std::unexpected{std::move(fd.error())}; + } + return install_file(*reserved, *fd, true); + } + + [[nodiscard]] Void::Result::Result> adopt_file_fd(int fd) override + { + if (fd < 0) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "Invalid negative fd in adopt_file_fd")}; + } + auto reserved = reserve_file_slot(); + if (!reserved.has_value()) { + return std::unexpected{std::move(reserved.error())}; + } + return install_file(*reserved, fd, false); + } + + [[nodiscard]] Void::Result::Result start_file_workers() override + { + if (shutdown_begun_.load(std::memory_order_acquire)) { + return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver is shutting down")}; + } + return workers_.start(limits_.file_workers, worker_hook_); + } + + [[nodiscard]] Void::Result::Result run_file_work(std::size_t max_requests) override + { + if (max_requests == 0) { + return std::size_t{0}; + } + auto ran = run_file_requests_inline(*files_, max_requests); + if (!ran.has_value()) { + return std::unexpected{make_io_error( + IoErrorCode::busy, "run_file_work is unavailable while file workers run")}; + } + if (*ran > 0) { + wake(); + } + return *ran; + } + + [[nodiscard]] Void::Result::Result>> + submit_file_read(const std::shared_ptr& file, + std::uint64_t offset, + std::span buf, + Async::OperationOptions options) override + { + return submit_file_transfer( + file, FileRequestKind::read, buf.data(), nullptr, buf.size(), offset, std::move(options)); + } + + [[nodiscard]] Void::Result::Result>> + submit_file_write(const std::shared_ptr& file, + std::uint64_t offset, + std::span buf, + Async::OperationOptions options) override + { + return submit_file_transfer( + file, FileRequestKind::write, nullptr, buf.data(), buf.size(), offset, std::move(options)); + } + + [[nodiscard]] Void::Result::Result>> + submit_file_sync(const std::shared_ptr& file, + SyncMode mode, + Async::OperationOptions options) override + { + if (auto pre = precheck_file_admission(file, options); !pre.has_value()) { + return std::unexpected{std::move(pre.error())}; + } + auto op = Async::OperationState::create( + options, &executor_, Async::StopBehavior::notify_only); + auto req = std::make_shared(); + req->kind = FileRequestKind::sync; + req->file = file; + req->mode = mode; + req->deadline = options.deadline; + req->void_op = op; + // The backend ref is taken before the request becomes visible to workers. + op->acquire_backend_ref(); + if (auto adm = admit_file_request(req, 0); !adm.has_value()) { + (void)op->release_backend_ref(); + return std::unexpected{std::move(adm.error())}; + } + finish_file_admission(req, op->stop_token()); + return op; + } + + [[nodiscard]] Void::Result::Result>> + submit_file_close(const std::shared_ptr& file, + Async::OperationOptions options) override + { + auto op = Async::OperationState::create( + options, &executor_, Async::StopBehavior::notify_only); + if (!file) { + (void)op->try_commit_value(); + return op; + } + const bool expired_now = + options.stop.stop_requested() || Async::is_deadline_expired(options, clock_); + auto waiter = std::make_shared(); + waiter->file = file; + waiter->op = op; + waiter->deadline = options.deadline; + + bool immediate_ok = false; + bool immediate_incomplete = false; + bool enqueued = false; + { + std::lock_guard lk{files_->mu}; + if (file->status == FileState::Status::closed) { + immediate_ok = true; + } else { + if (file->status == FileState::Status::open) { + file->status = FileState::Status::closing; + } + if (!file->close_enqueued) { + if (file->in_flight == 0) { + files_->enqueue_close_locked(*file); + enqueued = true; + } else { + file->close_pending = true; + } + } + if (expired_now) { + immediate_incomplete = true; + } else { + files_->close_waiters.push_back(waiter); + op->acquire_backend_ref(); + } + } + } + if (enqueued) { + files_->work_cv.notify_one(); + wake(); + } + if (immediate_ok) { + (void)op->try_commit_value(); + return op; + } + if (immediate_incomplete) { + (void)op->try_commit_error(make_io_error( + IoErrorCode::incomplete_shutdown, + "File close_and_join expired before the close completed")); + return op; + } + waiter->stop_cb.emplace(op->stop_token(), FileWakeForwarder{weak_from_this()}); + return op; + } + + // ── Bounded shutdown core ──────────────────────────────────────────────── + + void begin_shutdown() noexcept override + { + stopping_.store(true, std::memory_order_release); + if (!shutdown_begun_.exchange(true, std::memory_order_acq_rel)) { + { + std::lock_guard lk{files_->mu}; + files_->accepting = false; + // Queued requests are cancelled (moved to the completion queue + // for the next turn); active ones only record stop intent. + while (!files_->queued.empty()) { + FileRequest& r = *files_->queued.front(); + r.stop_requested = true; + files_->settle_queued_locked(r, FileSettle::cancelled); + } + for (auto& r : files_->active) { + r->stop_requested = true; + } + } + files_->work_cv.notify_all(); + } + wake(); + } + + [[nodiscard]] Void::Result::Result advance_shutdown( + std::optional deadline, + std::stop_token stop) override + { + if (is_own_worker_thread() || in_poll_turn_of(this)) { + return std::unexpected{Async::make_async_error( + Async::AdmissionError::self_join, + "IO Driver shutdown called on its own file worker or inside its poll turn")}; + } + // Keeps the backend alive if a dispatched continuation destroys the Driver. + const std::shared_ptr self = shared_from_this(); + begin_shutdown(); + + bool waiting = false; + for (;;) { + if (shut_down_.load(std::memory_order_acquire)) { + if (waiting) { + shutdown_waiting_.fetch_sub(1, std::memory_order_acq_rel); + } + return make_report(true); + } + // S1: announce the handoff so pollers return busy, then interrupt + // the current poller. + if (!waiting) { + shutdown_waiting_.fetch_add(1, std::memory_order_acq_rel); + waiting = true; + } + wake(); + bool owned = false; + { + std::unique_lock lk{poll_mu_, std::try_to_lock}; + if (lk.owns_lock()) { + owned = true; + shutdown_waiting_.fetch_sub(1, std::memory_order_acq_rel); + waiting = false; + std::vector tickets; + DriverShutdownReport report{}; + bool complete = false; + { + PollFrameGuard guard{this}; + complete = shut_down_.load(std::memory_order_acquire) || + shutdown_slice_locked(tickets); + report = make_report(complete); + } + lk.unlock(); + // P3-9: tickets are dispatched only after poll ownership is released. + dispatch_tickets(tickets); + if (complete) { + return report; + } + } + } + if (stop.stop_requested() || (deadline.has_value() && clock_.now() >= *deadline)) { + if (waiting) { + shutdown_waiting_.fetch_sub(1, std::memory_order_acq_rel); + } + return make_report(false); + } + wait_shutdown_slice(owned); + } + } + + [[nodiscard]] bool shutdown_complete() const noexcept override + { + return shut_down_.load(std::memory_order_acquire); + } + + [[nodiscard]] bool quiescent() const noexcept override + { + if (active_operations_.load(std::memory_order_acquire) != 0) { + return false; + } + std::lock_guard lk{files_->mu}; + return files_->queued.empty() && files_->active.empty() && + files_->completions.empty() && files_->close_queued.empty() && + files_->close_waiters.empty(); + } + + void teardown_blocking() noexcept override + { + if (is_own_worker_thread() || in_poll_turn_of(this)) { + std::fputs( + "Void::IO: Driver destroyed on one of its file workers or inside one of its " + "poll turns; terminating\n", + stderr); + std::terminate(); + } + for (;;) { + auto res = advance_shutdown(std::nullopt, {}); + if (!res.has_value()) { + std::fputs("Void::IO: Driver teardown could not shut down; terminating\n", stderr); + std::terminate(); + } + if (res->complete) { + break; + } + } + after_teardown(); + } + + [[nodiscard]] Void::Result::Result shutdown_and_join() final + { + auto res = advance_shutdown(std::nullopt, {}); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return {}; + } + protected: struct ControlAction { enum class Type { @@ -310,6 +724,48 @@ protected: DescriptorId id{}; }; + // One poll turn; called with poll_mu_ held and the poll frame pushed. + [[nodiscard]] virtual Void::Result::Result + run_turn(std::optional max_wait) = 0; + // Backend cancel/control queues, run by shutdown slices. + virtual std::size_t drain_socket_queues(std::vector& tickets) = 0; + // Stopping: the slot's interest is dropped (poll owner only, mu_ held). + virtual void on_slot_abort_locked(DescriptorSlot&) noexcept {} + // Shutdown step 5 for socket slots (mu_ held): close the native fd. + [[nodiscard]] virtual bool closes_native_fds() const noexcept { return false; } + virtual void on_slot_final_close_locked(DescriptorSlot&) noexcept {} + // Shutdown step 6 (after shut_down_). + virtual void on_shutdown_complete() noexcept {} + // Mock: complete requests still held by MockController tokens. + virtual void after_teardown() noexcept {} + + [[nodiscard]] static std::uint64_t to_u64(std::size_t v) noexcept + { + return static_cast(v); + } + + static void wake_trampoline(void* ctx) noexcept + { + static_cast(ctx)->wake(); + } + + [[nodiscard]] bool is_own_worker_thread() const noexcept + { + return current_io_worker_owner() == files_.get(); + } + + [[nodiscard]] bool try_reserve_operation() noexcept + { + std::size_t cur = active_operations_.load(std::memory_order_acquire); + while (cur < limits_.max_operations) { + if (active_operations_.compare_exchange_weak( + cur, cur + 1, std::memory_order_acq_rel, std::memory_order_acquire)) { + return true; + } + } + return false; + } + [[nodiscard]] Void::Result::Result allocate_slot_locked(int fd) { if (stopping_.load(std::memory_order_acquire)) { @@ -345,6 +801,8 @@ protected: s.eof_seen = false; s.epoll_registered = false; s.epoll_out_armed = false; + s.is_file = false; + s.file.reset(); s.active_read.reset(); s.active_write.reset(); s.close_waiters.clear(); @@ -352,14 +810,15 @@ protected: return s.id; } + // Callers move `file` out first so no FileState is destroyed under mu_. void release_slot_locked(std::uint32_t idx, bool close_native_fd) noexcept { if (idx >= slots_.size() || !slots_[idx].in_use) { return; } auto& s = slots_[idx]; -#ifdef __linux__ - if (close_native_fd && s.fd >= 0) { +#if defined(__unix__) || defined(__APPLE__) + if (close_native_fd && s.fd >= 0 && !s.is_file) { ::close(s.fd); } #else @@ -372,6 +831,8 @@ protected: s.eof_seen = false; s.epoll_registered = false; s.epoll_out_armed = false; + s.is_file = false; + s.file.reset(); s.active_read.reset(); s.active_write.reset(); free_slots_.push_back(idx); @@ -392,6 +853,7 @@ protected: return; } op.retired = true; + op.in_execution = false; active_operations_.fetch_sub(1, std::memory_order_acq_rel); if (op.len > 0) { borrowed_buffer_bytes_.fetch_sub(op.len, std::memory_order_acq_rel); @@ -418,13 +880,20 @@ protected: } } - void complete_op_and_collect_tickets(const std::shared_ptr& op, + // D1 retire-once: settles the op and releases its backend ref only if this + // call retired it. A cancel/expiry/shutdown path that meets an op already + // retired is counted in duplicate_completions_ignored and skipped. + bool complete_op_and_collect_tickets(const std::shared_ptr& op, const Void::Result::Result& res, std::vector& out_tickets, std::vector& close_waiters) { { std::lock_guard lk{mu_}; + if (op->retired) { + duplicate_completions_ignored_.fetch_add(1, std::memory_order_acq_rel); + return false; + } retire_op_locked(*op, close_waiters); } if (res.has_value()) { @@ -448,6 +917,13 @@ protected: if (auto t = op->op_state->release_backend_ref(); t.has_value()) { out_tickets.push_back(std::move(*t)); } + commit_close_waiters(close_waiters, out_tickets); + return true; + } + + static void commit_close_waiters(std::vector& close_waiters, + std::vector& out_tickets) + { for (auto& cw : close_waiters) { if (auto t = cw.op_state->try_commit_value(); t.has_value()) { out_tickets.push_back(std::move(*t)); @@ -464,19 +940,501 @@ protected: Direction dir, const std::shared_ptr& op) = 0; + // ── Stopping and shutdown helpers (poll owner) ─────────────────────────── + + // While stopping: pending socket ops that are not executing complete with + // `closed`; their slots stop receiving readiness so a stopping turn does + // not spin; streams already asked to close are released. + std::size_t abort_pending_socket_ops(std::vector& tickets) + { + std::vector> to_abort; + { + std::lock_guard lk{mu_}; + for (auto& s : slots_) { + if (!s.in_use || s.is_file) { + continue; + } + s.closing = true; + on_slot_abort_locked(s); + for (auto* op : {&s.active_read, &s.active_write}) { + if (*op && !(*op)->retired && !(*op)->in_execution) { + to_abort.push_back(*op); + } + } + } + } + std::size_t done = 0; + std::vector close_waiters; + for (const auto& op : to_abort) { + if (complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error(IoErrorCode::closed, "IO Driver shut down")}, + tickets, + close_waiters)) { + ++done; + } + } + { + std::lock_guard lk{mu_}; + for (std::uint32_t idx = 0; idx < slots_.size(); ++idx) { + auto& s = slots_[idx]; + if (s.in_use && !s.is_file && s.close_enqueued && !s.active_read && + !s.active_write) { + on_slot_final_close_locked(s); + close_waiters.insert( + close_waiters.end(), + std::make_move_iterator(s.close_waiters.begin()), + std::make_move_iterator(s.close_waiters.end())); + s.close_waiters.clear(); + release_slot_locked(idx, closes_native_fds()); + ++done; + } + } + } + commit_close_waiters(close_waiters, tickets); + return done; + } + + std::size_t drain_for_shutdown(std::vector& tickets) + { + std::size_t work = drain_socket_queues(tickets); + work += drain_file_completions(tickets); + work += scan_close_waiters(std::nullopt, tickets); + work += abort_pending_socket_ops(tickets); + if (file_deadlines_pending()) { + const auto now = clock_.now(); + work += expire_file_work_at(now, tickets); + work += drain_file_completions(tickets); + } + return work; + } + + // S2 steps 2-6, called with poll_mu_ held. Returns true once complete. + bool shutdown_slice_locked(std::vector& tickets) + { + (void)drain_for_shutdown(tickets); + bool ready = false; + { + std::lock_guard lk{files_->mu}; + ready = files_->queued.empty() && files_->active.empty(); + if (ready) { + files_->exit_requested = true; + files_->accepting = false; + } + } + if (!ready) { + return false; + } + files_->work_cv.notify_all(); + // (3) final drain of cancels, controls, file completions, close waiters. + (void)drain_for_shutdown(tickets); + // (4) join workers. + workers_.join_for_shutdown(); + // (5) remaining file fds, then op/descriptor fds. + (void)drain_file_completions(tickets); + close_remaining_files(); + complete_all_close_waiters(tickets); + (void)abort_pending_socket_ops(tickets); + close_socket_slots(tickets); + std::vector> stale_cancels; + { + std::lock_guard lk{mu_}; + control_queue_.clear(); + stale_cancels.swap(cancel_queue_); + } + stale_cancels.clear(); + // (6) publish completion. + shut_down_.store(true, std::memory_order_release); + on_shutdown_complete(); + return true; + } + + void wait_shutdown_slice(bool owned) + { + if (!owned) { + // Another poller is finishing its turn; it was woken above. + std::this_thread::sleep_for(std::chrono::microseconds{100}); + return; + } + std::unique_lock lk{files_->mu}; + (void)files_->idle_cv.wait_for(lk, std::chrono::milliseconds{1}, [this] { + return files_->active.empty(); + }); + } + + [[nodiscard]] DriverShutdownReport make_report(bool complete) const noexcept + { + DriverShutdownReport r; + r.complete = complete; + r.pending_operations = active_operations_.load(std::memory_order_acquire); + r.active_file_requests = files_->active_count.load(std::memory_order_acquire); + r.open_descriptors = active_descriptors_.load(std::memory_order_acquire); + r.retained_buffer_bytes = borrowed_buffer_bytes_.load(std::memory_order_acquire); + return r; + } + + void close_remaining_files() + { + std::vector> drops; + { + std::lock_guard lk{mu_}; + std::lock_guard flk{files_->mu}; + for (std::uint32_t idx = 0; idx < slots_.size(); ++idx) { + auto& s = slots_[idx]; + if (!s.in_use || !s.is_file) { + continue; + } + std::shared_ptr f = std::move(s.file); + if (f && f->status != FileState::Status::closed) { + if (f->fd >= 0) { + (void)f->syscalls->close(f->fd); + } + f->fd = -1; + f->status = FileState::Status::closed; + f->close_error = 0; + } + release_slot_locked(idx, false); + if (f) { + drops.push_back(std::move(f)); + } + } + // Close requests that never ran go back to their FileState (whose + // fd was closed above), breaking the pool -> request -> file cycle. + FileRequestList unrun; + unrun.splice(unrun.end(), files_->close_queued); + while (!unrun.empty()) { + auto it = unrun.begin(); + std::shared_ptr f = std::move((*it)->file); + (*it)->phase = FileRequestPhase::queued; + if (f) { + f->close_node.splice(f->close_node.end(), unrun, it); + drops.push_back(std::move(f)); + } else { + files_->completions.splice(files_->completions.end(), unrun, it); + } + } + files_->publish_counts_locked(); + } + drops.clear(); + } + + void complete_all_close_waiters(std::vector& tickets) + { + std::vector> ready; + { + std::lock_guard lk{files_->mu}; + ready.swap(files_->close_waiters); + } + for (auto& w : ready) { + if (auto t = w->op->try_commit_value(); t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto t = w->op->release_backend_ref(); t.has_value()) { + tickets.push_back(std::move(*t)); + } + } + } + + void close_socket_slots(std::vector& tickets) + { + std::vector close_waiters; + { + std::lock_guard lk{mu_}; + for (std::uint32_t idx = 0; idx < slots_.size(); ++idx) { + auto& s = slots_[idx]; + if (!s.in_use || s.is_file) { + continue; + } + on_slot_final_close_locked(s); + close_waiters.insert( + close_waiters.end(), + std::make_move_iterator(s.close_waiters.begin()), + std::make_move_iterator(s.close_waiters.end())); + s.close_waiters.clear(); + release_slot_locked(idx, closes_native_fds()); + } + } + commit_close_waiters(close_waiters, tickets); + } + + // ── File completion lane (poll owner) ──────────────────────────────────── + + std::size_t drain_file_completions(std::vector& tickets) + { + FileRequestList local; + { + std::lock_guard lk{files_->mu}; + local.splice(local.end(), files_->completions); + } + std::size_t n = 0; + for (auto& req : local) { + if (retire_file_request(*req, tickets)) { + ++n; + } + } + // Requests (and their stop callbacks) are destroyed here, outside locks. + return n; + } + + bool retire_file_request(FileRequest& req, std::vector& tickets) + { + bool enqueued_close = false; + FileSettle settle = FileSettle::syscall; + FileSyscallResult result{}; + { + std::lock_guard lk{files_->mu}; + if (req.phase == FileRequestPhase::retired) { + duplicate_completions_ignored_.fetch_add(1, std::memory_order_acq_rel); + return false; + } + req.phase = FileRequestPhase::retired; + settle = req.settle; + result = req.result; + if (req.kind != FileRequestKind::close && req.file) { + FileState& f = *req.file; + if (f.in_flight > 0) { + --f.in_flight; + } + if (f.in_flight == 0 && f.close_pending && !f.close_enqueued) { + files_->enqueue_close_locked(f); + enqueued_close = true; + } + } + } + if (enqueued_close) { + files_->work_cv.notify_one(); + } + if (req.kind == FileRequestKind::close) { + on_file_close_retired(req.file, tickets); + return true; + } + + active_operations_.fetch_sub(1, std::memory_order_acq_rel); + if (req.len > 0) { + borrowed_buffer_bytes_.fetch_sub(req.len, std::memory_order_acq_rel); + } + + const bool committing = (req.kind != FileRequestKind::read); + std::optional t; + if (req.kind == FileRequestKind::sync) { + auto& op = req.void_op; + if (settle == FileSettle::cancelled) { + t = op->try_commit_error( + make_io_error(IoErrorCode::cancelled, "File sync cancelled before execution"), + Async::DomainOutcomeKind::not_committed); + } else if (settle == FileSettle::timeout) { + t = op->try_commit_error( + make_io_error(IoErrorCode::timeout, "File sync deadline expired before execution"), + Async::DomainOutcomeKind::not_committed); + } else if (result.error != 0) { + t = op->try_commit_error( + make_io_error(IoErrorCode::sync_failed, "File sync failed", errno_code(result.error)), + Async::DomainOutcomeKind::unknown); + } else { + t = op->try_commit_value(); + } + if (t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + return true; + } + + auto& op = req.transfer_op; + if (settle == FileSettle::cancelled) { + t = op->try_commit_error( + make_io_error(IoErrorCode::cancelled, "File request cancelled before execution"), + committing ? Async::DomainOutcomeKind::not_committed + : Async::DomainOutcomeKind::cancelled); + } else if (settle == FileSettle::timeout) { + t = op->try_commit_error( + make_io_error(IoErrorCode::timeout, "File request deadline expired before execution"), + committing ? Async::DomainOutcomeKind::not_committed + : Async::DomainOutcomeKind::failed); + } else if (result.error != 0) { + t = op->try_commit_error( + make_io_error(IoErrorCode::os_error, + committing ? "pwrite failed" : "pread failed", + errno_code(result.error)), + committing ? Async::DomainOutcomeKind::unknown : Async::DomainOutcomeKind::failed); + } else { + const std::uint64_t raw = result.value < 0 ? 0u : static_cast(result.value); + const std::size_t bytes = static_cast(std::min(raw, to_u64(req.len))); + const bool eof = (req.kind == FileRequestKind::read) && bytes == 0 && req.len > 0; + t = op->try_commit_value(Transfer{bytes, eof}); + } + if (t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + return true; + } + + void on_file_close_retired(const std::shared_ptr& file, + std::vector& tickets) + { + if (!file) { + return; + } + std::shared_ptr drop; + { + std::lock_guard lk{mu_}; + const DescriptorId id = file->id; + if (id.valid() && id.slot < slots_.size()) { + auto& s = slots_[id.slot]; + if (s.in_use && s.is_file && s.id.generation == id.generation && + s.file == file) { + drop = std::move(s.file); + release_slot_locked(id.slot, false); + } + } + } + std::vector> ready; + int err = 0; + { + std::lock_guard lk{files_->mu}; + err = file->close_error; + auto& ws = files_->close_waiters; + for (auto it = ws.begin(); it != ws.end();) { + if ((*it)->file == file) { + ready.push_back(std::move(*it)); + it = ws.erase(it); + } else { + ++it; + } + } + } + for (auto& w : ready) { + std::optional t; + if (err == 0) { + t = w->op->try_commit_value(); + } else { + t = w->op->try_commit_error( + make_io_error(IoErrorCode::os_error, "File close failed", errno_code(err))); + } + if (t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = w->op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + } + + // close_and_join waiters whose stop fired or (with `now`) whose deadline + // passed complete with incomplete_shutdown; the File keeps its fd. + std::size_t scan_close_waiters(std::optional now, + std::vector& tickets) + { + std::vector> ready; + { + std::lock_guard lk{files_->mu}; + auto& ws = files_->close_waiters; + for (auto it = ws.begin(); it != ws.end();) { + const auto& w = *it; + const bool expired = now.has_value() && w->deadline.has_value() && + *now >= *w->deadline; + if (w->op->stop_requested() || expired) { + ready.push_back(std::move(*it)); + it = ws.erase(it); + } else { + ++it; + } + } + } + for (auto& w : ready) { + if (auto t = w->op->try_commit_error(make_io_error( + IoErrorCode::incomplete_shutdown, + "File close_and_join expired before the close completed")); + t.has_value()) { + tickets.push_back(std::move(*t)); + } + if (auto r = w->op->release_backend_ref(); r.has_value()) { + tickets.push_back(std::move(*r)); + } + } + return ready.size(); + } + + [[nodiscard]] bool file_deadlines_pending() const + { + std::lock_guard lk{files_->mu}; + for (const auto& r : files_->queued) { + if (r->deadline.has_value()) { + return true; + } + } + for (const auto& w : files_->close_waiters) { + if (w->deadline.has_value()) { + return true; + } + } + return false; + } + + [[nodiscard]] std::optional + earliest_file_deadline() const + { + std::optional earliest; + std::lock_guard lk{files_->mu}; + for (const auto& r : files_->queued) { + if (r->deadline.has_value() && (!earliest.has_value() || *r->deadline < *earliest)) { + earliest = r->deadline; + } + } + for (const auto& w : files_->close_waiters) { + if (w->deadline.has_value() && (!earliest.has_value() || *w->deadline < *earliest)) { + earliest = w->deadline; + } + } + return earliest; + } + + // Queued file requests past their deadline move to the completion queue as + // timeout (marked expired for workers); expired close waiters complete. + std::size_t expire_file_work_at(Void::Time::MonotonicClock::time_point now, + std::vector& tickets) + { + { + std::lock_guard lk{files_->mu}; + for (auto it = files_->queued.begin(); it != files_->queued.end();) { + auto next = std::next(it); + FileRequest& r = **it; + if (r.deadline.has_value() && now >= *r.deadline) { + files_->settle_queued_locked(r, FileSettle::timeout); + } + it = next; + } + } + return scan_close_waiters(now, tickets); + } + Async::Executor& executor_; IoLimits limits_{}; const Void::Time::MonotonicClock& clock_; std::shared_ptr buffer_tracker_{}; + FileSyscalls* file_syscalls_{nullptr}; + std::function(std::size_t)> worker_hook_{}; + std::shared_ptr files_{}; + FileWorkers workers_; mutable std::mutex mu_{}; + std::mutex poll_mu_{}; std::atomic stopping_{false}; + std::atomic shutdown_begun_{false}; + std::atomic shut_down_{false}; + std::atomic shutdown_waiting_{0}; std::atomic active_descriptors_{0}; std::atomic active_operations_{0}; std::atomic borrowed_buffer_bytes_{0}; std::atomic turns_{0}; std::atomic wakeups_{0}; std::atomic stale_events_ignored_{0}; + std::atomic duplicate_completions_ignored_{0}; std::vector slots_{}; std::vector free_slots_{}; @@ -484,6 +1442,180 @@ protected: std::vector> cancel_queue_{}; private: + [[nodiscard]] Void::Result::Result reserve_file_slot() + { + std::lock_guard lk{mu_}; + auto res = allocate_slot_locked(-1); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + slots_[res->slot].is_file = true; + return *res; + } + + void release_reserved_file_slot(DescriptorId id) noexcept + { + std::shared_ptr drop; + std::lock_guard lk{mu_}; + if (id.slot < slots_.size() && slots_[id.slot].in_use && slots_[id.slot].is_file && + slots_[id.slot].id.generation == id.generation) { + drop = std::move(slots_[id.slot].file); + release_slot_locked(id.slot, false); + } + } + + [[nodiscard]] Void::Result::Result> + install_file(DescriptorId id, int fd, bool close_fd_on_failure) + { + std::shared_ptr fs; + try { + fs = std::make_shared(files_, weak_from_this(), file_syscalls_, fd, id); + } catch (...) { + release_reserved_file_slot(id); +#if defined(__unix__) || defined(__APPLE__) + if (close_fd_on_failure) { + ::close(fd); + } +#endif + throw; + } + bool installed = false; + { + std::lock_guard lk{mu_}; + if (id.slot < slots_.size()) { + auto& s = slots_[id.slot]; + if (s.in_use && s.is_file && s.id.generation == id.generation && + !s.file && !shut_down_.load(std::memory_order_acquire)) { + s.file = fs; + installed = true; + } + } + } + if (!installed) { + // Shutdown released the reserved slot while the fd was opened. +#if defined(__unix__) || defined(__APPLE__) + if (close_fd_on_failure) { + ::close(fd); + } +#endif + return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver shut down while the file was opened")}; + } + return fs; + } + + [[nodiscard]] Void::Result::Result precheck_file_admission( + const std::shared_ptr& file, + const Async::OperationOptions& options) + { + if (!file) { + return std::unexpected{make_io_error(IoErrorCode::closed, "File is closed")}; + } + if (stopping_.load(std::memory_order_acquire)) { + return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver is shutting down")}; + } + if (options.stop.stop_requested()) { + return std::unexpected{make_io_error( + IoErrorCode::cancelled, "File request cancelled before submission")}; + } + if (Async::is_deadline_expired(options, clock_)) { + return std::unexpected{make_io_error( + IoErrorCode::timeout, "File request deadline expired before submission")}; + } + return {}; + } + + // Queues `req` (node allocated before locking). On success the request + // counts in active_operations_ and borrowed bytes until poll-turn retirement. + [[nodiscard]] Void::Result::Result admit_file_request( + const std::shared_ptr& req, std::size_t len) + { + FileRequestList node; + node.push_back(req); + std::lock_guard lk{files_->mu}; + if (!files_->accepting) { + return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver is shutting down")}; + } + if (req->file->status != FileState::Status::open) { + return std::unexpected{make_io_error(IoErrorCode::closed, "File is closed")}; + } + if (files_->queued.size() >= files_->max_queue) { + return std::unexpected{make_io_error( + IoErrorCode::overloaded, "IO Driver max_file_queue quota exceeded")}; + } + if (!try_reserve_operation()) { + return std::unexpected{make_io_error( + IoErrorCode::overloaded, "IO Driver max_operations quota exceeded")}; + } + ++req->file->in_flight; + if (len > 0) { + borrowed_buffer_bytes_.fetch_add(len, std::memory_order_acq_rel); + } + auto it = node.begin(); + files_->queued.splice(files_->queued.end(), node, it); + req->pos = it; + req->phase = FileRequestPhase::queued; + files_->publish_counts_locked(); + return {}; + } + + void finish_file_admission(const std::shared_ptr& req, std::stop_token op_stop) + { + files_->work_cv.notify_one(); + // Registered after unlocking; a stop already requested runs the + // forwarder synchronously here. + req->cancel_cb.emplace(std::move(op_stop), FileCancelForwarder{req}); + wake(); + } + + [[nodiscard]] Void::Result::Result>> + submit_file_transfer(const std::shared_ptr& file, + FileRequestKind kind, + std::byte* read_ptr, + const std::byte* write_ptr, + std::size_t len, + std::uint64_t offset, + Async::OperationOptions options) + { + if (!file) { + return std::unexpected{make_io_error(IoErrorCode::closed, "File is closed")}; + } + if (offset > kFileOffsetMax || to_u64(len) > kFileOffsetMax - offset) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "File offset plus length exceeds the maximum file offset")}; + } + if (len == 0) { + auto op = Async::OperationState::create( + {}, &executor_, Async::StopBehavior::notify_only); + (void)op->try_commit_value(Transfer{0, false}); + return op; + } + if (auto pre = precheck_file_admission(file, options); !pre.has_value()) { + return std::unexpected{std::move(pre.error())}; + } + auto op = Async::OperationState::create( + options, &executor_, Async::StopBehavior::notify_only); + auto req = std::make_shared(); + req->kind = kind; + req->file = file; + req->read_ptr = read_ptr; + req->write_ptr = write_ptr; + req->len = len; + req->offset = offset; + req->deadline = options.deadline; + req->transfer_op = op; + // The backend ref is taken before the request becomes visible to workers. + op->acquire_backend_ref(); + if (auto adm = admit_file_request(req, len); !adm.has_value()) { + (void)op->release_backend_ref(); + return std::unexpected{std::move(adm.error())}; + } + finish_file_admission(req, op->stop_token()); + return op; + } + [[nodiscard]] Void::Result::Result>> submit_io(const std::shared_ptr& stream, Direction dir, @@ -524,6 +1656,7 @@ private: } if (!did.valid() || did.slot >= slots_.size() || !slots_[did.slot].in_use || + slots_[did.slot].is_file || slots_[did.slot].id.generation != did.generation || slots_[did.slot].closing) { return std::unexpected{make_io_error( @@ -538,18 +1671,17 @@ private: ? "Another read_some operation is already active on this stream" : "Another write_some operation is already active on this stream")}; } - if (active_operations_.load(std::memory_order_acquire) >= limits_.max_operations) { - return std::unexpected{make_io_error( - IoErrorCode::overloaded, "IO Driver max_operations quota exceeded")}; - } if (kind() == BackendPreference::epoll && control_queue_.size() >= limits_.max_control_submissions) { return std::unexpected{make_io_error( IoErrorCode::overloaded, "IO Driver control queue full")}; } + if (!try_reserve_operation()) { + return std::unexpected{make_io_error( + IoErrorCode::overloaded, "IO Driver max_operations quota exceeded")}; + } op->op_state->acquire_backend_ref(); - active_operations_.fetch_add(1, std::memory_order_acq_rel); borrowed_buffer_bytes_.fetch_add(len, std::memory_order_acq_rel); if (dir == Direction::read) { slot.active_read = op; @@ -646,7 +1778,7 @@ public: return 0; } const auto& s = slots_[id.slot]; - if (!s.in_use || s.id.generation != id.generation) { + if (!s.in_use || s.is_file || s.id.generation != id.generation) { return 0; } const auto& op = (dir == Direction::read) ? s.active_read : s.active_write; @@ -661,7 +1793,7 @@ public: return std::nullopt; } auto& s = slots_[id.slot]; - if (!s.in_use || s.id.generation != id.generation) { + if (!s.in_use || s.is_file || s.id.generation != id.generation) { return std::nullopt; } auto& op = (dir == Direction::read) ? s.active_read : s.active_write; @@ -701,7 +1833,7 @@ public: } std::vector tickets; std::vector close_waiters; - complete_op_and_collect_tickets( + (void)complete_op_and_collect_tickets( op, Transfer{copy_n, eof}, tickets, close_waiters); dispatch_tickets(tickets); return true; @@ -716,7 +1848,7 @@ public: const std::size_t wrote = std::min(op->len, bytes); std::vector tickets; std::vector close_waiters; - complete_op_and_collect_tickets( + (void)complete_op_and_collect_tickets( op, Transfer{wrote, false}, tickets, close_waiters); dispatch_tickets(tickets); return true; @@ -730,75 +1862,68 @@ public: } std::vector tickets; std::vector close_waiters; - complete_op_and_collect_tickets( + (void)complete_op_and_collect_tickets( op, std::unexpected{std::move(err)}, tickets, close_waiters); dispatch_tickets(tickets); return true; } +protected: + // Mock poll_once ignores max_wait (REV1 P3). [[nodiscard]] Void::Result::Result - poll_once(std::optional) override + run_turn(std::optional) override { - turns_.fetch_add(1, std::memory_order_acq_rel); + std::vector tickets; + std::size_t processed = drain_socket_queues(tickets); + processed += drain_file_completions(tickets); + processed += scan_close_waiters(std::nullopt, tickets); + if (shutdown_begun_.load(std::memory_order_acquire)) { + processed += abort_pending_socket_ops(tickets); + } + const bool socket_deadlines = socket_deadlines_pending(); + const bool file_deadlines = file_deadlines_pending(); + if (socket_deadlines || file_deadlines) { + const auto now = clock_.now(); + if (socket_deadlines) { + processed += expire_socket_ops_at(now, tickets); + } + if (file_deadlines) { + processed += expire_file_work_at(now, tickets); + processed += drain_file_completions(tickets); + } + } + dispatch_tickets(tickets); + return processed; + } + std::size_t drain_socket_queues(std::vector& tickets) override + { std::vector> cancels; - std::vector> expired; std::vector controls; - const auto now = clock_.now(); - { std::lock_guard lk{mu_}; cancels.swap(cancel_queue_); controls.swap(control_queue_); - for (auto& slot : slots_) { - if (!slot.in_use) { - continue; - } - for (auto* op_ptr : {&slot.active_read, &slot.active_write}) { - if (*op_ptr && !(*op_ptr)->in_execution && !(*op_ptr)->retired && - (*op_ptr)->deadline.has_value() && now >= *(*op_ptr)->deadline) { - expired.push_back(*op_ptr); - } - } - } } std::size_t processed = 0; - std::vector tickets; std::vector close_waiters; - for (const auto& op : cancels) { - bool skip = false; + bool executing = false; { std::lock_guard lk{mu_}; - skip = op->in_execution || op->retired; + executing = op->in_execution && !op->retired; } - if (skip) { - continue; + if (executing) { + continue; // Held by a MockController token: stop intent only. } - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error(IoErrorCode::cancelled, "IO operation cancelled")}, - tickets, - close_waiters); - ++processed; - } - - for (const auto& op : expired) { - bool skip = false; - { - std::lock_guard lk{mu_}; - skip = op->in_execution || op->retired; + if (complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error(IoErrorCode::cancelled, "IO operation cancelled")}, + tickets, + close_waiters)) { + ++processed; } - if (skip) { - continue; - } - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error(IoErrorCode::timeout, "IO operation timed out")}, - tickets, - close_waiters); - ++processed; } for (const auto& ctrl : controls) { @@ -806,6 +1931,7 @@ public: std::lock_guard lk{mu_}; if (ctrl.id.valid() && ctrl.id.slot < slots_.size() && slots_[ctrl.id.slot].in_use && + !slots_[ctrl.id.slot].is_file && slots_[ctrl.id.slot].id.generation == ctrl.id.generation) { auto& s = slots_[ctrl.id.slot]; if (!s.active_read && !s.active_write) { @@ -820,73 +1946,34 @@ public: } } } - - for (auto& cw : close_waiters) { - if (auto t = cw.op_state->try_commit_value(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - if (auto t = cw.op_state->release_backend_ref(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - } - dispatch_tickets(tickets); + commit_close_waiters(close_waiters, tickets); return processed; } - [[nodiscard]] Void::Result::Result shutdown_and_join() override + void after_teardown() noexcept override { - stopping_.store(true, std::memory_order_release); - std::vector> to_abort; - std::vector close_waiters; + // S7: requests still held by MockController tokens complete with closed. + std::vector> held; { std::lock_guard lk{mu_}; - for (auto& slot : slots_) { - if (!slot.in_use) { - continue; - } - if (slot.active_read && !slot.active_read->in_execution && !slot.active_read->retired) { - to_abort.push_back(slot.active_read); - } - if (slot.active_write && !slot.active_write->in_execution && !slot.active_write->retired) { - to_abort.push_back(slot.active_write); - } - slot.closing = true; + for (auto& [tok, op] : held_requests_) { + (void)tok; + held.push_back(std::move(op)); } + held_requests_.clear(); } std::vector tickets; - for (const auto& op : to_abort) { - complete_op_and_collect_tickets( + std::vector close_waiters; + for (const auto& op : held) { + (void)complete_op_and_collect_tickets( op, std::unexpected{make_io_error(IoErrorCode::closed, "IO Driver shut down")}, tickets, close_waiters); } - { - std::lock_guard lk{mu_}; - for (std::uint32_t i = 0; i < slots_.size(); ++i) { - if (slots_[i].in_use) { - close_waiters.insert( - close_waiters.end(), - std::make_move_iterator(slots_[i].close_waiters.begin()), - std::make_move_iterator(slots_[i].close_waiters.end())); - slots_[i].close_waiters.clear(); - release_slot_locked(i, false); - } - } - } - for (auto& cw : close_waiters) { - if (auto t = cw.op_state->try_commit_value(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - if (auto t = cw.op_state->release_backend_ref(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - } dispatch_tickets(tickets); - return {}; } -protected: [[nodiscard]] Void::Result::Result on_op_submitted_locked(DescriptorSlot&, Direction, @@ -896,6 +1983,62 @@ protected: } private: + [[nodiscard]] bool socket_deadlines_pending() const + { + std::lock_guard lk{mu_}; + for (const auto& slot : slots_) { + if (!slot.in_use) { + continue; + } + for (const auto* op : {&slot.active_read, &slot.active_write}) { + if (*op && !(*op)->in_execution && !(*op)->retired && (*op)->deadline.has_value()) { + return true; + } + } + } + return false; + } + + std::size_t expire_socket_ops_at(Void::Time::MonotonicClock::time_point now, + std::vector& tickets) + { + std::vector> expired; + { + std::lock_guard lk{mu_}; + for (auto& slot : slots_) { + if (!slot.in_use) { + continue; + } + for (auto* op_ptr : {&slot.active_read, &slot.active_write}) { + if (*op_ptr && !(*op_ptr)->in_execution && !(*op_ptr)->retired && + (*op_ptr)->deadline.has_value() && now >= *(*op_ptr)->deadline) { + expired.push_back(*op_ptr); + } + } + } + } + std::size_t processed = 0; + std::vector close_waiters; + for (const auto& op : expired) { + bool executing = false; + { + std::lock_guard lk{mu_}; + executing = op->in_execution && !op->retired; + } + if (executing) { + continue; + } + if (complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error(IoErrorCode::timeout, "IO operation timed out")}, + tickets, + close_waiters)) { + ++processed; + } + } + return processed; + } + std::shared_ptr take_held(std::uint64_t tok) { std::lock_guard lk{mu_}; @@ -922,7 +2065,9 @@ public: Async::Executor& executor, IoLimits limits, const Void::Time::MonotonicClock& clock, - std::shared_ptr buffer_tracker) + std::shared_ptr buffer_tracker, + FileSyscalls* file_syscalls, + std::function(std::size_t)> worker_hook) { const int epfd = ::epoll_create1(EPOLL_CLOEXEC); if (epfd < 0) { @@ -946,13 +2091,28 @@ public: return std::unexpected{make_io_error( IoErrorCode::os_error, "epoll_ctl add wake_fd failed", errno_code(err))}; } - return std::shared_ptr(new EpollBackend( - executor, limits, clock, std::move(buffer_tracker), epfd, wfd)); + try { + return std::shared_ptr(new EpollBackend( + executor, limits, clock, std::move(buffer_tracker), file_syscalls, + std::move(worker_hook), epfd, wfd)); + } catch (...) { + ::close(wfd); + ::close(epfd); + throw; + } } + // F1/F2: never blocks. Driver teardown already completed shutdown, so only + // the epoll and wake descriptors remain (socket fds are closed here only if + // the backend was never torn down). ~EpollBackend() override { - (void)shutdown_and_join(); + for (auto& s : slots_) { + if (s.in_use && !s.is_file && s.fd >= 0) { + ::close(s.fd); + s.fd = -1; + } + } if (wake_fd_ >= 0) { ::close(wake_fd_); wake_fd_ = -1; @@ -1032,8 +2192,13 @@ public: return std::make_pair(std::move(*s0), std::move(*s1)); } + // F2: a no-op once shutdown completed; the eventfd itself closes only in + // ~EpollBackend, after every holder of a shared owner is gone. void wake() noexcept override { + if (wake_closed_.load(std::memory_order_acquire)) { + return; + } wakeups_.fetch_add(1, std::memory_order_acq_rel); const int wfd = wake_fd_; if (wfd >= 0) { @@ -1043,22 +2208,31 @@ public: } } +protected: [[nodiscard]] Void::Result::Result - poll_once(std::optional max_wait) override + run_turn(std::optional max_wait) override { - turns_.fetch_add(1, std::memory_order_acq_rel); std::size_t work_done = 0; std::vector tickets; - // 1. Drain coalesced cancel requests + bounded control updates first. + // 1. Drain cancels, controls and file completions before anything else + // (no clock read here; S8). While stopping, pending socket ops + // complete closed and their fds leave the interest set. work_done += process_cancels_and_controls(tickets); + work_done += drain_file_completions(tickets); + work_done += scan_close_waiters(std::nullopt, tickets); + if (shutdown_begun_.load(std::memory_order_acquire)) { + work_done += abort_pending_socket_ops(tickets); + } + if (file_deadlines_pending()) { + const auto now = clock_.now(); + work_done += expire_file_work_at(now, tickets); + work_done += drain_file_completions(tickets); + } dispatch_tickets(tickets); - if (stopping_.load(std::memory_order_acquire)) { - return work_done; - } - - // 2. Compute non-negative wait bounded by earliest armed op deadline in clock domain. + // 2. Compute non-negative wait bounded by the earliest armed op or + // queued-file deadline in the clock domain. int timeout_ms = 0; { std::optional earliest; @@ -1077,6 +2251,11 @@ public: } } } + if (const auto fdl = earliest_file_deadline(); fdl.has_value()) { + if (!earliest.has_value() || *fdl < *earliest) { + earliest = fdl; + } + } if (max_wait.has_value()) { auto wait_ns = *max_wait; if (earliest.has_value()) { @@ -1124,7 +2303,6 @@ public: IoErrorCode::os_error, "epoll_wait failed", errno_code(errno))}; } - // Re-check any newly posted control/cancel notifications woken during wait for (int i = 0; i < nready; ++i) { const std::uint64_t token = events[static_cast(i)].data.u64; const std::uint32_t ev_mask = events[static_cast(i)].events; @@ -1142,6 +2320,7 @@ public: std::lock_guard lk{mu_}; if (slot_idx >= slots_.size() || !slots_[slot_idx].in_use || + slots_[slot_idx].is_file || slots_[slot_idx].id.generation != gen || slots_[slot_idx].fd < 0 || slots_[slot_idx].closing) { @@ -1169,75 +2348,48 @@ public: } } - // Check deadlines and drain any cancels triggered before/during syscalls + // 3. Drain cancels triggered before/during syscalls, worker completions + // that woke this turn, then deadlines. work_done += process_cancels_and_controls(tickets); + work_done += drain_file_completions(tickets); + work_done += scan_close_waiters(std::nullopt, tickets); work_done += expire_deadlines(tickets); + if (file_deadlines_pending()) { + const auto now = clock_.now(); + work_done += expire_file_work_at(now, tickets); + work_done += drain_file_completions(tickets); + } dispatch_tickets(tickets); return work_done; } - [[nodiscard]] Void::Result::Result shutdown_and_join() override + std::size_t drain_socket_queues(std::vector& tickets) override { - stopping_.store(true, std::memory_order_release); - std::vector> to_abort; - std::vector close_waiters; - { - std::lock_guard lk{mu_}; - for (auto& s : slots_) { - if (!s.in_use) { - continue; - } - s.closing = true; - if (s.active_read && !s.active_read->retired) { - to_abort.push_back(s.active_read); - } - if (s.active_write && !s.active_write->retired) { - to_abort.push_back(s.active_write); - } - } + drain_wake_fd(); + return process_cancels_and_controls(tickets); + } + + void on_slot_abort_locked(DescriptorSlot& s) noexcept override + { + if (s.epoll_registered && epoll_fd_ >= 0 && s.fd >= 0) { + (void)::epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, s.fd, nullptr); } + s.epoll_registered = false; + s.epoll_out_armed = false; + } - std::vector tickets; - for (const auto& op : to_abort) { - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error(IoErrorCode::closed, "IO Driver shut down")}, - tickets, - close_waiters); - } + [[nodiscard]] bool closes_native_fds() const noexcept override { return true; } - { - std::lock_guard lk{mu_}; - for (std::uint32_t idx = 0; idx < slots_.size(); ++idx) { - if (slots_[idx].in_use) { - if (slots_[idx].epoll_registered && epoll_fd_ >= 0 && slots_[idx].fd >= 0) { - (void)::epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, slots_[idx].fd, nullptr); - } - close_waiters.insert( - close_waiters.end(), - std::make_move_iterator(slots_[idx].close_waiters.begin()), - std::make_move_iterator(slots_[idx].close_waiters.end())); - slots_[idx].close_waiters.clear(); - release_slot_locked(idx, true); - } - } - control_queue_.clear(); - cancel_queue_.clear(); - } + void on_slot_final_close_locked(DescriptorSlot& s) noexcept override + { + on_slot_abort_locked(s); + } - for (auto& cw : close_waiters) { - if (auto t = cw.op_state->try_commit_value(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - if (auto t = cw.op_state->release_backend_ref(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - } - dispatch_tickets(tickets); - return {}; + void on_shutdown_complete() noexcept override + { + wake_closed_.store(true, std::memory_order_release); } -protected: [[nodiscard]] Void::Result::Result on_op_submitted_locked(DescriptorSlot& slot, Direction dir, @@ -1256,9 +2408,12 @@ private: IoLimits limits, const Void::Time::MonotonicClock& clock, std::shared_ptr buffer_tracker, + FileSyscalls* file_syscalls, + std::function(std::size_t)> worker_hook, int epoll_fd, - int wake_fd) noexcept - : BaseBackend(executor, limits, clock, std::move(buffer_tracker)) + int wake_fd) + : BaseBackend(executor, limits, clock, std::move(buffer_tracker), file_syscalls, + std::move(worker_hook)) , epoll_fd_(epoll_fd) , wake_fd_(wake_fd) { @@ -1272,7 +2427,7 @@ private: void sync_epoll_interest_locked(DescriptorSlot& slot) noexcept { - if (!slot.in_use || slot.fd < 0 || slot.closing || epoll_fd_ < 0) { + if (!slot.in_use || slot.is_file || slot.fd < 0 || slot.closing || epoll_fd_ < 0) { return; } const bool want_out = (slot.active_write != nullptr && !slot.active_write->retired); @@ -1330,25 +2485,32 @@ private: } for (const auto& op : cancels) { + bool executing = false; { std::lock_guard lk{mu_}; - if (op->desc_id.slot < slots_.size() && + executing = op->in_execution && !op->retired; + if (!executing && !op->retired && + op->desc_id.slot < slots_.size() && slots_[op->desc_id.slot].in_use && slots_[op->desc_id.slot].id.generation == op->desc_id.generation) { auto& slot = slots_[op->desc_id.slot]; - if (op->dir == Direction::write && slot.epoll_out_armed && !op->retired) { + if (op->dir == Direction::write && slot.epoll_out_armed) { slot.active_write.reset(); sync_epoll_interest_locked(slot); slot.active_write = op; } } } - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error(IoErrorCode::cancelled, "IO operation cancelled")}, - tickets, - close_waiters); - ++done; + if (executing) { + continue; // The syscall's real result settles it (D1). + } + if (complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error(IoErrorCode::cancelled, "IO operation cancelled")}, + tickets, + close_waiters)) { + ++done; + } } { @@ -1358,7 +2520,7 @@ private: continue; } auto& s = slots_[act.id.slot]; - if (!s.in_use || s.id.generation != act.id.generation) { + if (!s.in_use || s.is_file || s.id.generation != act.id.generation) { continue; } if (act.type == ControlAction::Type::register_fd || @@ -1381,14 +2543,7 @@ private: } } - for (auto& cw : close_waiters) { - if (auto t = cw.op_state->try_commit_value(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - if (auto t = cw.op_state->release_backend_ref(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - } + commit_close_waiters(close_waiters, tickets); return done; } @@ -1399,24 +2554,26 @@ private: { std::lock_guard lk{mu_}; for (auto& s : slots_) { - if (!s.in_use) { + if (!s.in_use || s.is_file) { continue; } - if (s.active_read && !s.active_read->retired && + if (s.active_read && !s.active_read->retired && !s.active_read->in_execution && s.active_read->deadline.has_value() && now >= *s.active_read->deadline) { expired.push_back(s.active_read); } - if (s.active_write && !s.active_write->retired && + if (s.active_write && !s.active_write->retired && !s.active_write->in_execution && s.active_write->deadline.has_value() && now >= *s.active_write->deadline) { expired.push_back(s.active_write); } } } + std::size_t done = 0; std::vector close_waiters; for (const auto& op : expired) { { std::lock_guard lk{mu_}; - if (op->dir == Direction::write && op->desc_id.slot < slots_.size() && + if (!op->retired && op->dir == Direction::write && + op->desc_id.slot < slots_.size() && slots_[op->desc_id.slot].in_use && slots_[op->desc_id.slot].id.generation == op->desc_id.generation) { auto& s = slots_[op->desc_id.slot]; @@ -1425,21 +2582,33 @@ private: s.active_write = op; } } - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error(IoErrorCode::timeout, "IO operation timed out")}, - tickets, - close_waiters); - } - for (auto& cw : close_waiters) { - if (auto t = cw.op_state->try_commit_value(); t.has_value()) { - tickets.push_back(std::move(*t)); - } - if (auto t = cw.op_state->release_backend_ref(); t.has_value()) { - tickets.push_back(std::move(*t)); + if (complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error(IoErrorCode::timeout, "IO operation timed out")}, + tickets, + close_waiters)) { + ++done; } } - return expired.size(); + return done; + } + + // D1(c): the op is marked in_execution under mu_ before its syscall; the + // syscall's real result settles it. + [[nodiscard]] bool begin_execution(const std::shared_ptr& op) noexcept + { + std::lock_guard lk{mu_}; + if (op->retired) { + return false; + } + op->in_execution = true; + return true; + } + + void end_execution(const std::shared_ptr& op) noexcept + { + std::lock_guard lk{mu_}; + op->in_execution = false; } std::size_t drive_read(std::uint32_t slot_idx, @@ -1449,14 +2618,20 @@ private: const std::shared_ptr& op, std::vector& tickets) { + (void)slot_idx; + (void)gen; if (op->op_state->stop_requested()) { std::vector close_waiters; - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error(IoErrorCode::cancelled, "Read cancelled before syscall")}, - tickets, - close_waiters); - return 1; + return complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error(IoErrorCode::cancelled, "Read cancelled before syscall")}, + tickets, + close_waiters) + ? 1 + : 0; + } + if (!begin_execution(op)) { + return 0; } const std::size_t to_read = std::min(op->len, limits_.max_bytes_per_turn); @@ -1472,48 +2647,61 @@ private: } break; } + int so_err = 0; + if (n < 0 && (saved_errno == EAGAIN || saved_errno == EWOULDBLOCK) && + (ev_mask & EPOLLERR) != 0) { + socklen_t len = sizeof(so_err); + if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_err, &len) != 0) { + so_err = 0; + } + } + end_execution(op); + std::vector close_waiters; if (n > 0) { - std::vector close_waiters; - complete_op_and_collect_tickets( - op, Transfer{static_cast(n), false}, tickets, close_waiters); - return 1; + return complete_op_and_collect_tickets( + op, Transfer{static_cast(n), false}, tickets, close_waiters) + ? 1 + : 0; } if (n == 0) { - std::vector close_waiters; - complete_op_and_collect_tickets( - op, Transfer{0, true}, tickets, close_waiters); - return 1; + return complete_op_and_collect_tickets(op, Transfer{0, true}, tickets, close_waiters) + ? 1 + : 0; } if (saved_errno == EAGAIN || saved_errno == EWOULDBLOCK) { - if ((ev_mask & EPOLLERR) != 0) { - int so_err = 0; - socklen_t len = sizeof(so_err); - if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_err, &len) == 0 && so_err != 0) { - std::vector close_waiters; - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error( - IoErrorCode::os_error, "Socket error on read", errno_code(so_err))}, - tickets, - close_waiters); - return 1; - } + if (so_err != 0) { + return complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error( + IoErrorCode::os_error, "Socket error on read", errno_code(so_err))}, + tickets, + close_waiters) + ? 1 + : 0; } return 0; } - std::vector close_waiters; - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error( - IoErrorCode::os_error, - "read failed", - errno_code(saved_errno))}, - tickets, - close_waiters); - (void)slot_idx; - (void)gen; - return 1; + return complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error( + IoErrorCode::os_error, "read failed", errno_code(saved_errno))}, + tickets, + close_waiters) + ? 1 + : 0; + } + + void disarm_write_locked(std::uint32_t slot_idx, + std::uint32_t gen, + const std::shared_ptr& op) noexcept + { + if (slot_idx < slots_.size() && slots_[slot_idx].in_use && + slots_[slot_idx].id.generation == gen) { + slots_[slot_idx].active_write.reset(); + sync_epoll_interest_locked(slots_[slot_idx]); + slots_[slot_idx].active_write = op; + } } std::size_t drive_write(std::uint32_t slot_idx, @@ -1526,20 +2714,21 @@ private: if (op->op_state->stop_requested()) { { std::lock_guard lk{mu_}; - if (slot_idx < slots_.size() && slots_[slot_idx].in_use && - slots_[slot_idx].id.generation == gen) { - slots_[slot_idx].active_write.reset(); - sync_epoll_interest_locked(slots_[slot_idx]); - slots_[slot_idx].active_write = op; + if (!op->retired) { + disarm_write_locked(slot_idx, gen, op); } } std::vector close_waiters; - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error(IoErrorCode::cancelled, "Write cancelled before syscall")}, - tickets, - close_waiters); - return 1; + return complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error(IoErrorCode::cancelled, "Write cancelled before syscall")}, + tickets, + close_waiters) + ? 1 + : 0; + } + if (!begin_execution(op)) { + return 0; } const std::size_t to_write = std::min(op->len, limits_.max_bytes_per_turn); @@ -1553,87 +2742,74 @@ private: continue; } if (saved_errno == ENOTSOCK) { -#ifdef __linux__ - n = write_pipe_nosigpipe( - fd, op->write_ptr, to_write, saved_errno); -#else - n = ::write(fd, op->write_ptr, to_write); - if (n < 0) { - saved_errno = errno; - if (saved_errno == EINTR) { - continue; - } - } -#endif + n = write_pipe_nosigpipe(fd, op->write_ptr, to_write, saved_errno); } } break; } + int so_err = 0; + if (n < 0 && (saved_errno == EAGAIN || saved_errno == EWOULDBLOCK) && + (ev_mask & EPOLLERR) != 0) { + socklen_t len = sizeof(so_err); + if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_err, &len) != 0) { + so_err = 0; + } + } + end_execution(op); + std::vector close_waiters; if (n >= 0) { { std::lock_guard lk{mu_}; - if (slot_idx < slots_.size() && slots_[slot_idx].in_use && - slots_[slot_idx].id.generation == gen) { - slots_[slot_idx].active_write.reset(); - sync_epoll_interest_locked(slots_[slot_idx]); - slots_[slot_idx].active_write = op; + if (!op->retired) { + disarm_write_locked(slot_idx, gen, op); } } - std::vector close_waiters; - complete_op_and_collect_tickets( - op, Transfer{static_cast(n), false}, tickets, close_waiters); - return 1; + return complete_op_and_collect_tickets( + op, Transfer{static_cast(n), false}, tickets, close_waiters) + ? 1 + : 0; } if (saved_errno == EAGAIN || saved_errno == EWOULDBLOCK) { - if ((ev_mask & EPOLLERR) != 0) { - int so_err = 0; - socklen_t len = sizeof(so_err); - if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_err, &len) == 0 && so_err != 0) { - { - std::lock_guard lk{mu_}; - if (slot_idx < slots_.size() && slots_[slot_idx].in_use && - slots_[slot_idx].id.generation == gen) { - slots_[slot_idx].active_write.reset(); - sync_epoll_interest_locked(slots_[slot_idx]); - slots_[slot_idx].active_write = op; - } + if (so_err != 0) { + { + std::lock_guard lk{mu_}; + if (!op->retired) { + disarm_write_locked(slot_idx, gen, op); } - std::vector close_waiters; - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error( - IoErrorCode::os_error, "Socket error on write", errno_code(so_err))}, - tickets, - close_waiters); - return 1; } + return complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error( + IoErrorCode::os_error, "Socket error on write", errno_code(so_err))}, + tickets, + close_waiters) + ? 1 + : 0; } return 0; } { std::lock_guard lk{mu_}; - if (slot_idx < slots_.size() && slots_[slot_idx].in_use && - slots_[slot_idx].id.generation == gen) { - slots_[slot_idx].active_write.reset(); - sync_epoll_interest_locked(slots_[slot_idx]); - slots_[slot_idx].active_write = op; + if (!op->retired) { + disarm_write_locked(slot_idx, gen, op); } } - std::vector close_waiters; - complete_op_and_collect_tickets( - op, - std::unexpected{make_io_error( - IoErrorCode::os_error, "write failed", errno_code(saved_errno))}, - tickets, - close_waiters); - return 1; + return complete_op_and_collect_tickets( + op, + std::unexpected{make_io_error( + IoErrorCode::os_error, "write failed", errno_code(saved_errno))}, + tickets, + close_waiters) + ? 1 + : 0; } int epoll_fd_{-1}; int wake_fd_{-1}; + std::atomic wake_closed_{false}; }; #endif // __linux__ @@ -1734,10 +2910,12 @@ Driver::Driver(std::shared_ptr backend, } } +// F1: the only blocking teardown. teardown_blocking() terminates with a +// diagnostic on one of this Driver's file workers or inside its poll turn. Driver::~Driver() { if (backend_) { - (void)backend_->shutdown_and_join(); + backend_->teardown_blocking(); } } @@ -1757,11 +2935,13 @@ Void::Result::Result> Driver::create( std::shared_ptr backend; if (options.preference == BackendPreference::mock) { backend = std::make_shared( - executor, options.limits, clock, tracker); + executor, options.limits, clock, tracker, options.file_syscalls, + std::move(options.before_file_worker_start)); } else { #ifdef __linux__ auto ep = detail::EpollBackend::create_epoll( - executor, options.limits, clock, tracker); + executor, options.limits, clock, tracker, options.file_syscalls, + std::move(options.before_file_worker_start)); if (!ep.has_value()) { return std::unexpected{std::move(ep.error())}; } @@ -1861,4 +3041,33 @@ Void::Result::Result Driver::shutdown_and_join() return backend_->shutdown_and_join(); } -} // namespace Void::IO \ No newline at end of file +Void::Result::Result Driver::open_file(const std::filesystem::path& path, + FileOpenOptions options) +{ + auto st = backend_->open_file(path, options); + if (!st.has_value()) { + return std::unexpected{std::move(st.error())}; + } + return File{std::move(*st)}; +} + +Void::Result::Result Driver::adopt_file_fd(int fd) +{ + auto st = backend_->adopt_file_fd(fd); + if (!st.has_value()) { + return std::unexpected{std::move(st.error())}; + } + return File{std::move(*st)}; +} + +Void::Result::Result Driver::start_file_workers() +{ + return backend_->start_file_workers(); +} + +Void::Result::Result Driver::run_file_work(std::size_t max_requests) +{ + return backend_->run_file_work(max_requests); +} + +} // namespace Void::IO diff --git a/src/IO/FileWorkers.cpp b/src/IO/FileWorkers.cpp new file mode 100644 index 0000000..5a67738 --- /dev/null +++ b/src/IO/FileWorkers.cpp @@ -0,0 +1,743 @@ +#include "FileWorkers.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +#if defined(__unix__) || defined(__APPLE__) +#include +#include +#include +#define VOID_IO_POSIX_FILES 1 +#endif + +namespace Void::IO +{ + +namespace +{ +thread_local const detail::FileWorkerShared* tl_io_worker_owner = nullptr; +} // namespace + +bool is_io_worker_thread() noexcept +{ + return tl_io_worker_owner != nullptr; +} + +// ── FileSyscalls (native) ──────────────────────────────────────────────────── + +FileSyscallResult FileSyscalls::pread(int fd, std::span buf, std::uint64_t offset) noexcept +{ +#ifdef VOID_IO_POSIX_FILES + const ssize_t n = ::pread(fd, buf.data(), buf.size(), static_cast(offset)); + if (n < 0) { + return FileSyscallResult{-1, errno}; + } + return FileSyscallResult{static_cast(n), 0}; +#else + (void)fd; + (void)buf; + (void)offset; + return FileSyscallResult{-1, ENOSYS}; +#endif +} + +FileSyscallResult FileSyscalls::pwrite(int fd, + std::span buf, + std::uint64_t offset) noexcept +{ +#ifdef VOID_IO_POSIX_FILES + const ssize_t n = ::pwrite(fd, buf.data(), buf.size(), static_cast(offset)); + if (n < 0) { + return FileSyscallResult{-1, errno}; + } + return FileSyscallResult{static_cast(n), 0}; +#else + (void)fd; + (void)buf; + (void)offset; + return FileSyscallResult{-1, ENOSYS}; +#endif +} + +FileSyscallResult FileSyscalls::sync(int fd, SyncMode mode) noexcept +{ +#ifdef VOID_IO_POSIX_FILES + int rc = 0; +#if defined(__linux__) + rc = (mode == SyncMode::data) ? ::fdatasync(fd) : ::fsync(fd); +#else + (void)mode; + rc = ::fsync(fd); +#endif + if (rc != 0) { + return FileSyscallResult{-1, errno}; + } + return FileSyscallResult{0, 0}; +#else + (void)fd; + (void)mode; + return FileSyscallResult{-1, ENOSYS}; +#endif +} + +FileSyscallResult FileSyscalls::close(int fd) noexcept +{ +#ifdef VOID_IO_POSIX_FILES + if (::close(fd) != 0) { + return FileSyscallResult{-1, errno}; + } + return FileSyscallResult{0, 0}; +#else + (void)fd; + return FileSyscallResult{-1, ENOSYS}; +#endif +} + +FileSyscalls& FileSyscalls::native() noexcept +{ + static FileSyscalls instance; + return instance; +} + +} // namespace Void::IO + +namespace Void::IO::detail +{ + +namespace +{ +[[nodiscard]] std::error_code errno_code(int err) noexcept +{ + return std::error_code{err, std::generic_category()}; +} + +void worker_main(std::shared_ptr shared) noexcept +{ + tl_io_worker_owner = shared.get(); + FileWorkerShared& p = *shared; + std::unique_lock lk{p.mu}; + for (;;) { + p.work_cv.wait(lk, [&p] { + return p.exit_requested || p.rollback_requested || p.has_runnable_locked(); + }); + if (p.exit_requested || p.rollback_requested) { + break; + } + bool settled = false; + std::shared_ptr req = p.take_next_locked(settled); + if (!req) { + if (settled) { + lk.unlock(); + p.wake(); + lk.lock(); + } + continue; + } + lk.unlock(); + const FileSyscallResult result = execute_file_request(*req); + lk.lock(); + p.finish_locked(*req, result); + const bool idle = p.active.empty(); + // `completions` still owns the request, so this never destroys it. + req.reset(); + lk.unlock(); + p.work_cv.notify_all(); + if (idle) { + p.idle_cv.notify_all(); + } + p.wake(); + lk.lock(); + } + if (p.running_workers > 0) { + --p.running_workers; + } + p.publish_counts_locked(); + lk.unlock(); + p.idle_cv.notify_all(); + tl_io_worker_owner = nullptr; +} +} // namespace + +const FileWorkerShared* current_io_worker_owner() noexcept +{ + return tl_io_worker_owner; +} + +// ── FileState ──────────────────────────────────────────────────────────────── + +FileState::FileState(std::shared_ptr pool_in, + std::weak_ptr backend_in, + FileSyscalls* syscalls_in, + int fd_in, + DescriptorId id_in) + : pool(std::move(pool_in)) + , backend(std::move(backend_in)) + , syscalls(syscalls_in) + , id(id_in) + , fd(fd_in) +{ + auto close_req = std::make_shared(); + close_req->kind = FileRequestKind::close; + close_node.push_back(std::move(close_req)); +} + +// ── FileWorkerShared ───────────────────────────────────────────────────────── + +void FileWorkerShared::publish_counts_locked() noexcept +{ + queued_count.store(queued.size(), std::memory_order_release); + active_count.store(active.size(), std::memory_order_release); + running_count.store(running_workers, std::memory_order_release); +} + +bool FileWorkerShared::has_runnable_locked() const noexcept +{ + if (!close_queued.empty()) { + return true; + } + for (const auto& r : queued) { + if (r->stop_requested || r->expired) { + return true; + } + if (!r->serialized() || !r->file->serial_active) { + return true; + } + } + return false; +} + +std::shared_ptr FileWorkerShared::take_next_locked(bool& settled_without_syscall) noexcept +{ + settled_without_syscall = false; + if (exit_requested || rollback_requested) { + return nullptr; + } + if (!close_queued.empty()) { + auto it = close_queued.begin(); + std::shared_ptr req = *it; + active.splice(active.end(), close_queued, it); + req->phase = FileRequestPhase::active; + req->exec_fd = req->file ? req->file->fd : -1; + publish_counts_locked(); + return req; + } + for (auto it = queued.begin(); it != queued.end();) { + FileRequest& r = **it; + auto next = std::next(it); + if (r.stop_requested || r.expired) { + // S3: decided under the mutex from flags set by the stop callback or + // by the last poll turn; the clock is never read on a worker. + settle_queued_locked(r, r.expired ? FileSettle::timeout : FileSettle::cancelled); + settled_without_syscall = true; + it = next; + continue; + } + if (r.serialized() && r.file->serial_active) { + it = next; + continue; + } + if (r.serialized()) { + r.file->serial_active = true; + } + std::shared_ptr req = *it; + active.splice(active.end(), queued, it); + r.phase = FileRequestPhase::active; + r.exec_fd = r.file->fd; + publish_counts_locked(); + return req; + } + return nullptr; +} + +void FileWorkerShared::finish_locked(FileRequest& req, FileSyscallResult result) noexcept +{ + req.result = result; + req.settle = FileSettle::syscall; + req.phase = FileRequestPhase::done; + if (req.file) { + FileState& f = *req.file; + if (req.serialized()) { + f.serial_active = false; + } + if (req.kind == FileRequestKind::close) { + // Whoever closes the fd marks the file closed. Linux closes the fd + // even when close() reports EINTR, so that is not an error. + f.status = FileState::Status::closed; + f.fd = -1; + f.close_error = (result.error == EINTR) ? 0 : result.error; + } + } + completions.splice(completions.end(), active, req.pos); + publish_counts_locked(); +} + +void FileWorkerShared::settle_queued_locked(FileRequest& req, FileSettle settle) noexcept +{ + FileRequestList& from = (req.kind == FileRequestKind::close) ? close_queued : queued; + req.settle = settle; + req.phase = FileRequestPhase::done; + if (settle == FileSettle::timeout) { + req.expired = true; + } + completions.splice(completions.end(), from, req.pos); + publish_counts_locked(); +} + +void FileWorkerShared::enqueue_close_locked(FileState& file) noexcept +{ + if (file.close_enqueued || file.close_node.empty()) { + return; + } + std::shared_ptr self = file.weak_from_this().lock(); + if (!self) { + return; + } + file.close_enqueued = true; + file.close_pending = false; + auto it = file.close_node.begin(); + FileRequest& req = **it; + req.file = std::move(self); + req.phase = FileRequestPhase::queued; + close_queued.splice(close_queued.end(), file.close_node, it); + req.pos = it; + publish_counts_locked(); +} + +// ── Forwarders ─────────────────────────────────────────────────────────────── + +void FileCancelForwarder::operator()() const noexcept +{ + auto req = request.lock(); + if (!req || !req->file) { + return; + } + FileWorkerShared& pool = *req->file->pool; + bool removed = false; + { + std::lock_guard lk{pool.mu}; + req->stop_requested = true; + if (req->phase == FileRequestPhase::queued && req->kind != FileRequestKind::close) { + pool.settle_queued_locked(*req, FileSettle::cancelled); + removed = true; + } + } + if (removed) { + if (auto b = req->file->backend.lock()) { + b->wake(); + } + } +} + +void FileWakeForwarder::operator()() const noexcept +{ + if (auto b = backend.lock()) { + b->wake(); + } +} + +// ── Execution ──────────────────────────────────────────────────────────────── + +FileSyscallResult execute_file_request(const FileRequest& req) noexcept +{ + FileSyscalls& sys = (req.file && req.file->syscalls != nullptr) ? *req.file->syscalls + : FileSyscalls::native(); + const int fd = req.exec_fd; + for (;;) { + FileSyscallResult r{}; + switch (req.kind) { + case FileRequestKind::read: + r = sys.pread(fd, std::span{req.read_ptr, req.len}, req.offset); + break; + case FileRequestKind::write: + r = sys.pwrite(fd, std::span{req.write_ptr, req.len}, req.offset); + break; + case FileRequestKind::sync: + r = sys.sync(fd, req.mode); + break; + case FileRequestKind::close: + // Never retried: the descriptor is released even on EINTR. + return sys.close(fd); + } + if (r.error == EINTR) { + continue; + } + return r; + } +} + +std::optional run_file_requests_inline(FileWorkerShared& shared, + std::size_t max_requests) +{ + std::unique_lock lk{shared.mu}; + if (shared.running_workers > 0) { + return std::nullopt; + } + std::size_t done = 0; + while (done < max_requests) { + bool settled = false; + std::shared_ptr req = shared.take_next_locked(settled); + if (!req) { + break; + } + lk.unlock(); + const FileSyscallResult result = execute_file_request(*req); + lk.lock(); + shared.finish_locked(*req, result); + req.reset(); + ++done; + } + const bool idle = shared.active.empty(); + lk.unlock(); + if (idle) { + shared.idle_cv.notify_all(); + } + return done; +} + +void file_handle_dropped(FileState& file) noexcept +{ + FileWorkerShared& pool = *file.pool; + bool enqueued = false; + { + std::lock_guard lk{pool.mu}; + if (file.status == FileState::Status::closed) { + return; + } + if (file.status == FileState::Status::open) { + file.status = FileState::Status::closing; + } + if (!file.close_enqueued) { + if (file.in_flight == 0) { + pool.enqueue_close_locked(file); + enqueued = true; + } else { + file.close_pending = true; + } + } + } + if (enqueued) { + pool.work_cv.notify_one(); + if (auto b = file.backend.lock()) { + b->wake(); + } + } +} + +// ── Open helpers ───────────────────────────────────────────────────────────── + +Void::Result::Result validate_file_open_options(const FileOpenOptions& options) +{ + if (!options.read && !options.write) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "FileOpenOptions needs read or write access")}; + } + if (options.truncate && !options.write) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "FileOpenOptions::truncate requires write")}; + } + if (options.exclusive && !options.create) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "FileOpenOptions::exclusive requires create")}; + } + return {}; +} + +Void::Result::Result open_file_native(const std::filesystem::path& path, + const FileOpenOptions& options) +{ +#ifdef VOID_IO_POSIX_FILES + int flags = O_CLOEXEC; + if (options.read && options.write) { + flags |= O_RDWR; + } else if (options.write) { + flags |= O_WRONLY; + } else { + flags |= O_RDONLY; + } + if (options.create) { + flags |= O_CREAT; + } + if (options.truncate) { + flags |= O_TRUNC; + } + if (options.exclusive) { + flags |= O_EXCL; + } + int fd = -1; + for (;;) { + fd = ::open(path.c_str(), flags, static_cast(options.mode)); + if (fd < 0 && errno == EINTR) { + continue; + } + break; + } + if (fd < 0) { + return std::unexpected{make_io_error( + IoErrorCode::os_error, "open failed for " + path.string(), errno_code(errno))}; + } + return fd; +#else + (void)path; + (void)options; + return std::unexpected{make_io_error( + IoErrorCode::unsupported, "Positional files require a POSIX platform")}; +#endif +} + +// ── FileWorkers ────────────────────────────────────────────────────────────── + +FileWorkers::~FileWorkers() +{ + for (const auto& t : threads_) { + if (t.joinable()) { + std::fputs( + "Void::IO: file worker still running at backend destruction " + "(Driver teardown did not join it)\n", + stderr); + std::terminate(); + } + } +} + +Void::Result::Result FileWorkers::start( + std::size_t count, + const std::function(std::size_t)>& hook) +{ + std::lock_guard tl{threads_mu_}; + if (started_) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "start_file_workers was already called")}; + } + { + std::lock_guard lk{shared_->mu}; + if (!shared_->accepting || shared_->exit_requested) { + return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver is shutting down")}; + } + } + if (count == 0) { + started_ = true; + return {}; + } + try { + threads_.reserve(count); + } catch (...) { + return std::unexpected{make_io_error( + IoErrorCode::os_error, "Cannot allocate file worker table", + std::make_error_code(std::errc::not_enough_memory))}; + } + for (std::size_t i = 0; i < count; ++i) { + if (hook) { + Void::Result::Result hr{}; + try { + hr = hook(i); + } catch (const std::system_error& e) { + hr = std::unexpected{make_io_error(IoErrorCode::os_error, e.what(), e.code())}; + } catch (...) { + rollback_locked(); + throw; + } + if (!hr.has_value()) { + rollback_locked(); + return std::unexpected{make_io_error( + IoErrorCode::os_error, + "before_file_worker_start failed for worker " + std::to_string(i) + ": " + + std::string{hr.error().message()}, + hr.error().system_code())}; + } + } + { + std::lock_guard lk{shared_->mu}; + ++shared_->running_workers; + shared_->publish_counts_locked(); + } + try { + threads_.emplace_back(&worker_main, shared_); + } catch (const std::system_error& e) { + { + std::lock_guard lk{shared_->mu}; + --shared_->running_workers; + shared_->publish_counts_locked(); + } + rollback_locked(); + return std::unexpected{make_io_error( + IoErrorCode::os_error, "Cannot create file worker thread", e.code())}; + } + } + started_ = true; + return {}; +} + +void FileWorkers::rollback_locked() noexcept +{ + { + std::lock_guard lk{shared_->mu}; + shared_->rollback_requested = true; + } + shared_->work_cv.notify_all(); + for (auto& t : threads_) { + if (t.joinable()) { + t.join(); + } + } + threads_.clear(); + { + std::lock_guard lk{shared_->mu}; + shared_->rollback_requested = false; + } + // Requests queued meanwhile stay queued for a retried start or run_file_work. + shared_->work_cv.notify_all(); +} + +void FileWorkers::join_for_shutdown() noexcept +{ + std::lock_guard tl{threads_mu_}; + shared_->work_cv.notify_all(); + for (auto& t : threads_) { + if (t.joinable()) { + t.join(); + } + } + threads_.clear(); +} + +} // namespace Void::IO::detail + +// ── File ───────────────────────────────────────────────────────────────────── + +namespace Void::IO +{ + +File::File() noexcept = default; + +File::File(std::shared_ptr state) noexcept + : state_(std::move(state)) +{ +} + +File::File(File&& other) noexcept + : state_(std::move(other.state_)) +{ +} + +File& File::operator=(File&& other) noexcept +{ + if (this != &other) { + release_handle(); + state_ = std::move(other.state_); + } + return *this; +} + +File::~File() +{ + release_handle(); +} + +void File::release_handle() noexcept +{ + std::shared_ptr st = std::move(state_); + if (st) { + detail::file_handle_dropped(*st); + } +} + +DescriptorId File::id() const noexcept +{ + return state_ ? state_->id : DescriptorId{}; +} + +Coro::Task> File::read_at(std::uint64_t offset, + std::span buf, + Async::OperationOptions options) +{ + auto st = state_; + if (!st) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "File is closed or moved-from")}; + } + auto backend = st->backend.lock(); + if (!backend) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver no longer alive")}; + } + auto submitted = backend->submit_file_read(st, offset, buf, std::move(options)); + if (!submitted.has_value()) { + co_return std::unexpected{std::move(submitted.error())}; + } + auto op = std::move(*submitted); + co_return co_await op->awaitable(&backend->executor()); +} + +Coro::Task> File::write_at(std::uint64_t offset, + std::span buf, + Async::OperationOptions options) +{ + auto st = state_; + if (!st) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "File is closed or moved-from")}; + } + auto backend = st->backend.lock(); + if (!backend) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver no longer alive")}; + } + auto submitted = backend->submit_file_write(st, offset, buf, std::move(options)); + if (!submitted.has_value()) { + co_return std::unexpected{std::move(submitted.error())}; + } + auto op = std::move(*submitted); + co_return co_await op->awaitable(&backend->executor()); +} + +Coro::Task> File::sync(SyncMode mode, Async::OperationOptions options) +{ + auto st = state_; + if (!st) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "File is closed or moved-from")}; + } + auto backend = st->backend.lock(); + if (!backend) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver no longer alive")}; + } + auto submitted = backend->submit_file_sync(st, mode, std::move(options)); + if (!submitted.has_value()) { + co_return std::unexpected{std::move(submitted.error())}; + } + auto op = std::move(*submitted); + co_return co_await op->awaitable(&backend->executor()); +} + +Coro::Task> File::close_and_join(Async::OperationOptions options) +{ + auto st = state_; + if (!st) { + co_return Void::Result::Result{}; + } + Void::Result::Result res{}; + if (auto backend = st->backend.lock()) { + auto submitted = backend->submit_file_close(st, std::move(options)); + if (!submitted.has_value()) { + co_return std::unexpected{std::move(submitted.error())}; + } + auto op = std::move(*submitted); + res = co_await op->awaitable(&backend->executor()); + } + // Without a backend the Driver was torn down, which closed the fd. + if (res.has_value() && state_ == st) { + release_handle(); + } + co_return res; +} + +} // namespace Void::IO diff --git a/src/IO/FileWorkers.hpp b/src/IO/FileWorkers.hpp new file mode 100644 index 0000000..6857fae --- /dev/null +++ b/src/IO/FileWorkers.hpp @@ -0,0 +1,267 @@ +#pragma once + +// Private to the IO module: the bounded positional-file worker pool shared by +// every backend. Nothing here is installed. +// +// Ownership (S6/F1): +// - FileWorkerShared holds the queues, the mutex/condvars, the completion +// queue and a raw waker (function pointer + backend context). Workers hold +// only shared_ptr; the raw waker is called only by workers +// and run_file_work, which are finished or joined before the backend dies. +// - FileState holds shared_ptr and weak_ptr. +// - A FileRequest lives in exactly one FileWorkerShared list (queued, +// close_queued, active, completions) from admission until a poll turn +// retires it; nodes move between lists with splice, so workers never +// allocate. +// +// Lock order: backend poll_mu_ -> backend mu_ -> FileWorkerShared::mu, and +// poll_mu_ -> FileWorkers::threads_mu_ -> FileWorkerShared::mu. Workers take +// only FileWorkerShared::mu. No stop_callback is constructed or destroyed and +// no clock is read while FileWorkerShared::mu is held. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IO::detail +{ + +struct FileRequest; +struct FileWorkerShared; +using FileRequestList = std::list>; + +enum class FileRequestKind : std::uint8_t { + read, + write, + sync, + close +}; + +enum class FileRequestPhase : std::uint8_t { + queued, // in queued / close_queued + active, // in active, syscall running + done, // in completions, awaiting poll-turn retirement + retired // delivered by a poll turn +}; + +enum class FileSettle : std::uint8_t { + syscall, // result holds the syscall outcome + cancelled, // stopped while queued (no syscall) + timeout // expired while queued (no syscall) +}; + +struct FileCancelForwarder { + std::weak_ptr request; + + void operator()() const noexcept; +}; + +struct FileWakeForwarder { + std::weak_ptr backend; + + void operator()() const noexcept; +}; + +class FileState; + +struct FileRequest { + FileRequestKind kind{FileRequestKind::read}; + // Guarded by FileWorkerShared::mu. + FileRequestPhase phase{FileRequestPhase::queued}; + FileSettle settle{FileSettle::syscall}; + bool stop_requested{false}; + bool expired{false}; + int exec_fd{-1}; + FileSyscallResult result{}; + FileRequestList::iterator pos{}; + // Immutable after admission (a close request's `file` is set under mu + // when it is enqueued). + std::shared_ptr file{}; + std::byte* read_ptr{nullptr}; + const std::byte* write_ptr{nullptr}; + std::size_t len{0}; + std::uint64_t offset{0}; + SyncMode mode{SyncMode::full}; + std::optional deadline{}; + std::shared_ptr> transfer_op{}; + std::shared_ptr> void_op{}; + // MUST stay LAST: synchronized teardown with external stop callbacks. + std::optional> cancel_cb{}; + + [[nodiscard]] bool serialized() const noexcept + { + return kind == FileRequestKind::write || kind == FileRequestKind::sync; + } +}; + +class FileState : public std::enable_shared_from_this +{ +public: + enum class Status : std::uint8_t { + open, + closing, + closed + }; + + // Allocates the preallocated close request node (so ~File never allocates). + FileState(std::shared_ptr pool_in, + std::weak_ptr backend_in, + FileSyscalls* syscalls_in, + int fd_in, + DescriptorId id_in); + + FileState(const FileState&) = delete; + FileState& operator=(const FileState&) = delete; + + const std::shared_ptr pool; + const std::weak_ptr backend; + FileSyscalls* const syscalls; + const DescriptorId id; + + // Guarded by pool->mu. + int fd{-1}; + Status status{Status::open}; + bool close_pending{false}; + bool close_enqueued{false}; + bool serial_active{false}; + std::size_t in_flight{0}; + int close_error{0}; + FileRequestList close_node{}; +}; + +struct FileCloseWaiter { + std::shared_ptr file{}; + std::shared_ptr> op{}; + std::optional deadline{}; + // MUST stay LAST. + std::optional> stop_cb{}; +}; + +struct FileWorkerShared { + FileWorkerShared(std::size_t max_queue_in, FileSyscalls* syscalls_in) noexcept + : max_queue(max_queue_in) + , syscalls(syscalls_in) + { + } + + FileWorkerShared(const FileWorkerShared&) = delete; + FileWorkerShared& operator=(const FileWorkerShared&) = delete; + + std::mutex mu{}; + std::condition_variable work_cv{}; + std::condition_variable idle_cv{}; + + // Guarded by mu. + FileRequestList queued{}; // admitted read/write/sync, admission order + FileRequestList close_queued{}; // internal close requests (reserved capacity) + FileRequestList active{}; // syscall running + FileRequestList completions{}; // finished, awaiting poll-turn retirement + std::vector> close_waiters{}; + bool accepting{true}; + bool exit_requested{false}; + bool rollback_requested{false}; + std::size_t running_workers{0}; + + const std::size_t max_queue; + FileSyscalls* const syscalls; + void (*waker)(void*) noexcept {nullptr}; + void* waker_ctx{nullptr}; + + // Lock-free telemetry mirrors (written under mu). + std::atomic queued_count{0}; + std::atomic active_count{0}; + std::atomic running_count{0}; + + void wake() const noexcept + { + if (waker != nullptr) { + waker(waker_ctx); + } + } + + // All *_locked members require `mu`. + void publish_counts_locked() noexcept; + [[nodiscard]] bool has_runnable_locked() const noexcept; + // Moves the next eligible request to `active` (close requests first; a + // write/sync only when its file has no serialized request active). A + // queued request already stopped/expired is settled without a syscall and + // `settled_without_syscall` is set. + [[nodiscard]] std::shared_ptr take_next_locked( + bool& settled_without_syscall) noexcept; + void finish_locked(FileRequest& req, FileSyscallResult result) noexcept; + // queued -> completions with `settle` (cancelled/timeout). + void settle_queued_locked(FileRequest& req, FileSettle settle) noexcept; + void enqueue_close_locked(FileState& file) noexcept; +}; + +// Runs one request's syscall through the shim (EINTR retried except close). +[[nodiscard]] FileSyscallResult execute_file_request(const FileRequest& req) noexcept; + +// Executes up to `max_requests` requests on the calling thread. Returns +// nullopt (busy) while workers are running. +[[nodiscard]] std::optional run_file_requests_inline( + FileWorkerShared& shared, std::size_t max_requests); + +// Handle-drop transition for ~File and File move-assignment (noexcept, never +// allocates; wakes only through the worker condvar or a weak->strong lock). +void file_handle_dropped(FileState& file) noexcept; + +[[nodiscard]] const FileWorkerShared* current_io_worker_owner() noexcept; + +[[nodiscard]] Void::Result::Result validate_file_open_options( + const FileOpenOptions& options); +[[nodiscard]] Void::Result::Result open_file_native( + const std::filesystem::path& path, const FileOpenOptions& options); + +// Owns the worker threads. Never blocks in its destructor: a joinable thread +// left at destruction is a programmer error (diagnostic + std::terminate). +class FileWorkers +{ +public: + explicit FileWorkers(std::shared_ptr shared) noexcept + : shared_(std::move(shared)) + { + } + + ~FileWorkers(); + + FileWorkers(const FileWorkers&) = delete; + FileWorkers& operator=(const FileWorkers&) = delete; + + // invalid_argument when already started, closed once shutdown began, + // os_error (with the system code when present) on a hook or thread + // creation failure after joining the workers already started. + [[nodiscard]] Void::Result::Result start( + std::size_t count, + const std::function(std::size_t)>& hook); + + // FileWorkerShared::exit_requested must already be set. + void join_for_shutdown() noexcept; + +private: + void rollback_locked() noexcept; + + std::shared_ptr shared_{}; + std::mutex threads_mu_{}; + std::vector threads_{}; + bool started_{false}; +}; + +} // namespace Void::IO::detail diff --git a/tests/standalone/IO/IoFile.cpp b/tests/standalone/IO/IoFile.cpp new file mode 100644 index 0000000..6e0210a --- /dev/null +++ b/tests/standalone/IO/IoFile.cpp @@ -0,0 +1,2124 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ + +using namespace std::chrono_literals; + +using Void::Async::ManualExecutor; +using Void::Async::OperationOptions; +using Void::Async::TaskScope; +using Void::IO::BackendOptions; +using Void::IO::BackendPreference; +using Void::IO::BufferLease; +using Void::IO::ByteStream; +using Void::IO::ComposedTransferError; +using Void::IO::Driver; +using Void::IO::DriverShutdownReport; +using Void::IO::File; +using Void::IO::FileOpenOptions; +using Void::IO::FileSyscallResult; +using Void::IO::FileSyscalls; +using Void::IO::IoErrorCode; +using Void::IO::IoLimits; +using Void::IO::SyncMode; +using Void::IO::Transfer; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +using TransferResult = Void::Result::Result; +using VoidResult = Void::Result::Result; +using Composed = std::expected; + +// ── Helpers ────────────────────────────────────────────────────────────────── + +// Isolated per-test temporary directory (mkdtemp under the system temp dir). +class TempDir +{ +public: + TempDir() + { + std::error_code ec; + const auto base = std::filesystem::temp_directory_path(ec); + if (ec) { + return; + } + std::string tmpl = (base / "void_iofile_XXXXXX").string(); + std::vector buf(tmpl.begin(), tmpl.end()); + buf.push_back('\0'); + if (::mkdtemp(buf.data()) != nullptr) { + path_ = std::filesystem::path{buf.data()}; + } + } + + ~TempDir() + { + if (!path_.empty()) { + std::error_code ec; + std::filesystem::remove_all(path_, ec); + } + } + + TempDir(const TempDir&) = delete; + TempDir& operator=(const TempDir&) = delete; + + [[nodiscard]] bool valid() const noexcept { return !path_.empty(); } + [[nodiscard]] std::filesystem::path file(std::string_view name) const { return path_ / name; } + +private: + std::filesystem::path path_{}; +}; + +[[nodiscard]] std::span as_bytes(std::string_view sv) noexcept +{ + return std::as_bytes(std::span{sv.data(), sv.size()}); +} + +[[nodiscard]] std::string as_string(std::span b) +{ + return std::string{reinterpret_cast(b.data()), b.size()}; +} + +[[nodiscard]] std::string read_file(const std::filesystem::path& p) +{ + std::ifstream in{p, std::ios::binary}; + return std::string{std::istreambuf_iterator{in}, std::istreambuf_iterator{}}; +} + +void write_file(const std::filesystem::path& p, std::string_view content) +{ + std::ofstream out{p, std::ios::binary | std::ios::trunc}; + out.write(content.data(), static_cast(content.size())); +} + +[[nodiscard]] bool io_code(const Void::Result::Error& e, IoErrorCode c) noexcept +{ + return e.code().domain == Void::Result::kIoErrorDomain && + e.code().value == static_cast(c); +} + +template +[[nodiscard]] bool failed_with(const std::optional>& r, IoErrorCode c) +{ + return r.has_value() && !r->has_value() && io_code(r->error(), c); +} + +template +[[nodiscard]] bool failed_with(const Void::Result::Result& r, IoErrorCode c) +{ + return !r.has_value() && io_code(r.error(), c); +} + +[[nodiscard]] bool is_self_join(const Void::Result::Error& e) noexcept +{ + return e.code().domain == Void::Result::kAsyncErrorDomain && + e.code().value == static_cast(Void::Async::AsyncErrorCode::self_join); +} + +[[nodiscard]] std::unique_ptr make_driver( + Void::Async::Executor& exec, + BackendOptions options, + const Void::Time::MonotonicClock& clock = Void::Time::SystemMonotonicClock::instance()) +{ + auto res = Driver::create(exec, std::move(options), clock); + require(res.has_value()); + return std::move(*res); +} + +[[nodiscard]] File open_rw(Driver& driver, const std::filesystem::path& p) +{ + auto f = driver.open_file(p, FileOpenOptions{.read = true, .write = true, .create = true}); + require(f.has_value()); + return std::move(*f); +} + +template +bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms) +{ + const auto end = std::chrono::steady_clock::now() + timeout; + while (!pred()) { + if (std::chrono::steady_clock::now() >= end) { + return pred(); + } + std::this_thread::sleep_for(200us); + } + return true; +} + +// Drives poll turns and the executor until `done` (bounded). +template +bool pump(Driver& driver, ManualExecutor& exec, Pred done, int max_iters = 5000) +{ + for (int i = 0; i < max_iters; ++i) { + (void)exec.drain(); + if (done()) { + return true; + } + (void)driver.poll_once(1ms); + (void)exec.drain(); + if (done()) { + return true; + } + if (driver.active_backend() == BackendPreference::mock) { + std::this_thread::sleep_for(100us); + } + } + return done(); +} + +// A latch-like gate used by shims to hold a syscall on a worker. +class Gate +{ +public: + void wait() + { + std::unique_lock lk{mu_}; + ++waiting_; + cv_.notify_all(); + cv_.wait(lk, [this] { return open_; }); + } + + [[nodiscard]] bool wait_for_waiters(int n, std::chrono::milliseconds timeout = 5000ms) + { + std::unique_lock lk{mu_}; + return cv_.wait_for(lk, timeout, [&] { return waiting_ >= n; }); + } + + void open() + { + std::lock_guard lk{mu_}; + open_ = true; + cv_.notify_all(); + } + +private: + std::mutex mu_{}; + std::condition_variable cv_{}; + bool open_{false}; + int waiting_{0}; +}; + +// Opens the gate on scope exit so a failing require never strands a worker. +struct GateOpener { + Gate& gate; + ~GateOpener() { gate.open(); } +}; + +// Counting shim with optional gates and injected failures. +class TestSyscalls : public FileSyscalls +{ +public: + std::atomic preads{0}; + std::atomic pwrites{0}; + std::atomic syncs{0}; + std::atomic closes{0}; + std::atomic gate_pread{false}; + std::atomic gate_pwrite{false}; + std::atomic gate_sync{false}; + std::atomic sync_error{0}; + std::atomic eintr_pread{0}; + std::atomic eintr_pwrite{0}; + std::atomic eintr_sync{0}; + std::atomic eintr_close{false}; + std::atomic worker_marker_in_pread{false}; + Gate gate{}; + + [[nodiscard]] int total() const noexcept + { + return preads.load() + pwrites.load() + syncs.load() + closes.load(); + } + + FileSyscallResult pread(int fd, std::span buf, std::uint64_t offset) noexcept override + { + preads.fetch_add(1); + worker_marker_in_pread.store(Void::IO::is_io_worker_thread()); + if (eintr_pread.load() > 0) { + eintr_pread.fetch_sub(1); + return FileSyscallResult{-1, EINTR}; + } + if (gate_pread.load()) { + gate.wait(); + } + return FileSyscalls::pread(fd, buf, offset); + } + + FileSyscallResult pwrite(int fd, std::span buf, std::uint64_t offset) noexcept override + { + pwrites.fetch_add(1); + if (eintr_pwrite.load() > 0) { + eintr_pwrite.fetch_sub(1); + return FileSyscallResult{-1, EINTR}; + } + if (gate_pwrite.load()) { + gate.wait(); + } + return FileSyscalls::pwrite(fd, buf, offset); + } + + FileSyscallResult sync(int fd, SyncMode mode) noexcept override + { + syncs.fetch_add(1); + if (eintr_sync.load() > 0) { + eintr_sync.fetch_sub(1); + return FileSyscallResult{-1, EINTR}; + } + if (gate_sync.load()) { + gate.wait(); + } + if (const int err = sync_error.load(); err != 0) { + return FileSyscallResult{-1, err}; + } + return FileSyscalls::sync(fd, mode); + } + + FileSyscallResult close(int fd) noexcept override + { + closes.fetch_add(1); + const FileSyscallResult r = FileSyscalls::close(fd); + if (eintr_close.load()) { + return FileSyscallResult{-1, EINTR}; + } + return r; + } +}; + +// ── Coroutine bodies ───────────────────────────────────────────────────────── + +Void::Coro::Task do_read(File* f, + std::uint64_t off, + std::span buf, + OperationOptions opts, + std::optional* out) +{ + *out = co_await f->read_at(off, buf, opts); +} + +Void::Coro::Task do_write(File* f, + std::uint64_t off, + std::span buf, + OperationOptions opts, + std::optional* out) +{ + *out = co_await f->write_at(off, buf, opts); +} + +Void::Coro::Task do_write_owned(File* f, + std::uint64_t off, + const BufferLease* lease, + OperationOptions opts, + std::optional* out) +{ + *out = co_await f->write_at_owned(off, *lease, opts); +} + +Void::Coro::Task do_sync(File* f, SyncMode mode, OperationOptions opts, std::optional* out) +{ + *out = co_await f->sync(mode, opts); +} + +Void::Coro::Task do_close(File* f, OperationOptions opts, std::optional* out) +{ + *out = co_await f->close_and_join(opts); +} + +Void::Coro::Task do_write_all(File* f, + std::uint64_t off, + std::span buf, + std::optional* out) +{ + *out = co_await Void::IO::write_all_at(*f, off, buf); +} + +Void::Coro::Task do_stream_read(ByteStream* s, + std::span buf, + OperationOptions opts, + std::optional* out) +{ + *out = co_await s->read_some(buf, opts); +} + +template +void spawn(Scope& scope, Task&& task) +{ + require(scope.spawn(std::forward(task)).has_value()); +} + +// Executor whose completion lane resumes inline (inside the poll turn). +class InlineExecutor final : public Void::Async::Executor +{ +public: + void post(std::coroutine_handle<> h) override + { + if (h) { + h.resume(); + } + } + void post_completion(std::coroutine_handle<> h) override + { + if (h) { + h.resume(); + } + } + [[nodiscard]] bool has_background_workers() const noexcept override { return false; } +}; + +// Forwards to a ManualExecutor and records the worker marker seen while the +// poll turn dispatches a completion. +class RecordingExecutor final : public Void::Async::Executor +{ +public: + explicit RecordingExecutor(ManualExecutor& inner) noexcept + : inner_(inner) + { + } + void post(std::coroutine_handle<> h) override { inner_.post(h); } + void post_completion(std::coroutine_handle<> h) override + { + posted.fetch_add(1); + marker_in_dispatch.store(Void::IO::is_io_worker_thread()); + inner_.post_completion(h); + } + [[nodiscard]] bool has_background_workers() const noexcept override { return false; } + + std::atomic posted{0}; + std::atomic marker_in_dispatch{true}; + +private: + ManualExecutor& inner_; +}; + +// Clock whose now() requests stop on an armed stop_source (D1 seam). +class StopOnNowClock final : public Void::Time::MonotonicClock +{ +public: + [[nodiscard]] time_point now() const noexcept override + { + calls.fetch_add(1); + if (auto* src = armed.load()) { + src->request_stop(); + } + return time_point{std::chrono::seconds{1000}}; + } + + mutable std::atomic calls{0}; + std::atomic armed{nullptr}; +}; + +[[nodiscard]] BackendOptions mock_options(IoLimits limits = {}, FileSyscalls* sys = nullptr) +{ + return BackendOptions{.limits = limits, .preference = BackendPreference::mock, .file_syscalls = sys}; +} + +[[nodiscard]] BackendOptions epoll_options(IoLimits limits = {}, FileSyscalls* sys = nullptr) +{ + return BackendOptions{.limits = limits, .preference = BackendPreference::epoll, .file_syscalls = sys}; +} + +} // namespace + +// ── Tests ──────────────────────────────────────────────────────────────────── + +Void::Testing::Test io_file_native_roundtrip_isolated_tmpdir() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + const auto path = dir.file("roundtrip.bin"); + const std::string payload = "positional file roundtrip through bounded workers"; + std::array rbuf{}; + std::optional wrote; + std::optional read_res; + std::optional synced_full; + std::optional synced_data; + std::optional closed; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 2})); + require(drv->start_file_workers().has_value()); + expect_eq(drv->telemetry().file_workers_running, std::size_t{2}); + + auto f = drv->open_file(path, FileOpenOptions{.read = true, .write = true, .create = true, .exclusive = true}); + require(f.has_value()); + file = std::move(*f); + expect(file.valid()); + expect(file.id().valid()); + expect_eq(drv->telemetry().active_descriptors, std::size_t{1}); + + spawn(scope, do_write_all(&file, 0, as_bytes(payload), &wrote)); + require(pump(*drv, exec, [&] { return wrote.has_value(); })); + require(wrote->has_value()); + expect_eq(**wrote, payload.size()); + + spawn(scope, do_sync(&file, SyncMode::full, {}, &synced_full)); + spawn(scope, do_sync(&file, SyncMode::data, {}, &synced_data)); + require(pump(*drv, exec, [&] { return synced_full.has_value() && synced_data.has_value(); })); + expect(synced_full->has_value()); + expect(synced_data->has_value()); + + spawn(scope, do_read(&file, 0, rbuf, {}, &read_res)); + require(pump(*drv, exec, [&] { return read_res.has_value(); })); + require(read_res->has_value()); + expect_eq((*read_res)->bytes, payload.size()); + expect(!(*read_res)->eof); + expect_eq(as_string(std::span{rbuf}.first(payload.size())), payload); + + // Read at EOF: 0 bytes for a non-zero length means EOF. + std::optional eof_res; + spawn(scope, do_read(&file, payload.size(), rbuf, {}, &eof_res)); + require(pump(*drv, exec, [&] { return eof_res.has_value(); })); + require(eof_res->has_value()); + expect_eq((*eof_res)->bytes, std::size_t{0}); + expect((*eof_res)->eof); + + spawn(scope, do_close(&file, {}, &closed)); + require(pump(*drv, exec, [&] { return closed.has_value(); })); + expect(closed->has_value()); + expect(!file.valid()); + require(pump(*drv, exec, [&] { return drv->telemetry().active_descriptors == 0; })); + expect_eq(drv->telemetry().active_operations, std::size_t{0}); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{0}); + + // exclusive + create on an existing path surfaces the native errno. + auto again = drv->open_file(path, FileOpenOptions{.read = false, .write = true, .create = true, .exclusive = true}); + require(!again.has_value()); + expect(io_code(again.error(), IoErrorCode::os_error)); + expect(again.error().system_code() == std::error_code(EEXIST, std::generic_category())); + + // Flag validation. + expect(failed_with(drv->open_file(path, FileOpenOptions{.read = false, .write = false}), + IoErrorCode::invalid_argument)); + expect(failed_with(drv->open_file(path, FileOpenOptions{.read = true, .write = false, .truncate = true}), + IoErrorCode::invalid_argument)); + expect(failed_with(drv->open_file(path, FileOpenOptions{.read = true, .exclusive = true}), + IoErrorCode::invalid_argument)); + expect_eq(drv->telemetry().active_descriptors, std::size_t{0}); + + // adopt_file_fd and a default (read-only) open of the same path. + auto ro = drv->adopt_file_fd(::open(path.c_str(), O_RDONLY | O_CLOEXEC)); + require(ro.has_value()); + File ro_file = std::move(*ro); + auto ro2 = drv->open_file(path); + require(ro2.has_value()); + } + expect_eq(read_file(path), payload); +} + +Void::Testing::Test io_file_short_write_preserves_progress_write_all_at() +{ + class ShortWrites final : public FileSyscalls + { + public: + std::atomic pwrites{0}; + std::atomic zero{false}; + FileSyscallResult pwrite(int fd, std::span buf, std::uint64_t off) noexcept override + { + pwrites.fetch_add(1); + if (zero.load()) { + return FileSyscallResult{0, 0}; + } + return FileSyscalls::pwrite(fd, buf.first(std::min(buf.size(), 3)), off); + } + }; + + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + ShortWrites sys; + const auto path = dir.file("short.bin"); + const std::string payload = "0123456789abcdefghij"; // 20 bytes + std::optional wrote; + std::optional stuck; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 1}, &sys)); + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, path); + + spawn(scope, do_write_all(&file, 5, as_bytes(payload), &wrote)); + require(pump(*drv, exec, [&] { return wrote.has_value(); })); + require(wrote->has_value()); + expect_eq(**wrote, payload.size()); + expect_eq(sys.pwrites.load(), 7); // ceil(20 / 3) single-syscall requests + + // A zero-byte pwrite with bytes remaining is an error, not a loop. + sys.zero.store(true); + const int before = sys.pwrites.load(); + spawn(scope, do_write_all(&file, 0, as_bytes("xyz"), &stuck)); + require(pump(*drv, exec, [&] { return stuck.has_value(); })); + require(!stuck->has_value()); + expect_eq(stuck->error().bytes_transferred, std::size_t{0}); + expect(io_code(stuck->error().error, IoErrorCode::os_error)); + expect_eq(sys.pwrites.load(), before + 1); + } + expect_eq(read_file(path), std::string(5, '\0') + payload); +} + +Void::Testing::Test io_file_writes_syncs_serialized_admission_order() +{ + class OrderSyscalls final : public FileSyscalls + { + public: + std::mutex mu; + std::vector order; + int in_serial{0}; + int max_serial{0}; + std::atomic hold_first{true}; + Gate gate; + + void enter(std::string tag) + { + std::lock_guard lk{mu}; + ++in_serial; + max_serial = std::max(max_serial, in_serial); + order.push_back(std::move(tag)); + } + void leave() + { + std::lock_guard lk{mu}; + --in_serial; + } + FileSyscallResult pwrite(int fd, std::span buf, std::uint64_t off) noexcept override + { + enter("W" + std::to_string(off)); + if (hold_first.exchange(false)) { + gate.wait(); + } else { + std::this_thread::sleep_for(1ms); // widen any overlap window + } + const auto r = FileSyscalls::pwrite(fd, buf, off); + leave(); + return r; + } + FileSyscallResult sync(int fd, SyncMode mode) noexcept override + { + enter("S"); + std::this_thread::sleep_for(1ms); + const auto r = FileSyscalls::sync(fd, mode); + leave(); + return r; + } + }; + + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + OrderSyscalls sys; + const auto path = dir.file("order.bin"); + std::array, 4> writes{}; + std::array, 2> syncs{}; + const std::array bytes{"a", "b", "c", "d"}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 4}, &sys)); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, path); + + // Admission order: W0 W1 S W2 S W3. + spawn(scope, do_write(&file, 0, as_bytes(bytes[0]), {}, &writes[0])); + spawn(scope, do_write(&file, 1, as_bytes(bytes[1]), {}, &writes[1])); + spawn(scope, do_sync(&file, SyncMode::full, {}, &syncs[0])); + spawn(scope, do_write(&file, 2, as_bytes(bytes[2]), {}, &writes[2])); + spawn(scope, do_sync(&file, SyncMode::data, {}, &syncs[1])); + spawn(scope, do_write(&file, 3, as_bytes(bytes[3]), {}, &writes[3])); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + // Four idle workers, yet only the first serialized request is active. + std::this_thread::sleep_for(10ms); + expect_eq(drv->telemetry().active_file_requests, std::size_t{1}); + expect_eq(drv->telemetry().queued_file_requests, std::size_t{5}); + sys.gate.open(); + + require(pump(*drv, exec, [&] { + return std::all_of(writes.begin(), writes.end(), [](const auto& w) { return w.has_value(); }) && + std::all_of(syncs.begin(), syncs.end(), [](const auto& s) { return s.has_value(); }); + })); + for (const auto& w : writes) { + require(w->has_value()); + expect_eq((*w)->bytes, std::size_t{1}); + } + for (const auto& s : syncs) { + expect(s->has_value()); + } + } + { + std::lock_guard lk{sys.mu}; + const std::vector expected_order{"W0", "W1", "S", "W2", "S", "W3"}; + expect(sys.order == expected_order); + expect_eq(sys.max_serial, 1); + } + expect_eq(read_file(path), std::string{"abcd"}); +} + +Void::Testing::Test io_file_reads_concurrent_explicit_offsets() +{ + class BarrierReads final : public FileSyscalls + { + public: + std::mutex mu; + std::condition_variable cv; + int inflight{0}; + int max_inflight{0}; + int target{3}; + FileSyscallResult pread(int fd, std::span buf, std::uint64_t off) noexcept override + { + { + std::unique_lock lk{mu}; + ++inflight; + max_inflight = std::max(max_inflight, inflight); + cv.notify_all(); + (void)cv.wait_for(lk, 5s, [this] { return max_inflight >= target; }); + } + const auto r = FileSyscalls::pread(fd, buf, off); + std::lock_guard lk{mu}; + --inflight; + return r; + } + }; + + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + BarrierReads sys; + const auto path = dir.file("reads.bin"); + std::string content; + for (int i = 0; i < 300; ++i) { + content.push_back(static_cast('A' + (i % 26))); + } + write_file(path, content); + std::array, 3> bufs{}; + std::array, 3> reads{}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 3}, &sys)); + require(drv->start_file_workers().has_value()); + auto f = drv->open_file(path); + require(f.has_value()); + file = std::move(*f); + // Reverse offsets: results must follow each request's explicit offset. + spawn(scope, do_read(&file, 200, bufs[2], {}, &reads[2])); + spawn(scope, do_read(&file, 100, bufs[1], {}, &reads[1])); + spawn(scope, do_read(&file, 0, bufs[0], {}, &reads[0])); + require(pump(*drv, exec, [&] { + return std::all_of(reads.begin(), reads.end(), [](const auto& r) { return r.has_value(); }); + })); + } + for (std::size_t i = 0; i < 3; ++i) { + require(reads[i]->has_value()); + expect_eq((*reads[i])->bytes, std::size_t{100}); + expect_eq(as_string(bufs[i]), content.substr(i * 100, 100)); + } + std::lock_guard lk{sys.mu}; + expect_eq(sys.max_inflight, 3); +} + +Void::Testing::Test io_file_queue_and_ops_quota_overloaded() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + std::array, 6> w{}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver( + exec, mock_options(IoLimits{.max_operations = 3, .max_file_queue = 2}, &sys)); + file = open_rw(*drv, dir.file("quota.bin")); + + spawn(scope, do_write(&file, 0, as_bytes("0"), {}, &w[0])); + spawn(scope, do_write(&file, 1, as_bytes("1"), {}, &w[1])); + spawn(scope, do_write(&file, 2, as_bytes("2"), {}, &w[2])); // max_file_queue + (void)exec.drain(); + expect_eq(drv->telemetry().queued_file_requests, std::size_t{2}); + expect(failed_with(w[2], IoErrorCode::overloaded)); + + // One executed (result queued, not yet retired): still counts in ops. + require(drv->run_file_work(1).has_value()); + spawn(scope, do_write(&file, 3, as_bytes("3"), {}, &w[3])); + (void)exec.drain(); + expect(!w[3].has_value()); + expect_eq(drv->telemetry().active_operations, std::size_t{3}); + require(drv->run_file_work(1).has_value()); + spawn(scope, do_write(&file, 4, as_bytes("4"), {}, &w[4])); // max_operations + (void)exec.drain(); + expect(failed_with(w[4], IoErrorCode::overloaded)); + expect_eq(drv->telemetry().queued_file_requests, std::size_t{1}); + + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(w[0].has_value() && w[0]->has_value()); + expect(w[1].has_value() && w[1]->has_value()); + expect_eq(drv->telemetry().active_operations, std::size_t{1}); + spawn(scope, do_write(&file, 5, as_bytes("5"), {}, &w[5])); + (void)exec.drain(); + auto ran = drv->run_file_work(8); + require(ran.has_value()); + expect_eq(*ran, std::size_t{2}); + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(w[3].has_value() && w[3]->has_value()); + expect(w[5].has_value() && w[5]->has_value()); + expect_eq(drv->telemetry().active_operations, std::size_t{0}); + } + expect_eq(sys.pwrites.load(), 4); +} + +Void::Testing::Test io_file_queued_cancel_not_committed_zero_effects() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + const auto path = dir.file("cancel.bin"); + write_file(path, "original"); + std::stop_source wsrc; + std::stop_source ssrc; + std::stop_source rsrc; + std::optional w; + std::optional s; + std::optional r; + std::array rbuf{}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options({}, &sys)); + file = open_rw(*drv, path); + spawn(scope, do_write(&file, 0, as_bytes("XXXXXXXX"), OperationOptions{.stop = wsrc.get_token()}, &w)); + spawn(scope, do_sync(&file, SyncMode::full, OperationOptions{.stop = ssrc.get_token()}, &s)); + spawn(scope, do_read(&file, 0, rbuf, OperationOptions{.stop = rsrc.get_token()}, &r)); + (void)exec.drain(); + expect_eq(drv->telemetry().queued_file_requests, std::size_t{3}); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{16}); + + wsrc.request_stop(); + ssrc.request_stop(); + rsrc.request_stop(); + expect_eq(drv->telemetry().queued_file_requests, std::size_t{0}); + auto ran = drv->run_file_work(8); + require(ran.has_value()); + expect_eq(*ran, std::size_t{0}); + expect(!w.has_value()); // delivered only by a poll turn + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(failed_with(w, IoErrorCode::cancelled)); + expect(failed_with(s, IoErrorCode::cancelled)); + expect(failed_with(r, IoErrorCode::cancelled)); + expect_eq(drv->telemetry().active_operations, std::size_t{0}); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{0}); + } + expect_eq(sys.preads.load() + sys.pwrites.load() + sys.syncs.load(), 0); + expect_eq(read_file(path), std::string{"original"}); +} + +Void::Testing::Test io_file_queued_deadline_expires_once_manual_clock_poll() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}}; + std::optional expired; + int expired_deliveries = 0; + std::optional late_but_unmarked; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options({}, &sys), clock); + file = open_rw(*drv, dir.file("deadline.bin")); + + auto counted = [](File* f, OperationOptions o, std::optional* out, int* n) + -> Void::Coro::Task { + *out = co_await f->write_at(0, as_bytes("late"), o); + ++(*n); + }; + spawn(scope, counted(&file, OperationOptions{.deadline = clock.now() + 5s}, &expired, &expired_deliveries)); + (void)exec.drain(); + (void)clock.advance(5s); + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(failed_with(expired, IoErrorCode::timeout)); + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect_eq(expired_deliveries, 1); + auto ran = drv->run_file_work(4); + require(ran.has_value()); + expect_eq(*ran, std::size_t{0}); + expect_eq(sys.pwrites.load(), 0); + + // S3: workers never read the clock; without a poll turn marking it + // expired, a request past its deadline still executes. + spawn(scope, do_write(&file, 0, as_bytes("ok"), OperationOptions{.deadline = clock.now() + 1s}, &late_but_unmarked)); + (void)exec.drain(); + (void)clock.advance(2s); + ran = drv->run_file_work(1); + require(ran.has_value()); + expect_eq(*ran, std::size_t{1}); + require(drv->poll_once().has_value()); + (void)exec.drain(); + require(late_but_unmarked.has_value()); + expect(late_but_unmarked->has_value()); + } + // Epoll: the wait bound includes the earliest queued-file deadline. + { + std::optional bounded; + File efile; + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options()); + efile = open_rw(*drv, dir.file("deadline_epoll.bin")); + const auto& sys_clock = Void::Time::SystemMonotonicClock::instance(); + spawn(scope, do_write(&efile, 0, as_bytes("x"), OperationOptions{.deadline = sys_clock.now() + 30ms}, &bounded)); + (void)exec.drain(); + const auto start = std::chrono::steady_clock::now(); + for (int i = 0; i < 20 && !bounded.has_value(); ++i) { + (void)drv->poll_once(std::chrono::seconds{4}); + (void)exec.drain(); + } + const auto elapsed = std::chrono::steady_clock::now() - start; + expect(failed_with(bounded, IoErrorCode::timeout)); + expect(elapsed < 2s); + } +} + +Void::Testing::Test io_file_active_timeout_retains_buffer_until_syscall_returns() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_pwrite.store(true); + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}}; + std::optional w; + const auto path = dir.file("active_timeout.bin"); + BufferLease lease; // outlives the Driver (and so the active syscall) + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 1}, &sys), clock); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, path); + auto alloc = drv->allocate_buffer(16); + require(alloc.has_value()); + lease = std::move(*alloc); + std::memset(lease.writable().data(), 'L', lease.size()); + + spawn(scope, do_write_owned(&file, 0, &lease, OperationOptions{.deadline = clock.now() + 1s}, &w)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + (void)clock.advance(2s); + for (int i = 0; i < 3; ++i) { + require(drv->poll_once().has_value()); + (void)exec.drain(); + } + expect(!w.has_value()); + expect_eq(drv->telemetry().active_file_requests, std::size_t{1}); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{16}); + expect_eq(drv->telemetry().owned_buffer_bytes, std::size_t{16}); + + sys.gate.open(); + require(pump(*drv, exec, [&] { return w.has_value(); })); + require(w->has_value()); // the syscall's actual outcome, not timeout + expect_eq((*w)->bytes, std::size_t{16}); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{0}); + } + expect_eq(read_file(path), std::string(16, 'L')); +} + +Void::Testing::Test io_file_sync_success_after_stop_is_success() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_sync.store(true); + std::stop_source src; + std::optional s; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 1}, &sys)); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, dir.file("sync_ok.bin")); + spawn(scope, do_sync(&file, SyncMode::full, OperationOptions{.stop = src.get_token()}, &s)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + src.request_stop(); + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(!s.has_value()); + sys.gate.open(); + require(pump(*drv, exec, [&] { return s.has_value(); })); + expect(s->has_value()); + } + expect_eq(sys.syncs.load(), 1); +} + +Void::Testing::Test io_file_sync_failure_after_stop_sync_failed_unknown_errno() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_sync.store(true); + sys.sync_error.store(EIO); + std::stop_source src; + std::optional s; + std::optional s2; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 1}, &sys)); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, dir.file("sync_fail.bin")); + spawn(scope, do_sync(&file, SyncMode::data, OperationOptions{.stop = src.get_token()}, &s)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + src.request_stop(); + sys.gate.open(); + require(pump(*drv, exec, [&] { return s.has_value(); })); + require(failed_with(s, IoErrorCode::sync_failed)); + expect((*s).error().system_code() == std::error_code(EIO, std::generic_category())); + expect((*s).error().kind() == Void::Result::ErrorKind::io); + + // Failure without stop is equally authoritative. + sys.sync_error.store(ENOSPC); + spawn(scope, do_sync(&file, SyncMode::full, {}, &s2)); + require(pump(*drv, exec, [&] { return s2.has_value(); })); + require(failed_with(s2, IoErrorCode::sync_failed)); + expect((*s2).error().system_code() == std::error_code(ENOSPC, std::generic_category())); + } +} + +Void::Testing::Test io_file_manual_stepping_without_workers() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + std::optional w; + std::optional r; + std::array rbuf{}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 2}, &sys)); + file = open_rw(*drv, dir.file("manual.bin")); + expect_eq(drv->telemetry().file_workers_running, std::size_t{0}); + + spawn(scope, do_write(&file, 0, as_bytes("hello"), {}, &w)); + (void)exec.drain(); + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(!w.has_value()); + expect_eq(sys.pwrites.load(), 0); + + auto zero = drv->run_file_work(0); + require(zero.has_value()); + expect_eq(*zero, std::size_t{0}); + auto one = drv->run_file_work(1); + require(one.has_value()); + expect_eq(*one, std::size_t{1}); + expect_eq(sys.pwrites.load(), 1); + (void)exec.drain(); + expect(!w.has_value()); // results are queued, never delivered by run_file_work + require(drv->poll_once().has_value()); + (void)exec.drain(); + require(w.has_value() && w->has_value()); + expect_eq((*w)->bytes, std::size_t{5}); + + spawn(scope, do_read(&file, 0, rbuf, {}, &r)); + (void)exec.drain(); + auto ran = drv->run_file_work(10); + require(ran.has_value()); + expect_eq(*ran, std::size_t{1}); + auto none = drv->run_file_work(10); + require(none.has_value()); + expect_eq(*none, std::size_t{0}); + require(drv->poll_once().has_value()); + (void)exec.drain(); + require(r.has_value() && r->has_value()); + expect_eq(as_string(rbuf), std::string{"hello"}); + + require(drv->start_file_workers().has_value()); + expect(failed_with(drv->run_file_work(1), IoErrorCode::busy)); + } +} + +Void::Testing::Test io_file_shutdown_joins_stalled_worker_then_delivers() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_pwrite.store(true); + std::optional w; + int deliveries = 0; + const auto path = dir.file("stalled.bin"); + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 2}, &sys)); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, path); + auto counted = [](File* f, std::optional* out, int* n) -> Void::Coro::Task { + *out = co_await f->write_at(0, as_bytes("stalled"), {}); + ++(*n); + }; + spawn(scope, counted(&file, &w, &deliveries)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + + std::atomic joined{false}; + Void::Result::Result join_res{}; + std::thread joiner([&] { + join_res = drv->shutdown_and_join(); + joined.store(true); + }); + std::this_thread::sleep_for(30ms); + expect(!joined.load()); + expect(!drv->shutdown_complete()); + expect_eq(drv->telemetry().file_workers_running, std::size_t{2}); + sys.gate.open(); + joiner.join(); + expect(join_res.has_value()); + expect(drv->shutdown_complete()); + expect_eq(drv->telemetry().file_workers_running, std::size_t{0}); + expect_eq(drv->telemetry().active_descriptors, std::size_t{0}); + (void)exec.drain(); + require(w.has_value() && w->has_value()); + expect_eq((*w)->bytes, std::size_t{7}); + expect_eq(deliveries, 1); + expect_eq(sys.closes.load(), 1); + } + expect_eq(deliveries, 1); + expect_eq(read_file(path), std::string{"stalled"}); +} + +Void::Testing::Test io_file_shutdown_from_worker_self_join() +{ + class SelfJoinSyscalls final : public FileSyscalls + { + public: + std::atomic driver{nullptr}; + std::atomic join_self_join{false}; + std::atomic shutdown_self_join{false}; + std::atomic on_worker{false}; + FileSyscallResult pwrite(int fd, std::span buf, std::uint64_t off) noexcept override + { + // The one documented worker-side Driver call: detected, no state change. + if (auto* d = driver.load()) { + on_worker.store(Void::IO::is_io_worker_thread()); + auto r1 = d->shutdown_and_join(); + join_self_join.store(!r1.has_value() && is_self_join(r1.error())); + auto r2 = d->shutdown(OperationOptions{}); + shutdown_self_join.store(!r2.has_value() && is_self_join(r2.error())); + } + return FileSyscalls::pwrite(fd, buf, off); + } + }; + + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + SelfJoinSyscalls sys; + std::optional w; + std::optional w2; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 1}, &sys)); + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, dir.file("selfjoin.bin")); + sys.driver.store(drv.get()); + spawn(scope, do_write(&file, 0, as_bytes("abc"), {}, &w)); + require(pump(*drv, exec, [&] { return w.has_value(); })); + sys.driver.store(nullptr); + expect(sys.on_worker.load()); + expect(sys.join_self_join.load()); + expect(sys.shutdown_self_join.load()); + require(w->has_value()); + expect(!drv->shutdown_complete()); + // No state changed: the Driver still admits work. + spawn(scope, do_write(&file, 3, as_bytes("def"), {}, &w2)); + require(pump(*drv, exec, [&] { return w2.has_value(); })); + expect(w2->has_value()); + } +} + +Void::Testing::Test io_file_workers_partial_start_failure_joins_started() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + std::atomic fail_at{2}; + std::mutex calls_mu; + std::vector calls; + std::optional w; + File file; + { + TaskScope scope{exec}; + BackendOptions opts = mock_options(IoLimits{.file_workers = 4}); + opts.before_file_worker_start = [&](std::size_t index) -> Void::Result::Result { + { + std::lock_guard lk{calls_mu}; + calls.push_back(index); + } + if (static_cast(index) == fail_at.load()) { + return std::unexpected{Void::IO::make_io_error( + IoErrorCode::os_error, "injected thread start failure", + std::error_code(EAGAIN, std::generic_category()))}; + } + return {}; + }; + auto drv = make_driver(exec, std::move(opts)); + file = open_rw(*drv, dir.file("partial.bin")); + // Queued before any worker exists; it must survive the failed start. + spawn(scope, do_write(&file, 0, as_bytes("queued"), {}, &w)); + (void)exec.drain(); + + auto first = drv->start_file_workers(); + require(!first.has_value()); + expect(io_code(first.error(), IoErrorCode::os_error)); + expect(first.error().system_code() == std::error_code(EAGAIN, std::generic_category())); + expect_eq(drv->telemetry().file_workers_running, std::size_t{0}); + { + std::lock_guard lk{calls_mu}; + expect(calls == std::vector{0, 1, 2}); + calls.clear(); + } + expect(!w.has_value()); + + fail_at.store(-1); + require(drv->start_file_workers().has_value()); + expect_eq(drv->telemetry().file_workers_running, std::size_t{4}); + { + std::lock_guard lk{calls_mu}; + expect(calls == std::vector{0, 1, 2, 3}); + } + require(pump(*drv, exec, [&] { return w.has_value(); })); + expect(w->has_value()); + } +} + +Void::Testing::Test io_file_drop_with_inflight_defers_close_until_drained() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_pread.store(true); + const auto path = dir.file("drop.bin"); + write_file(path, "deferred"); + std::array rbuf{}; + std::optional r; + { + File file; + TaskScope scope{exec}; + // Two workers: an idle one would run a premature close immediately. + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 2}, &sys)); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + auto f = drv->open_file(path); + require(f.has_value()); + file = std::move(*f); + spawn(scope, do_read(&file, 0, rbuf, {}, &r)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + + { + File dropped = std::move(file); // ~File with a request in flight + } + expect(!file.valid()); + std::this_thread::sleep_for(10ms); + expect_eq(sys.closes.load(), 0); + expect_eq(drv->telemetry().active_descriptors, std::size_t{1}); + + sys.gate.open(); + require(pump(*drv, exec, [&] { return r.has_value(); })); + require(r->has_value()); + expect_eq(as_string(rbuf), std::string{"deferred"}); + require(pump(*drv, exec, [&] { return drv->telemetry().active_descriptors == 0; })); + expect_eq(sys.closes.load(), 1); + } + expect_eq(sys.closes.load(), 1); +} + +Void::Testing::Test io_file_close_and_join_expiry_incomplete_retains_then_completes() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_pread.store(true); + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{20}}}; + const auto path = dir.file("close_expiry.bin"); + write_file(path, "retained"); + std::array rbuf{}; + std::optional r; + std::optional c1; + std::optional c_stopped; + std::optional after; + std::optional c2; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 2}, &sys), clock); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + auto f = drv->open_file(path); + require(f.has_value()); + file = std::move(*f); + spawn(scope, do_read(&file, 0, rbuf, {}, &r)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + + spawn(scope, do_close(&file, OperationOptions{.deadline = clock.now() + 1s}, &c1)); + (void)exec.drain(); + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(!c1.has_value()); // waits for (does not cancel) the active read + (void)clock.advance(2s); + require(drv->poll_once().has_value()); + (void)exec.drain(); + expect(failed_with(c1, IoErrorCode::incomplete_shutdown)); + expect(file.valid()); // File retained, closing + expect_eq(sys.closes.load(), 0); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{8}); + + std::stop_source stopped; + stopped.request_stop(); + spawn(scope, do_close(&file, OperationOptions{.stop = stopped.get_token()}, &c_stopped)); + (void)exec.drain(); + expect(failed_with(c_stopped, IoErrorCode::incomplete_shutdown)); + + const int syscalls_before = sys.total(); + spawn(scope, do_read(&file, 0, rbuf, {}, &after)); + (void)exec.drain(); + expect(failed_with(after, IoErrorCode::closed)); + expect_eq(sys.total(), syscalls_before); + + sys.gate.open(); + require(pump(*drv, exec, [&] { return r.has_value(); })); + require(r->has_value()); + expect_eq(as_string(rbuf), std::string{"retained"}); + + spawn(scope, do_close(&file, {}, &c2)); + require(pump(*drv, exec, [&] { return c2.has_value(); })); + expect(c2->has_value()); + expect(!file.valid()); + require(pump(*drv, exec, [&] { return drv->telemetry().active_descriptors == 0; })); + expect_eq(sys.closes.load(), 1); + } +} + +Void::Testing::Test io_file_ops_after_teardown_closed_no_syscall() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; // must outlive Driver teardown + std::array rbuf{}; + std::optional r; + std::optional w; + std::optional s; + std::optional c; + File file; + TaskScope scope{exec}; + { + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 2}, &sys)); + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, dir.file("teardown.bin")); + } // ~Driver: joins workers and closes the still-open file fd + expect_eq(sys.closes.load(), 1); + expect(file.valid()); + const int before = sys.total(); + spawn(scope, do_read(&file, 0, rbuf, {}, &r)); + spawn(scope, do_write(&file, 0, as_bytes("x"), {}, &w)); + spawn(scope, do_sync(&file, SyncMode::full, {}, &s)); + (void)exec.drain(); + expect(failed_with(r, IoErrorCode::closed)); + expect(failed_with(w, IoErrorCode::closed)); + expect(failed_with(s, IoErrorCode::closed)); + spawn(scope, do_close(&file, {}, &c)); + (void)exec.drain(); + require(c.has_value()); + expect(c->has_value()); + expect(!file.valid()); + expect_eq(sys.total(), before); + require(scope.join_pumping(exec).has_value()); +} + +Void::Testing::Test io_driver_destroyed_from_coroutine_resumed_after_poll_dispatch_same_thread() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + const auto path = dir.file("destroy.bin"); + write_file(path, "data"); + std::array rbuf{}; + std::optional r; + bool destroyed_inside = false; + std::unique_ptr holder; + File file; + TaskScope scope{exec}; + holder = make_driver(exec, mock_options()); + auto f = holder->open_file(path); + require(f.has_value()); + file = std::move(*f); + + auto body = [](File* fl, + std::span buf, + std::unique_ptr* h, + std::optional* out, + bool* flag) -> Void::Coro::Task { + *out = co_await fl->read_at(0, buf); + h->reset(); // ~Driver from a continuation resumed by executor drain + *flag = true; + }; + spawn(scope, body(&file, rbuf, &holder, &r, &destroyed_inside)); + (void)exec.drain(); + require(holder->run_file_work(1).has_value()); + require(holder->poll_once().has_value()); // dispatches the ticket + expect(!destroyed_inside); + (void)exec.drain(); // same thread, outside the poll turn + expect(destroyed_inside); + expect(holder == nullptr); + require(r.has_value() && r->has_value()); + expect_eq(as_string(rbuf), std::string{"data"}); + require(scope.join_pumping(exec).has_value()); +} + +Void::Testing::Test io_worker_thread_marker_only_on_file_workers() +{ + ManualExecutor exec; + RecordingExecutor recording{exec}; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + const auto path = dir.file("marker.bin"); + write_file(path, "mark"); + std::array rbuf{}; + std::optional r; + std::atomic marker_in_drain{true}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(recording, epoll_options(IoLimits{.file_workers = 1}, &sys)); + require(drv->start_file_workers().has_value()); + auto f = drv->open_file(path); + require(f.has_value()); + file = std::move(*f); + auto body = [](File* fl, std::span buf, std::optional* out, + std::atomic* m) -> Void::Coro::Task { + *out = co_await fl->read_at(0, buf); + m->store(Void::IO::is_io_worker_thread()); + }; + spawn(scope, body(&file, rbuf, &r, &marker_in_drain)); + require(pump(*drv, exec, [&] { return r.has_value(); })); + require(r->has_value()); + } + expect(!Void::IO::is_io_worker_thread()); + expect(sys.worker_marker_in_pread.load()); + expect(recording.posted.load() >= 1); + expect(!recording.marker_in_dispatch.load()); + expect(!marker_in_drain.load()); +} + +Void::Testing::Test io_concurrent_poll_once_second_caller_busy_no_fd_touch_tsan() +{ + ManualExecutor exec; + auto drv = make_driver(exec, epoll_options()); + std::atomic first_done{false}; + Void::Result::Result first_res{}; + std::thread first([&] { + first_res = drv->poll_once(std::chrono::seconds{5}); // parked in epoll_wait + first_done.store(true); + }); + require(wait_until([&] { return drv->telemetry().turns == 1; })); + const auto before = drv->telemetry(); + for (int i = 0; i < 50; ++i) { + auto busy = drv->poll_once(std::chrono::nanoseconds{0}); + expect(failed_with(busy, IoErrorCode::busy)); + } + const auto after = drv->telemetry(); + expect_eq(after.turns, before.turns); + expect_eq(after.wakeups, before.wakeups); + expect(!first_done.load()); + drv->wake(); + first.join(); + expect(first_res.has_value()); + auto again = drv->poll_once(std::chrono::nanoseconds{0}); + expect(again.has_value()); + expect_eq(drv->telemetry().turns, std::uint64_t{2}); +} + +Void::Testing::Test io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan() +{ + TempDir dir; + require(dir.valid()); + for (int iter = 0; iter < 10; ++iter) { + ManualExecutor exec; + std::array rbuf{}; + std::optional sock_read; + std::optional file_write; + File file; + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 2})); + require(drv->start_file_workers().has_value()); + auto pair = drv->create_socket_pair(); + require(pair.has_value()); + ByteStream a = std::move(pair->first); + ByteStream b = std::move(pair->second); + file = open_rw(*drv, dir.file("concurrent_" + std::to_string(iter) + ".bin")); + spawn(scope, do_stream_read(&a, rbuf, {}, &sock_read)); + spawn(scope, do_write(&file, 0, as_bytes("concurrent"), {}, &file_write)); + (void)exec.drain(); + + std::atomic busy_count{0}; + std::thread poller([&] { + while (!drv->shutdown_complete()) { + auto res = drv->poll_once(std::chrono::milliseconds{2}); + if (!res.has_value()) { + busy_count.fetch_add(1); + std::this_thread::sleep_for(50us); + } + } + }); + std::this_thread::sleep_for(std::chrono::milliseconds{1 + iter % 3}); + auto report = drv->shutdown(OperationOptions{}); + poller.join(); + require(report.has_value()); + expect(report->complete); + expect_eq(report->pending_operations, std::size_t{0}); + expect_eq(report->open_descriptors, std::size_t{0}); + (void)exec.drain(); + expect(failed_with(sock_read, IoErrorCode::closed)); + require(file_write.has_value()); + expect(file_write->has_value() || failed_with(file_write, IoErrorCode::cancelled)); + (void)b.valid(); + require(scope.join_pumping(exec).has_value()); + } +} + +Void::Testing::Test io_stop_after_completion_releases_backend_ref_once() +{ + InlineExecutor inline_exec; + auto drv = make_driver(inline_exec, epoll_options()); + auto p1 = drv->create_socket_pair(); + auto p2 = drv->create_socket_pair(); + require(p1.has_value() && p2.has_value()); + ByteStream a1 = std::move(p1->first); + ByteStream b1 = std::move(p1->second); + ByteStream a2 = std::move(p2->first); + ByteStream b2 = std::move(p2->second); + require(drv->poll_once(std::chrono::nanoseconds{0}).has_value()); // register fds + + // Peer data is already queued for a2. + { + auto writer = [](ByteStream* s, std::optional* out) -> Void::Coro::Task { + *out = co_await s->write_some(as_bytes("payload")); + }; + std::optional wrote; + auto t = writer(&b2, &wrote); + t.handle().resume(); + for (int i = 0; i < 50 && !wrote.has_value(); ++i) { + (void)drv->poll_once(std::chrono::milliseconds{1}); + } + require(wrote.has_value() && wrote->has_value()); + } + + std::stop_source x_src; + std::stop_source b_src; + std::array xbuf{}; + std::array bbuf{}; + std::optional x_res; + std::optional b_res; + int b_deliveries = 0; + + // X's completion is dispatched (inline) at the start of the turn; its + // continuation stops B, whose read the same turn then completes; the + // end-of-turn cancel pass meets the retired op. + auto x_body = [](ByteStream* s, std::span buf, std::stop_token tok, + std::optional* out, std::stop_source* stop_b) -> Void::Coro::Task { + *out = co_await s->read_some(buf, OperationOptions{.stop = tok}); + stop_b->request_stop(); + }; + auto b_body = [](ByteStream* s, std::span buf, std::stop_token tok, + std::optional* out, int* n) -> Void::Coro::Task { + *out = co_await s->read_some(buf, OperationOptions{.stop = tok}); + ++(*n); + }; + auto tb = b_body(&a2, bbuf, b_src.get_token(), &b_res, &b_deliveries); + tb.handle().resume(); + auto tx = x_body(&a1, xbuf, x_src.get_token(), &x_res, &b_src); + tx.handle().resume(); + expect(!b_res.has_value()); + const auto dup_before = drv->telemetry().duplicate_completions_ignored; + x_src.request_stop(); + require(drv->poll_once(std::chrono::milliseconds{50}).has_value()); + expect(tx.done()); + expect(failed_with(x_res, IoErrorCode::cancelled)); + expect(tb.done()); + expect_eq(b_deliveries, 1); + expect(failed_with(b_res, IoErrorCode::cancelled)); + expect(drv->telemetry().duplicate_completions_ignored > dup_before); + expect_eq(drv->telemetry().active_operations, std::size_t{0}); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{0}); + require(drv->poll_once(std::chrono::nanoseconds{0}).has_value()); + expect_eq(b_deliveries, 1); + + // The stream is intact: the queued bytes are still readable. + std::optional again; + std::array abuf{}; + auto reader = [](ByteStream* s, std::span buf, std::optional* out) + -> Void::Coro::Task { *out = co_await s->read_some(buf); }; + auto tr = reader(&a2, abuf, &again); + tr.handle().resume(); + for (int i = 0; i < 50 && !again.has_value(); ++i) { + (void)drv->poll_once(std::chrono::milliseconds{1}); + } + require(again.has_value() && again->has_value()); + expect_eq(as_string(std::span{abuf}.first((*again)->bytes)), std::string{"payload"}); + (void)b1.valid(); +} + +Void::Testing::Test io_epoll_stop_requested_at_deadline_scan_completes_once() +{ + ManualExecutor exec; + StopOnNowClock clock; + std::stop_source src; + std::array rbuf{}; + std::optional res; + int deliveries = 0; + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(), clock); + auto pair = drv->create_socket_pair(); + require(pair.has_value()); + ByteStream a = std::move(pair->first); + ByteStream b = std::move(pair->second); + require(drv->poll_once(std::chrono::nanoseconds{0}).has_value()); // register fds + + // 1. The socket already has data. + { + std::optional wrote; + auto writer = [](ByteStream* s, std::optional* out) -> Void::Coro::Task { + *out = co_await s->write_some(as_bytes("ready")); + }; + spawn(scope, writer(&b, &wrote)); + require(pump(*drv, exec, [&] { return wrote.has_value(); })); + require(wrote->has_value()); + } + + auto body = [](ByteStream* s, std::span buf, OperationOptions o, + std::optional* out, int* n) -> Void::Coro::Task { + *out = co_await s->read_some(buf, o); + ++(*n); + }; + spawn(scope, body(&a, rbuf, + OperationOptions{.stop = src.get_token(), .deadline = clock.now() + std::chrono::hours{1}}, + &res, &deliveries)); + (void)exec.drain(); + const auto dup_before = drv->telemetry().duplicate_completions_ignored; + // P3-5: armed only after submission (submit reads the clock). + clock.armed.store(&src); + // 2. The wait computation's now() requests stop -> cancel queued. + // 3. drive_read sees the stop and completes the op. + // 4. The end-of-turn cancel pass meets the retired op. + require(drv->poll_once(std::chrono::nanoseconds{0}).has_value()); + clock.armed.store(nullptr); + (void)exec.drain(); + require(drv->poll_once(std::chrono::nanoseconds{0}).has_value()); + (void)exec.drain(); + expect_eq(deliveries, 1); + expect(failed_with(res, IoErrorCode::cancelled)); + expect(drv->telemetry().duplicate_completions_ignored >= dup_before + 1); + expect_eq(drv->telemetry().active_operations, std::size_t{0}); + expect_eq(drv->telemetry().borrowed_buffer_bytes, std::size_t{0}); +} + +Void::Testing::Test io_file_eintr_retried_via_shim() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.eintr_pwrite.store(1); + sys.eintr_pread.store(2); + sys.eintr_sync.store(1); + sys.eintr_close.store(true); + std::optional w; + std::optional r; + std::optional s; + std::optional c; + std::array rbuf{}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options({}, &sys)); + file = open_rw(*drv, dir.file("eintr.bin")); + spawn(scope, do_write(&file, 0, as_bytes("eintr"), {}, &w)); + spawn(scope, do_sync(&file, SyncMode::full, {}, &s)); + spawn(scope, do_read(&file, 0, rbuf, {}, &r)); + (void)exec.drain(); + auto ran = drv->run_file_work(3); + require(ran.has_value()); + expect_eq(*ran, std::size_t{3}); + require(drv->poll_once().has_value()); + (void)exec.drain(); + require(w.has_value() && w->has_value()); + expect_eq((*w)->bytes, std::size_t{5}); + expect(s.has_value() && s->has_value()); + require(r.has_value() && r->has_value()); + expect_eq(as_string(rbuf), std::string{"eintr"}); + expect_eq(sys.pwrites.load(), 2); + expect_eq(sys.syncs.load(), 2); + expect_eq(sys.preads.load(), 3); + + // close(2) is never retried: EINTR still releases the descriptor. + spawn(scope, do_close(&file, {}, &c)); + (void)exec.drain(); + require(drv->run_file_work(1).has_value()); + require(drv->poll_once().has_value()); + (void)exec.drain(); + require(c.has_value()); + expect(c->has_value()); + expect_eq(sys.closes.load(), 1); + expect_eq(drv->telemetry().active_descriptors, std::size_t{0}); + } + expect_eq(sys.closes.load(), 1); +} + +Void::Testing::Test io_file_zero_length_overflow_and_zero_queue_limit() +{ + ManualExecutor exec; + { + auto bad = Driver::create(exec, mock_options(IoLimits{.max_file_queue = 0})); + require(!bad.has_value()); + expect(io_code(bad.error(), IoErrorCode::invalid_argument)); + expect(failed_with(Void::IO::validate_limits(IoLimits{.max_file_queue = 0}), + IoErrorCode::invalid_argument)); + } + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + std::optional zr; + std::optional zw; + std::optional ov1; + std::optional ov2; + std::optional edge; + std::array one{}; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options({}, &sys)); + file = open_rw(*drv, dir.file("edges.bin")); + const auto off_max = static_cast(std::numeric_limits::max()); + spawn(scope, do_read(&file, 0, {}, {}, &zr)); + spawn(scope, do_write(&file, 0, {}, {}, &zw)); + spawn(scope, do_read(&file, std::numeric_limits::max(), one, {}, &ov1)); + spawn(scope, do_write(&file, off_max, as_bytes("x"), {}, &ov2)); + spawn(scope, do_read(&file, off_max - 1, one, {}, &edge)); // offset+len == OFF_MAX is valid + (void)exec.drain(); + require(zr.has_value() && zr->has_value()); + expect((**zr) == (Transfer{0, false})); + require(zw.has_value() && zw->has_value()); + expect((**zw) == (Transfer{0, false})); + expect(failed_with(ov1, IoErrorCode::invalid_argument)); + expect(failed_with(ov2, IoErrorCode::invalid_argument)); + expect(!edge.has_value()); + expect_eq(drv->telemetry().queued_file_requests, std::size_t{1}); + require(drv->run_file_work(1).has_value()); + require(drv->poll_once().has_value()); + (void)exec.drain(); + require(edge.has_value()); + if (edge->has_value()) { + expect((*edge)->eof); + } else { + expect(io_code(edge->error(), IoErrorCode::os_error)); + } + expect_eq(sys.preads.load(), 1); + expect_eq(sys.pwrites.load(), 0); + expect(failed_with(drv->adopt_file_fd(-1), IoErrorCode::invalid_argument)); + } +} + +Void::Testing::Test io_file_counts_against_max_descriptors() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + std::optional c; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.max_descriptors = 2})); + auto stream = drv->create_mock_stream(); + require(stream.has_value()); + file = open_rw(*drv, dir.file("first.bin")); + expect_eq(drv->telemetry().active_descriptors, std::size_t{2}); + expect(file.id().valid()); + expect(!(file.id() == stream->id())); + + // The slot is reserved before open(2), so a rejected open creates nothing. + const auto third = dir.file("third.bin"); + expect(failed_with(drv->open_file(third, FileOpenOptions{.write = true, .create = true}), + IoErrorCode::overloaded)); + expect(!std::filesystem::exists(third)); + + // adopt_file_fd takes ownership only on success. + const int fd = ::open(dir.file("first.bin").c_str(), O_RDONLY | O_CLOEXEC); + require(fd >= 0); + expect(failed_with(drv->adopt_file_fd(fd), IoErrorCode::overloaded)); + expect(::fcntl(fd, F_GETFD) != -1); + + spawn(scope, do_close(&file, {}, &c)); + (void)exec.drain(); + require(drv->run_file_work(1).has_value()); + require(drv->poll_once().has_value()); + (void)exec.drain(); + require(c.has_value() && c->has_value()); + expect_eq(drv->telemetry().active_descriptors, std::size_t{1}); + + auto adopted = drv->adopt_file_fd(fd); + require(adopted.has_value()); + expect_eq(drv->telemetry().active_descriptors, std::size_t{2}); + } +} + +Void::Testing::Test io_file_workers_second_start_invalid() +{ + ManualExecutor exec; + { + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 2})); + require(drv->start_file_workers().has_value()); + expect_eq(drv->telemetry().file_workers_running, std::size_t{2}); + expect(failed_with(drv->start_file_workers(), IoErrorCode::invalid_argument)); + expect_eq(drv->telemetry().file_workers_running, std::size_t{2}); + } + { + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 0})); + require(drv->start_file_workers().has_value()); + expect_eq(drv->telemetry().file_workers_running, std::size_t{0}); + expect(failed_with(drv->start_file_workers(), IoErrorCode::invalid_argument)); + expect(drv->run_file_work(1).has_value()); + } + { + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 2})); + drv->begin_shutdown(); + expect(failed_with(drv->start_file_workers(), IoErrorCode::closed)); + expect_eq(drv->telemetry().file_workers_running, std::size_t{0}); + } +} + +Void::Testing::Test io_poll_once_after_shutdown_returns_zero() +{ + ManualExecutor exec; + for (const auto pref : {BackendPreference::epoll, BackendPreference::mock}) { + auto drv = make_driver(exec, BackendOptions{.preference = pref}); + require(drv->shutdown_and_join().has_value()); + expect(drv->shutdown_complete()); + expect(drv->quiescent()); + const auto before = drv->telemetry(); + auto r0 = drv->poll_once(std::chrono::nanoseconds{0}); + require(r0.has_value()); + expect_eq(*r0, std::size_t{0}); + const auto start = std::chrono::steady_clock::now(); + auto rinf = drv->poll_once(std::nullopt); // must not block + require(rinf.has_value()); + expect_eq(*rinf, std::size_t{0}); + expect(std::chrono::steady_clock::now() - start < 1s); + if (pref == BackendPreference::epoll) { + drv->wake(); // F2: a no-op once shut down + } + const auto after = drv->telemetry(); + expect_eq(after.turns, before.turns); + expect_eq(after.wakeups, before.wakeups); + // Repeatable and idempotent. + auto again = drv->shutdown(OperationOptions{}); + require(again.has_value()); + expect(again->complete); + expect(drv->shutdown_and_join().has_value()); + } +} + +Void::Testing::Test io_poll_once_reentrant_inline_resume_busy() +{ + InlineExecutor inline_exec; + ManualExecutor other_exec; + auto drv = make_driver(inline_exec, mock_options()); + auto other = make_driver(other_exec, mock_options()); + auto st = drv->create_mock_stream(); + require(st.has_value()); + ByteStream stream = std::move(*st); + + struct Seen { + bool reentrant_busy{false}; + bool shutdown_self_join{false}; + bool join_self_join{false}; + bool other_driver_polled{false}; + std::optional res; + } seen; + std::stop_source src; + std::array buf{}; + auto body = [](ByteStream* s, std::span b, std::stop_token tok, Driver* d, + Driver* o, Seen* out) -> Void::Coro::Task { + out->res = co_await s->read_some(b, OperationOptions{.stop = tok}); + // Resumed inline inside d's poll turn. + auto again = d->poll_once(); + out->reentrant_busy = !again.has_value() && io_code(again.error(), IoErrorCode::busy); + auto sd = d->shutdown(OperationOptions{}); + out->shutdown_self_join = !sd.has_value() && is_self_join(sd.error()); + auto sj = d->shutdown_and_join(); + out->join_self_join = !sj.has_value() && is_self_join(sj.error()); + // A nested turn of a different driver is allowed. + out->other_driver_polled = o->poll_once().has_value(); + }; + auto t = body(&stream, buf, src.get_token(), drv.get(), other.get(), &seen); + t.handle().resume(); + src.request_stop(); + require(drv->poll_once().has_value()); + expect(t.done()); + expect(failed_with(seen.res, IoErrorCode::cancelled)); + expect(seen.reentrant_busy); + expect(seen.shutdown_self_join); + expect(seen.join_self_join); + expect(seen.other_driver_polled); + expect(!drv->shutdown_complete()); + expect_eq(drv->telemetry().turns, std::uint64_t{1}); +} + +Void::Testing::Test io_shutdown_bounded_deadline_incomplete_then_complete() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_pwrite.store(true); + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{30}}}; + std::optional w; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 1}, &sys), clock); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, dir.file("bounded.bin")); + spawn(scope, do_write(&file, 0, as_bytes("bounded!"), {}, &w)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + + auto r1 = drv->shutdown(OperationOptions{.deadline = clock.now()}); + require(r1.has_value()); + expect(!r1->complete); + expect_eq(r1->active_file_requests, std::size_t{1}); + expect_eq(r1->pending_operations, std::size_t{1}); + expect_eq(r1->open_descriptors, std::size_t{1}); + expect_eq(r1->retained_buffer_bytes, std::size_t{8}); + expect(!drv->shutdown_complete()); + expect_eq(drv->telemetry().file_workers_running, std::size_t{1}); + + // A future deadline is judged by the injected clock, re-read per slice. + std::thread advancer([&] { + std::this_thread::sleep_for(20ms); + (void)clock.advance(2s); + }); + auto r2 = drv->shutdown(OperationOptions{.deadline = clock.now() + 1s}); + advancer.join(); + require(r2.has_value()); + expect(!r2->complete); + expect(!w.has_value()); + + sys.gate.open(); + auto r3 = drv->shutdown(OperationOptions{}); + require(r3.has_value()); + expect(r3->complete); + expect_eq(r3->pending_operations, std::size_t{0}); + expect_eq(r3->active_file_requests, std::size_t{0}); + expect_eq(r3->open_descriptors, std::size_t{0}); + expect_eq(r3->retained_buffer_bytes, std::size_t{0}); + (void)exec.drain(); + require(w.has_value() && w->has_value()); + expect_eq((*w)->bytes, std::size_t{8}); + expect(drv->quiescent()); + } +} + +Void::Testing::Test io_shutdown_stop_token_returns_incomplete_report() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + sys.gate_sync.store(true); + std::optional s; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, epoll_options(IoLimits{.file_workers = 1}, &sys)); + GateOpener opener{sys.gate}; + require(drv->start_file_workers().has_value()); + file = open_rw(*drv, dir.file("stop_token.bin")); + spawn(scope, do_sync(&file, SyncMode::full, {}, &s)); + (void)exec.drain(); + require(sys.gate.wait_for_waiters(1)); + + std::stop_source pre; + pre.request_stop(); + auto r1 = drv->shutdown(OperationOptions{.stop = pre.get_token()}); + require(r1.has_value()); + expect(!r1->complete); + expect_eq(r1->active_file_requests, std::size_t{1}); + + std::stop_source later; + std::thread stopper([&] { + std::this_thread::sleep_for(20ms); + later.request_stop(); + }); + auto r2 = drv->shutdown(OperationOptions{.stop = later.get_token()}); + stopper.join(); + require(r2.has_value()); + expect(!r2->complete); + expect(!s.has_value()); + + sys.gate.open(); + auto r3 = drv->shutdown(OperationOptions{}); + require(r3.has_value()); + expect(r3->complete); + (void)exec.drain(); + require(s.has_value()); + expect(s->has_value()); // the active sync's real outcome + } +} + +Void::Testing::Test io_request_stop_then_shutdown_cancels_queued_files() +{ + ManualExecutor exec; + TempDir dir; + require(dir.valid()); + TestSyscalls sys; + const auto path = dir.file("request_stop.bin"); + write_file(path, "keep"); + std::array, 3> w{}; + std::optional s; + std::optional late; + File file; + { + TaskScope scope{exec}; + auto drv = make_driver(exec, mock_options(IoLimits{.file_workers = 2}, &sys)); + file = open_rw(*drv, path); + for (std::size_t i = 0; i < w.size(); ++i) { + spawn(scope, do_write(&file, i, as_bytes("Z"), {}, &w[i])); + } + spawn(scope, do_sync(&file, SyncMode::full, {}, &s)); + (void)exec.drain(); + expect_eq(drv->telemetry().queued_file_requests, std::size_t{4}); + + drv->request_stop(); // == begin_shutdown() + expect_eq(drv->telemetry().queued_file_requests, std::size_t{0}); + spawn(scope, do_write(&file, 0, as_bytes("late"), {}, &late)); + (void)exec.drain(); + expect(failed_with(late, IoErrorCode::closed)); + expect(failed_with(drv->start_file_workers(), IoErrorCode::closed)); + + require(drv->poll_once().has_value()); + (void)exec.drain(); + for (const auto& r : w) { + expect(failed_with(r, IoErrorCode::cancelled)); + } + expect(failed_with(s, IoErrorCode::cancelled)); + require(drv->shutdown_and_join().has_value()); + expect(drv->quiescent()); + } + expect_eq(sys.pwrites.load() + sys.syncs.load(), 0); + expect_eq(sys.closes.load(), 1); + expect_eq(read_file(path), std::string{"keep"}); +} + +Void::Testing::Test io_mock_held_request_does_not_block_teardown() +{ + ManualExecutor exec; + std::array b1{}; + std::array b2{}; + std::optional r1; + std::optional r2; + TaskScope scope{exec}; + { + auto drv = make_driver(exec, mock_options()); + auto* ctrl = drv->mock_controller(); + require(ctrl != nullptr); + auto s1 = drv->create_mock_stream(); + auto s2 = drv->create_mock_stream(); + require(s1.has_value() && s2.has_value()); + spawn(scope, do_stream_read(&*s1, b1, {}, &r1)); + spawn(scope, do_stream_read(&*s2, b2, {}, &r2)); + (void)exec.drain(); + const auto t1 = ctrl->try_acquire_read(*s1); + const auto t2 = ctrl->try_acquire_read(*s2); + require(t1.has_value() && t2.has_value()); + + // Held requests never block advance_shutdown. + auto report = drv->shutdown(OperationOptions{}); + require(report.has_value()); + expect(report->complete); + expect_eq(report->pending_operations, std::size_t{2}); + expect(!r1.has_value()); + + // finish_* still completes a held request after shutdown. + expect(ctrl->finish_read_data(*t1, as_bytes("held"), false)); + (void)exec.drain(); + require(r1.has_value() && r1->has_value()); + expect_eq((*r1)->bytes, std::size_t{4}); + expect(!r2.has_value()); + } // teardown completes the still-held request with closed + (void)exec.drain(); + expect(failed_with(r2, IoErrorCode::closed)); + require(scope.join_pumping(exec).has_value()); +}