#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()); }