From 9918ed476090b7d771dcc9b9456cc2ac150b0855 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:57:29 +0300 Subject: [PATCH 1/5] docs(workflow): add Wave 4B (P1 IO, Runtime, Testing) task specs --- docs/agent-workflow/tasks/M-TESTING-02-03.md | 38 ++++++++++++++++++++ docs/agent-workflow/tasks/S-IO-01-02.md | 37 +++++++++++++++++++ docs/agent-workflow/tasks/S-RUNTIME-01.md | 35 ++++++++++++++++++ 3 files changed, 110 insertions(+) create mode 100644 docs/agent-workflow/tasks/M-TESTING-02-03.md create mode 100644 docs/agent-workflow/tasks/S-IO-01-02.md create mode 100644 docs/agent-workflow/tasks/S-RUNTIME-01.md diff --git a/docs/agent-workflow/tasks/M-TESTING-02-03.md b/docs/agent-workflow/tasks/M-TESTING-02-03.md new file mode 100644 index 0000000..6cb2636 --- /dev/null +++ b/docs/agent-workflow/tasks/M-TESTING-02-03.md @@ -0,0 +1,38 @@ +# Testing Per-Run Reporters, Subprocess Isolation, and Deterministic Harness +Task ID: M-TESTING-02, M-TESTING-03 +Phase: P1 +Status: APPROVED +Contracts: C-01, C-04, C-16 + +## 1. Context and baseline +`Testing` (`Runner.cpp`, `Assert.cpp`, `Config.hpp`, `JUnitReporter.cpp`) currently uses a process-global static `std::ofstream` for JUnit reporting, silently turns malformed regex or empty explicit filter selections into passing 0-test runs, retains unbounded per-test assertions, and lacks owned `FailureCapture`, isolated subprocess test execution, versioned deterministic property shrinking, and clock/order-controlled `DeterministicRun`. + +## 2. Deliverables +- Updated `include/Void/Testing/{Config,Assert,Runner}.hpp` and `src/Testing/{Assert,Runner}.cpp`: + - Per-run owned JUnit stream checking open/write health cleanly. + - Strict CLI/config validation (invalid regex, unknown reporter, unopenable output path, empty selection without `--allow-empty` fail with exit code 2). + - Bounded per-test assertion retention (`1000` assertions / `1 MiB` diagnostics) and stray-assertion counter. + - Single-teardown fixture lifecycle recording teardown errors in `cleanup_error` without masking primary test failure. + - `--selftest-child ` fixtures inside `Runner::main`. +- New `include/Void/Testing/Capture.hpp` (`FailureCapture`) and `include/Void/Testing/{Subprocess.hpp}` + `src/Testing/Subprocess.cpp` (`current_executable_path`, `run_isolated_subprocess`, `ProcessTestOptions`, `ProcessOutcome`, `ProcessTestResult`). +- New `include/Void/Testing/Deterministic.hpp` (`ReplayToken`, version-1 rejection-mapped `DeterministicRng`, `check_property` with shrinking & budget-exhaustion `inconclusive`, and `DeterministicRun` schedule/clock/timer harness). +- Tests in `tests/standalone/Testing/{FrameworkHardening,Deterministic}.cpp`. + +## 3. Exact files and interfaces +- `include/Void/Testing/{Config,Assert,Runner,Capture,Subprocess,Deterministic}.hpp` +- `src/Testing/{Assert,Runner,Subprocess}.cpp` +- `tests/standalone/Testing/{FrameworkHardening,Deterministic}.cpp` + +## 4. Edge cases +- Child process `flood` saturating stdout and stderr concurrently drains via non-blocking `poll` with bounded truncation without pipe deadlock. +- Child process `hang` beyond `ProcessTestOptions::timeout` terminates via `SIGKILL` and reports `ProcessOutcome::timed_out`. +- Child process `abort` reports `ProcessOutcome::crashed` (`SIGABRT`) safely even under ASan/UBSan. +- Property shrinking preserves counterexample failure category and reports `inconclusive` on step, time, or discard exhaustion. + +## 5. Acceptance criteria +- `FrameworkHardening*|Deterministic*|Math*|ContainerFixture*|StructRepr*` and full 1,345+ `VoidTests` pass under RelWithDebInfo `-Werror` and ASan+UBSan. + +## 6. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4b-testing -G Ninja -DVOID_ENABLED_MODULES="Core;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4b-testing && /tmp/void-w4b-testing/tests/VoidTests --filter "FrameworkHardening*|Deterministic*|Math*|ContainerFixture*|StructRepr*" && ctest --test-dir /tmp/void-w4b-testing --output-on-failure --timeout 60' +``` \ No newline at end of file diff --git a/docs/agent-workflow/tasks/S-IO-01-02.md b/docs/agent-workflow/tasks/S-IO-01-02.md new file mode 100644 index 0000000..843a55b --- /dev/null +++ b/docs/agent-workflow/tasks/S-IO-01-02.md @@ -0,0 +1,37 @@ +# IO Portable Driver, BufferLease, Mock Backend, and Linux Epoll Driver +Task ID: S-IO-01, S-IO-02 +Phase: P1 +Status: APPROVED +Contracts: C-01, C-02, C-03, C-04, C-06 + +## 1. Context and baseline +VoidLibrary currently has no `IO` module (`src/IO/`, `include/Void/IO/`). Now that `Async` (`M-ASYNC-02`, `M-ASYNC-03`) and `Time` (`M-TIME-02`) are in place, `IO` can expose a dependency-minimal native descriptor/stream layer (`INTERNAL_DEPS Core Functional Time Memory Async`) with zero dependency on `Net`, `Runtime`, `System`, or `Log`. + +## 2. Deliverables +- `src/IO/module.cmake` (`INTERNAL_DEPS Core Functional Time Memory Async`). +- `include/Void/IO/Types.hpp`: `IoErrorCode` (`kIoErrorDomain = 8`), `make_io_error`, `Transfer`, `ComposedTransferError`, `IoLimits`, `BackendPreference`, `BackendOptions`, `DescriptorId`, `DriverTelemetry`, and PMR/quota-tracked `BufferLease`. +- `include/Void/IO/Driver.hpp`, `include/Void/IO/Stream.hpp`, `src/IO/EpollDriver.cpp`: + - `Driver` (`create`, `allocate_buffer`, `create_mock_stream`, `mock_controller`, `adopt_fd`, `create_socket_pair`, `poll_once`, `wake`, `request_stop`, `shutdown_and_join`, `telemetry`, `active_backend`). + - `ByteStream` (`read_some`, `write_some`, `read_some_owned`, `write_some_owned`, `close_and_join`) plus composed `read_exact` / `write_all`. + - Portable `MockBackend` for deterministic concurrency/stop-race verification and Linux level-triggered `EpollBackend` (no `EPOLLET`, `eventfd` wakeups, `(slot, generation)` tokens). +- `tests/standalone/IO/IoDriver.cpp` and installed package consumer `tests/package/IOOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake`. + +## 3. Exact files and interfaces +- `src/IO/module.cmake`, `src/IO/EpollDriver.cpp` +- `include/Void/IO/{Types,Driver,Stream}.hpp` +- `tests/standalone/IO/IoDriver.cpp` +- `tests/package/IOOnly/{CMakeLists.txt,main.cpp}`, `tests/package/InstalledComponents.cmake` + +## 4. Edge cases +- Zero-length `read_some`/`write_some` succeeds immediately (`Transfer{0, false}`) without probing EOF. +- Same-direction overlapping operation on a stream rejects with `IoErrorCode::busy`; simultaneous `read_some` + `write_some` succeeds. +- Pre-stopped options or expired injected `MonotonicClock` deadline rejected before backend submission; active ops never resume continuations while backend holds `backend_refs` or borrowed buffers. +- Linux epoll level-triggered handling handles `EAGAIN`/`EINTR`/short transfers, drains buffered data before `EOF`/`HUP`, ignores stale `(slot, generation)` events after fd reuse, and keeps `EPOLLOUT` disabled when no write is pending. + +## 5. Acceptance criteria +- `Io*` tests and `VoidInstalledComponentConsumers` (`IOOnly`) pass under `-DVOID_WARNINGS_AS_ERRORS=ON`, ASan+UBSan, and Debug TSan (`-DVOID_ENABLE_TSAN=ON`). + +## 6. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4b-io -G Ninja -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4b-io && /tmp/void-w4b-io/tests/VoidTests --filter "Io*" && ctest --test-dir /tmp/void-w4b-io --output-on-failure --timeout 60' +``` \ No newline at end of file diff --git a/docs/agent-workflow/tasks/S-RUNTIME-01.md b/docs/agent-workflow/tasks/S-RUNTIME-01.md new file mode 100644 index 0000000..b33feea --- /dev/null +++ b/docs/agent-workflow/tasks/S-RUNTIME-01.md @@ -0,0 +1,35 @@ +# Runtime Inert Host, Validated Limits, EmbeddedResources, and ResourceGraph +Task ID: S-RUNTIME-01 +Phase: P1 +Status: APPROVED +Contracts: C-01, C-04, C-05, C-09 + +## 1. Context and baseline +VoidLibrary currently has no `Runtime` module (`src/Runtime/`, `include/Void/Runtime/`). P1 establishes the inert managed composition contracts on top of `Core`, `Functional`, `Time`, `Memory`, `Algorithms`, `Async`, and `IO` without implicitly starting worker threads or depending on `System`, `Net`, `Service`, or `Log`. + +## 2. Deliverables +- `src/Runtime/module.cmake` (`INTERNAL_DEPS Core Functional Time Memory Algorithms Async IO`). +- `include/Void/Runtime/Options.hpp`: `kRuntimeErrorDomain = 11`, `RuntimeLimits`, `ShutdownPolicy`, `Options`, `validate_options`. +- `include/Void/Runtime/ResourceGraph.hpp`: `ResourceOwnership`, `ResourceKind`, `ResourceNode`, `LifecyclePlan`, and `ResourceGraph` (`add_node`, `add_dependency`, `validate_and_plan` via `Void::Algorithms::topological_order`). +- `include/Void/Runtime/Host.hpp`: `HostState`, `EmbeddedResources`, `ShutdownReport`, inert `Host` (`create`, `create_embedded`), and `HostBuilder`. +- `tests/standalone/Runtime/RuntimeHost.cpp` and installed consumer `tests/package/RuntimeOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake`. + +## 3. Exact files and interfaces +- `src/Runtime/module.cmake` +- `include/Void/Runtime/{Options,ResourceGraph,Host}.hpp` +- `tests/standalone/Runtime/RuntimeHost.cpp` +- `tests/package/RuntimeOnly/{CMakeLists.txt,main.cpp}`, `tests/package/InstalledComponents.cmake` + +## 4. Edge cases +- `Host::create()` starts zero worker threads and opens zero OS descriptors (`HostState::constructed`). +- Zero worker counts in non-embedded mode, zero limits, `drain_grace > total_timeout`, and submodule `IO::BackendOptions::limits` exceeding global `RuntimeLimits` reject before construction. +- `EmbeddedResources::validate()` rejects null required ports (`executor`, `io`, `clock`). +- `ResourceGraph::validate_and_plan()` catches duplicate node IDs, missing required dependencies, and dependency cycles (preserving cycle witness) while producing deterministic startup order and exact reverse shutdown order. + +## 5. Acceptance criteria +- `Runtime*` tests and `VoidInstalledComponentConsumers` (`RuntimeOnly`) pass under `-DVOID_WARNINGS_AS_ERRORS=ON` and ASan+UBSan. + +## 6. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4b-runtime -G Ninja -DVOID_ENABLED_MODULES="Runtime;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4b-runtime && /tmp/void-w4b-runtime/tests/VoidTests --filter "Runtime*" && ctest --test-dir /tmp/void-w4b-runtime --output-on-failure --timeout 60' +``` \ No newline at end of file From 673bb7e8b4777e80ce85fbb4173c50c85459929e Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 09:31:13 +0300 Subject: [PATCH 2/5] feat(IO): add portable Driver/ByteStream/BufferLease, mock backend, and Linux epoll driver (S-IO-01, S-IO-02) --- include/Void/IO/Detail/Backend.hpp | 119 ++ include/Void/IO/Driver.hpp | 107 ++ include/Void/IO/Stream.hpp | 182 +++ include/Void/IO/Types.hpp | 292 ++++ src/IO/EpollDriver.cpp | 1809 +++++++++++++++++++++++ src/IO/module.cmake | 3 + tests/package/IOOnly/CMakeLists.txt | 10 + tests/package/IOOnly/main.cpp | 35 + tests/package/InstalledComponents.cmake | 5 + tests/standalone/IO/IoDriver.cpp | 509 +++++++ 10 files changed, 3071 insertions(+) create mode 100644 include/Void/IO/Detail/Backend.hpp create mode 100644 include/Void/IO/Driver.hpp create mode 100644 include/Void/IO/Stream.hpp create mode 100644 include/Void/IO/Types.hpp create mode 100644 src/IO/EpollDriver.cpp create mode 100644 src/IO/module.cmake create mode 100644 tests/package/IOOnly/CMakeLists.txt create mode 100644 tests/package/IOOnly/main.cpp create mode 100644 tests/standalone/IO/IoDriver.cpp diff --git a/include/Void/IO/Detail/Backend.hpp b/include/Void/IO/Detail/Backend.hpp new file mode 100644 index 0000000..2249ec2 --- /dev/null +++ b/include/Void/IO/Detail/Backend.hpp @@ -0,0 +1,119 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IO +{ + +class ByteStream; + +namespace detail +{ + +class StreamState; + +enum class Direction { + read, + write +}; + +class DriverBackend : public std::enable_shared_from_this +{ +public: + virtual ~DriverBackend() = default; + + [[nodiscard]] virtual BackendPreference kind() const noexcept = 0; + [[nodiscard]] virtual const IoLimits& limits() const noexcept = 0; + [[nodiscard]] virtual const Void::Time::MonotonicClock& clock() const noexcept = 0; + [[nodiscard]] virtual Async::Executor& executor() noexcept = 0; + + [[nodiscard]] virtual Void::Result::Result> + create_mock_stream() = 0; + + [[nodiscard]] virtual Void::Result::Result> + adopt_fd(int fd) = 0; + + [[nodiscard]] virtual Void::Result::Result< + std::pair, std::shared_ptr>> + create_socket_pair() = 0; + + [[nodiscard]] virtual Void::Result::Result>> + submit_read(const std::shared_ptr& stream, + std::span buf, + Async::OperationOptions options) = 0; + + [[nodiscard]] virtual Void::Result::Result>> + submit_write(const std::shared_ptr& stream, + std::span buf, + Async::OperationOptions options) = 0; + + [[nodiscard]] virtual Void::Result::Result>> + submit_close(const std::shared_ptr& stream, + Async::OperationOptions options) = 0; + + virtual void on_stream_destroyed(const DescriptorId& id) noexcept = 0; + + [[nodiscard]] virtual Void::Result::Result + poll_once(std::optional max_wait) = 0; + + virtual void wake() noexcept = 0; + virtual void request_stop() noexcept = 0; + [[nodiscard]] virtual Void::Result::Result shutdown_and_join() = 0; + [[nodiscard]] virtual DriverTelemetry telemetry() const noexcept = 0; + + // Mock inspection / test-only control hooks (returns nullptr on non-mock backends). + [[nodiscard]] virtual class MockBackend* as_mock() noexcept { return nullptr; } +}; + +class StreamState +{ +public: + StreamState(std::weak_ptr backend, DescriptorId id) noexcept + : backend_(std::move(backend)) + , id_(id) + { + } + + ~StreamState() + { + if (!explicitly_closed_.load(std::memory_order_acquire)) { + if (auto b = backend_.lock()) { + b->on_stream_destroyed(id_); + } + } + } + + StreamState(const StreamState&) = delete; + StreamState& operator=(const StreamState&) = delete; + + [[nodiscard]] DescriptorId id() const noexcept { return id_; } + [[nodiscard]] std::shared_ptr lock_backend() const noexcept + { + return backend_.lock(); + } + + void mark_explicit_closed() noexcept + { + explicitly_closed_.store(true, std::memory_order_release); + } + +private: + std::weak_ptr backend_{}; + DescriptorId id_{}; + std::atomic explicitly_closed_{false}; +}; + +} // namespace detail +} // namespace Void::IO \ No newline at end of file diff --git a/include/Void/IO/Driver.hpp b/include/Void/IO/Driver.hpp new file mode 100644 index 0000000..e2986aa --- /dev/null +++ b/include/Void/IO/Driver.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IO +{ + +class MockController +{ +public: + explicit MockController(detail::MockBackend* backend) noexcept + : backend_(backend) + { + } + + [[nodiscard]] std::size_t pending_read_count(const ByteStream& stream) const noexcept; + [[nodiscard]] std::size_t pending_write_count(const ByteStream& stream) const noexcept; + + [[nodiscard]] std::optional + try_acquire_read(const ByteStream& stream); + [[nodiscard]] std::optional + try_acquire_write(const ByteStream& stream); + + [[nodiscard]] bool is_stop_requested(std::uint64_t token) const noexcept; + [[nodiscard]] std::size_t requested_size(std::uint64_t token) const noexcept; + + bool finish_read_data(std::uint64_t token, + std::span data, + bool eof = false); + bool finish_write_bytes(std::uint64_t token, std::size_t bytes); + bool finish_error(std::uint64_t token, Void::Result::Error err); + bool finish_cancelled(std::uint64_t token, std::string msg = "Operation cancelled"); + + bool complete_read(const ByteStream& stream, + std::span data, + bool eof = false); + bool complete_write(const ByteStream& stream, std::size_t bytes); + bool fail_read(const ByteStream& stream, Void::Result::Error err); + bool fail_write(const ByteStream& stream, Void::Result::Error err); + +private: + detail::MockBackend* backend_{nullptr}; +}; + +class Driver +{ +public: + ~Driver(); + + Driver(const Driver&) = delete; + Driver& operator=(const Driver&) = delete; + Driver(Driver&&) = delete; + Driver& operator=(Driver&&) = delete; + + [[nodiscard]] static Void::Result::Result> create( + Async::Executor& executor, + BackendOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance(), + std::pmr::memory_resource* resource = std::pmr::get_default_resource()); + + [[nodiscard]] BackendPreference active_backend() const noexcept; + [[nodiscard]] const IoLimits& limits() const noexcept; + [[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept; + [[nodiscard]] Async::Executor& executor() noexcept; + [[nodiscard]] DriverTelemetry telemetry() const noexcept; + + [[nodiscard]] Void::Result::Result allocate_buffer(std::size_t bytes); + + [[nodiscard]] Void::Result::Result create_mock_stream(); + [[nodiscard]] MockController* mock_controller() noexcept; + + [[nodiscard]] Void::Result::Result adopt_fd(int fd); + [[nodiscard]] Void::Result::Result> + create_socket_pair(); + + [[nodiscard]] Void::Result::Result poll_once( + std::optional max_wait = std::chrono::nanoseconds{0}); + + void wake() noexcept; + void request_stop() noexcept; + [[nodiscard]] Void::Result::Result shutdown_and_join(); + +private: + Driver(std::shared_ptr backend, + std::shared_ptr buffer_tracker) noexcept; + + std::shared_ptr backend_{}; + std::shared_ptr buffer_tracker_{}; + std::unique_ptr mock_controller_{}; +}; + +} // namespace Void::IO \ No newline at end of file diff --git a/include/Void/IO/Stream.hpp b/include/Void/IO/Stream.hpp new file mode 100644 index 0000000..b49ea63 --- /dev/null +++ b/include/Void/IO/Stream.hpp @@ -0,0 +1,182 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::IO +{ + +class ByteStream +{ +public: + ByteStream() noexcept = default; + + explicit ByteStream(std::shared_ptr state) noexcept + : state_(std::move(state)) + { + } + + ByteStream(ByteStream&&) noexcept = default; + ByteStream& operator=(ByteStream&&) noexcept = default; + ByteStream(const ByteStream&) = delete; + ByteStream& operator=(const ByteStream&) = delete; + + [[nodiscard]] bool valid() const noexcept { return state_ != nullptr; } + + [[nodiscard]] DescriptorId id() const noexcept + { + return state_ ? state_->id() : DescriptorId{}; + } + + [[nodiscard]] Coro::Task> read_some( + std::span buf, Async::OperationOptions options = {}) + { + if (buf.empty()) { + co_return Transfer{0, false}; + } + auto state = state_; + if (!state) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "ByteStream is closed or moved-from")}; + } + auto backend = state->lock_backend(); + if (!backend) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver no longer alive")}; + } + auto submitted = backend->submit_read(state, 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()); + } + + [[nodiscard]] Coro::Task> write_some( + std::span buf, Async::OperationOptions options = {}) + { + if (buf.empty()) { + co_return Transfer{0, false}; + } + auto state = state_; + if (!state) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "ByteStream is closed or moved-from")}; + } + auto backend = state->lock_backend(); + if (!backend) { + co_return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver no longer alive")}; + } + auto submitted = backend->submit_write(state, 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()); + } + + [[nodiscard]] Coro::Task> read_some_owned( + BufferLease& lease, Async::OperationOptions options = {}) + { + auto res = co_await read_some(lease.writable(), std::move(options)); + if (res.has_value()) { + lease.set_valid_bytes(res->bytes); + } + co_return res; + } + + [[nodiscard]] Coro::Task> write_some_owned( + const BufferLease& lease, Async::OperationOptions options = {}) + { + co_return co_await write_some(lease.readable(), std::move(options)); + } + + [[nodiscard]] Coro::Task> close_and_join( + Async::OperationOptions options = {}) + { + auto state = std::move(state_); + if (!state) { + co_return {}; + } + state->mark_explicit_closed(); + auto backend = state->lock_backend(); + if (!backend) { + co_return {}; + } + auto submitted = backend->submit_close(state, 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()); + } + +private: + std::shared_ptr state_{}; +}; + +[[nodiscard]] inline Coro::Task> + read_exact(ByteStream& stream, + 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 stopped before completion")}}; + } + const auto chunk = co_await stream.read_some(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 finished")}}; + } + } + co_return total; +} + +[[nodiscard]] inline Coro::Task> + write_all(ByteStream& stream, + 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 stopped before completion")}}; + } + const auto chunk = co_await stream.write_some(buf.subspan(total), options); + if (!chunk.has_value()) { + co_return std::unexpected{ComposedTransferError{ + total, + false, + chunk.error()}}; + } + total += chunk->bytes; + } + co_return total; +} + +} // namespace Void::IO \ No newline at end of file diff --git a/include/Void/IO/Types.hpp b/include/Void/IO/Types.hpp new file mode 100644 index 0000000..ddd82cf --- /dev/null +++ b/include/Void/IO/Types.hpp @@ -0,0 +1,292 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::IO +{ + +enum class IoErrorCode : std::int32_t { + none = 0, + busy = 1, + closed = 2, + cancelled = 3, + timeout = 4, + overloaded = 5, + unsupported = 6, + eof = 7, + invalid_argument = 8, + os_error = 9, + incomplete_shutdown = 10, + exhausted = 11 +}; + +[[nodiscard]] inline Void::Result::Error make_io_error( + IoErrorCode code, + std::string message = {}, + std::error_code sys_err = {}) +{ + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::io; + switch (code) { + case IoErrorCode::none: + kind = ErrorKind::internal; + break; + case IoErrorCode::busy: + case IoErrorCode::incomplete_shutdown: + kind = ErrorKind::conflict; + break; + case IoErrorCode::closed: + case IoErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case IoErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case IoErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case IoErrorCode::unsupported: + kind = ErrorKind::unsupported; + break; + case IoErrorCode::eof: + case IoErrorCode::os_error: + kind = ErrorKind::io; + break; + case IoErrorCode::invalid_argument: + kind = ErrorKind::invalid_argument; + break; + case IoErrorCode::exhausted: + kind = ErrorKind::exhausted; + break; + } + + const ErrorCode domain_code{ + Void::Result::kIoErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code, sys_err}; +} + +struct Transfer { + std::size_t bytes{0}; + bool eof{false}; + + [[nodiscard]] constexpr bool operator==(const Transfer&) const noexcept = default; +}; + +struct ComposedTransferError { + std::size_t bytes_transferred{0}; + bool eof{false}; + Void::Result::Error error{}; +}; + +struct IoLimits { + std::size_t max_descriptors{4096}; + std::size_t max_operations{8192}; + std::size_t max_timers{4096}; + std::size_t max_owned_buffer_bytes{16ULL * 1024ULL * 1024ULL}; + std::size_t max_control_submissions{1024}; + std::size_t max_ready_per_turn{64}; + std::size_t max_bytes_per_turn{65536}; + std::size_t file_workers{4}; + std::size_t max_file_queue{256}; +}; + +[[nodiscard]] inline Void::Result::Result validate_limits(const IoLimits& limits) +{ + if (limits.max_descriptors == 0 || + limits.max_operations == 0 || + limits.max_control_submissions == 0 || + limits.max_ready_per_turn == 0 || + limits.max_bytes_per_turn == 0) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, + "IoLimits descriptor, operation, control, and turn bounds must be non-zero")}; + } + return {}; +} + +enum class BackendPreference { + auto_native, + epoll, + mock +}; + +struct BackendOptions { + IoLimits limits{}; + BackendPreference preference{BackendPreference::auto_native}; +}; + +struct DescriptorId { + std::uint32_t slot{0}; + std::uint32_t generation{0}; + + [[nodiscard]] constexpr bool valid() const noexcept { return generation != 0; } + [[nodiscard]] constexpr bool operator==(const DescriptorId&) const noexcept = default; +}; + +struct DriverTelemetry { + std::size_t active_descriptors{0}; + std::size_t active_operations{0}; + std::size_t owned_buffer_bytes{0}; + std::size_t borrowed_buffer_bytes{0}; + std::uint64_t turns{0}; + std::uint64_t wakeups{0}; + std::uint64_t stale_events_ignored{0}; +}; + +namespace detail +{ +struct OwnedBufferTracker { + explicit OwnedBufferTracker(std::pmr::memory_resource* res, + std::size_t byte_limit) noexcept + : resource(res ? res : std::pmr::get_default_resource()) + , limit(byte_limit) + { + } + + std::pmr::memory_resource* resource{nullptr}; + std::size_t limit{0}; + std::atomic live_bytes{0}; +}; +} // namespace detail + +// Move-only PMR-backed buffer lease carrying shared quota accounting. Safe to +// outlive the Driver as long as the backing memory_resource remains valid. +class BufferLease +{ +public: + BufferLease() noexcept = default; + + ~BufferLease() + { + reset(); + } + + BufferLease(BufferLease&& other) noexcept + : tracker_(std::move(other.tracker_)) + , data_(std::exchange(other.data_, nullptr)) + , capacity_(std::exchange(other.capacity_, 0)) + , valid_bytes_(std::exchange(other.valid_bytes_, 0)) + { + } + + BufferLease& operator=(BufferLease&& other) noexcept + { + if (this != &other) { + reset(); + tracker_ = std::move(other.tracker_); + data_ = std::exchange(other.data_, nullptr); + capacity_ = std::exchange(other.capacity_, 0); + valid_bytes_ = std::exchange(other.valid_bytes_, 0); + } + return *this; + } + + BufferLease(const BufferLease&) = delete; + BufferLease& operator=(const BufferLease&) = delete; + + [[nodiscard]] static Void::Result::Result allocate( + const std::shared_ptr& tracker, + std::size_t bytes) + { + if (!tracker) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "Null OwnedBufferTracker")}; + } + if (bytes == 0) { + BufferLease lease; + lease.tracker_ = tracker; + return lease; + } + + std::size_t cur = tracker->live_bytes.load(std::memory_order_acquire); + for (;;) { + if (bytes > tracker->limit || cur > tracker->limit - bytes) { + return std::unexpected{make_io_error( + IoErrorCode::exhausted, + "Owned IO buffer lease quota exhausted")}; + } + if (tracker->live_bytes.compare_exchange_weak( + cur, + cur + bytes, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + break; + } + } + + void* raw = nullptr; + try { + raw = tracker->resource->allocate(bytes, alignof(std::max_align_t)); + } catch (...) { + tracker->live_bytes.fetch_sub(bytes, std::memory_order_acq_rel); + return std::unexpected{make_io_error( + IoErrorCode::exhausted, + "PMR allocation failed for IO BufferLease")}; + } + + BufferLease lease; + lease.tracker_ = tracker; + lease.data_ = static_cast(raw); + lease.capacity_ = bytes; + lease.valid_bytes_ = bytes; + return lease; + } + + void reset() noexcept + { + if (data_ != nullptr && tracker_) { + tracker_->resource->deallocate(data_, capacity_, alignof(std::max_align_t)); + tracker_->live_bytes.fetch_sub(capacity_, std::memory_order_acq_rel); + } + data_ = nullptr; + capacity_ = 0; + valid_bytes_ = 0; + tracker_.reset(); + } + + [[nodiscard]] explicit operator bool() const noexcept { return tracker_ != nullptr; } + [[nodiscard]] std::size_t size() const noexcept { return capacity_; } + [[nodiscard]] std::size_t valid_bytes() const noexcept { return valid_bytes_; } + [[nodiscard]] bool empty() const noexcept { return capacity_ == 0; } + + void set_valid_bytes(std::size_t n) noexcept + { + valid_bytes_ = std::min(n, capacity_); + } + + [[nodiscard]] std::span writable() noexcept + { + return (data_ != nullptr) ? std::span{data_, capacity_} : std::span{}; + } + + [[nodiscard]] std::span readable() const noexcept + { + return (data_ != nullptr) ? std::span{data_, valid_bytes_} + : std::span{}; + } + +private: + std::shared_ptr tracker_{}; + std::byte* data_{nullptr}; + std::size_t capacity_{0}; + std::size_t valid_bytes_{0}; +}; + +} // namespace Void::IO \ No newline at end of file diff --git a/src/IO/EpollDriver.cpp b/src/IO/EpollDriver.cpp new file mode 100644 index 0000000..38638ab --- /dev/null +++ b/src/IO/EpollDriver.cpp @@ -0,0 +1,1809 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#include +#include +#include +#endif + +namespace Void::IO::detail +{ + +namespace +{ +[[nodiscard]] std::error_code errno_code(int err) noexcept +{ + return std::error_code{err, std::generic_category()}; +} + +void dispatch_tickets(std::vector& tickets) +{ + for (auto& t : tickets) { + t.dispatch(); + } + tickets.clear(); +} +} // namespace + +class BaseBackend; + +struct PendingOp : public std::enable_shared_from_this { + struct CancelForwarder { + std::weak_ptr backend; + std::weak_ptr op; + + void operator()() const noexcept; + }; + + DescriptorId desc_id{}; + Direction dir{Direction::read}; + std::byte* read_ptr{nullptr}; + const std::byte* write_ptr{nullptr}; + std::size_t len{0}; + std::optional deadline{}; + std::shared_ptr> op_state{}; + std::atomic cancel_queued{false}; + bool in_execution{false}; + bool retired{false}; + std::uint64_t mock_token{0}; + // MUST stay LAST: synchronized teardown with external stop callbacks. + std::optional> cancel_cb{}; +}; + +struct CloseWaiter { + std::shared_ptr> op_state{}; +}; + +struct DescriptorSlot { + DescriptorId id{}; + int fd{-1}; + bool in_use{false}; + bool closing{false}; + bool close_enqueued{false}; + bool eof_seen{false}; + bool epoll_registered{false}; + bool epoll_out_armed{false}; + std::shared_ptr active_read{}; + std::shared_ptr active_write{}; + std::vector close_waiters{}; +}; + +class BaseBackend : public DriverBackend +{ +public: + BaseBackend(Async::Executor& executor, + IoLimits limits, + const Void::Time::MonotonicClock& clock, + std::shared_ptr buffer_tracker) + : executor_(executor) + , limits_(limits) + , clock_(clock) + , buffer_tracker_(std::move(buffer_tracker)) + { + } + + [[nodiscard]] const IoLimits& limits() const noexcept override { return limits_; } + [[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept override { return clock_; } + [[nodiscard]] Async::Executor& executor() noexcept override { return executor_; } + + void enqueue_cancel(const std::shared_ptr& op) noexcept + { + if (!op) { + return; + } + if (op->cancel_queued.exchange(true, std::memory_order_acq_rel)) { + return; // Already coalesced once for this operation + } + { + std::lock_guard lk{mu_}; + cancel_queue_.push_back(op); + } + wake(); + } + + [[nodiscard]] Void::Result::Result>> + submit_read(const std::shared_ptr& stream, + std::span buf, + Async::OperationOptions options) override + { + return submit_io( + stream, Direction::read, buf.data(), nullptr, buf.size(), std::move(options)); + } + + [[nodiscard]] Void::Result::Result>> + submit_write(const std::shared_ptr& stream, + std::span buf, + Async::OperationOptions options) override + { + return submit_io( + stream, Direction::write, nullptr, buf.data(), buf.size(), std::move(options)); + } + + [[nodiscard]] Void::Result::Result>> + submit_close(const std::shared_ptr& stream, + Async::OperationOptions options) override + { + auto op = Async::OperationState::create( + options, &executor_, Async::StopBehavior::settle_cancelled); + if (!stream) { + if (auto t = op->try_commit_value(); t.has_value()) { + t->dispatch(); + } + return op; + } + + const DescriptorId did = stream->id(); + bool immediate_complete = false; + bool need_wake = false; + std::vector> to_cancel; + + { + std::lock_guard lk{mu_}; + if (!did.valid() || did.slot >= slots_.size() || + !slots_[did.slot].in_use || + slots_[did.slot].id.generation != did.generation) { + immediate_complete = true; + } else { + auto& slot = slots_[did.slot]; + slot.closing = true; + if (slot.active_read) { + to_cancel.push_back(slot.active_read); + } + if (slot.active_write) { + to_cancel.push_back(slot.active_write); + } + if (kind() == BackendPreference::mock && !slot.active_read && !slot.active_write) { + release_slot_locked(did.slot, false); + immediate_complete = true; + } else { + op->acquire_backend_ref(); + slot.close_waiters.push_back(CloseWaiter{op}); + if (!slot.close_enqueued) { + slot.close_enqueued = true; + enqueue_close_control_locked(did); + need_wake = true; + } + } + } + } + + for (const auto& pop : to_cancel) { + enqueue_cancel(pop); + } + if (need_wake) { + wake(); + } + if (immediate_complete) { + (void)op->try_commit_value(); + } + return op; + } + + void on_stream_destroyed(const DescriptorId& id) noexcept override + { + if (!id.valid()) { + return; + } + std::vector> to_cancel; + bool need_wake = false; + { + std::lock_guard lk{mu_}; + if (id.slot < slots_.size() && + slots_[id.slot].in_use && + slots_[id.slot].id.generation == id.generation) { + auto& slot = slots_[id.slot]; + slot.closing = true; + if (slot.active_read) { + to_cancel.push_back(slot.active_read); + } + if (slot.active_write) { + to_cancel.push_back(slot.active_write); + } + if (!slot.close_enqueued) { + slot.close_enqueued = true; + enqueue_close_control_locked(id); + need_wake = true; + } + } + } + for (const auto& pop : to_cancel) { + pop->op_state->request_stop(); + enqueue_cancel(pop); + } + if (need_wake) { + wake(); + } + } + + void request_stop() noexcept override + { + stopping_.store(true, std::memory_order_release); + wake(); + } + + [[nodiscard]] DriverTelemetry telemetry() const noexcept override + { + DriverTelemetry t; + t.active_descriptors = active_descriptors_.load(std::memory_order_acquire); + t.active_operations = active_operations_.load(std::memory_order_acquire); + t.owned_buffer_bytes = + buffer_tracker_ ? buffer_tracker_->live_bytes.load(std::memory_order_acquire) : 0; + t.borrowed_buffer_bytes = borrowed_buffer_bytes_.load(std::memory_order_acquire); + 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); + return t; + } + +protected: + struct ControlAction { + enum class Type { + register_fd, + arm_interest, + close_fd + }; + Type type{Type::arm_interest}; + DescriptorId id{}; + }; + + [[nodiscard]] Void::Result::Result allocate_slot_locked(int fd) + { + if (stopping_.load(std::memory_order_acquire)) { + return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver is stopped")}; + } + std::uint32_t idx = 0; + if (!free_slots_.empty()) { + idx = free_slots_.back(); + free_slots_.pop_back(); + } else { + if (slots_.size() >= limits_.max_descriptors) { + return std::unexpected{make_io_error( + IoErrorCode::overloaded, + "IO Driver max_descriptors limit reached")}; + } + idx = static_cast(slots_.size()); + slots_.emplace_back(); + slots_.back().id.slot = idx; + slots_.back().id.generation = 0; + } + auto& s = slots_[idx]; + s.id.slot = idx; + s.id.generation = + (s.id.generation == std::numeric_limits::max() || + s.id.generation == 0) + ? 1u + : (s.id.generation + 1u); + s.fd = fd; + s.in_use = true; + s.closing = false; + s.close_enqueued = false; + s.eof_seen = false; + s.epoll_registered = false; + s.epoll_out_armed = false; + s.active_read.reset(); + s.active_write.reset(); + s.close_waiters.clear(); + active_descriptors_.fetch_add(1, std::memory_order_acq_rel); + return s.id; + } + + 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) { + ::close(s.fd); + } +#else + (void)close_native_fd; +#endif + s.fd = -1; + s.in_use = false; + s.closing = false; + s.close_enqueued = false; + s.eof_seen = false; + s.epoll_registered = false; + s.epoll_out_armed = false; + s.active_read.reset(); + s.active_write.reset(); + free_slots_.push_back(idx); + active_descriptors_.fetch_sub(1, std::memory_order_acq_rel); + } + + void enqueue_close_control_locked(DescriptorId id) + { + control_queue_.push_back(ControlAction{ControlAction::Type::close_fd, id}); + } + + // Retires `op` from its slot and decrements counters under `mu_`, collecting + // any close_waiters ready once both directions have drained. + void retire_op_locked(PendingOp& op, + std::vector& ready_close_waiters) noexcept + { + if (op.retired) { + return; + } + op.retired = true; + 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); + } + + if (op.desc_id.valid() && op.desc_id.slot < slots_.size()) { + auto& slot = slots_[op.desc_id.slot]; + if (slot.in_use && slot.id.generation == op.desc_id.generation) { + if (op.dir == Direction::read && slot.active_read.get() == &op) { + slot.active_read.reset(); + } else if (op.dir == Direction::write && slot.active_write.get() == &op) { + slot.active_write.reset(); + } + if (slot.closing && !slot.active_read && !slot.active_write && + kind() == BackendPreference::mock) { + ready_close_waiters.insert( + ready_close_waiters.end(), + std::make_move_iterator(slot.close_waiters.begin()), + std::make_move_iterator(slot.close_waiters.end())); + slot.close_waiters.clear(); + release_slot_locked(op.desc_id.slot, false); + } + } + } + } + + void 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_}; + retire_op_locked(*op, close_waiters); + } + if (res.has_value()) { + if (auto t = op->op_state->try_commit_value(*res); t.has_value()) { + out_tickets.push_back(std::move(*t)); + } + } else { + const auto& ec = res.error().code(); + std::optional t; + if (ec.domain == Void::Result::kIoErrorDomain && + static_cast(ec.value) == IoErrorCode::cancelled) { + t = op->op_state->try_commit_error( + res.error(), Async::DomainOutcomeKind::cancelled); + } else { + t = op->op_state->try_commit_error(res.error()); + } + if (t.has_value()) { + out_tickets.push_back(std::move(*t)); + } + } + if (auto t = op->op_state->release_backend_ref(); t.has_value()) { + out_tickets.push_back(std::move(*t)); + } + for (auto& cw : close_waiters) { + if (auto t = cw.op_state->try_commit_value(); t.has_value()) { + out_tickets.push_back(std::move(*t)); + } + if (auto t = cw.op_state->release_backend_ref(); t.has_value()) { + out_tickets.push_back(std::move(*t)); + } + } + close_waiters.clear(); + } + + [[nodiscard]] virtual Void::Result::Result + on_op_submitted_locked(DescriptorSlot& slot, + Direction dir, + const std::shared_ptr& op) = 0; + + Async::Executor& executor_; + IoLimits limits_{}; + const Void::Time::MonotonicClock& clock_; + std::shared_ptr buffer_tracker_{}; + + mutable std::mutex mu_{}; + std::atomic stopping_{false}; + 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::vector slots_{}; + std::vector free_slots_{}; + std::vector control_queue_{}; + std::vector> cancel_queue_{}; + +private: + [[nodiscard]] Void::Result::Result>> + submit_io(const std::shared_ptr& stream, + Direction dir, + std::byte* read_ptr, + const std::byte* write_ptr, + std::size_t len, + Async::OperationOptions options) + { + 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, "IO operation cancelled before submission")}; + } + if (Async::is_deadline_expired(options, clock_)) { + return std::unexpected{make_io_error( + IoErrorCode::timeout, "IO operation deadline expired before submission")}; + } + + const DescriptorId did = stream->id(); + auto op = std::make_shared(); + op->desc_id = did; + op->dir = dir; + op->read_ptr = read_ptr; + op->write_ptr = write_ptr; + op->len = len; + op->deadline = options.deadline; + op->op_state = Async::OperationState::create( + options, &executor_, Async::StopBehavior::notify_only); + + { + std::lock_guard lk{mu_}; + if (stopping_.load(std::memory_order_acquire)) { + return std::unexpected{make_io_error( + IoErrorCode::closed, "IO Driver is shutting down")}; + } + if (!did.valid() || did.slot >= slots_.size() || + !slots_[did.slot].in_use || + slots_[did.slot].id.generation != did.generation || + slots_[did.slot].closing) { + return std::unexpected{make_io_error( + IoErrorCode::closed, "ByteStream descriptor is closed")}; + } + auto& slot = slots_[did.slot]; + if ((dir == Direction::read && slot.active_read) || + (dir == Direction::write && slot.active_write)) { + return std::unexpected{make_io_error( + IoErrorCode::busy, + (dir == Direction::read) + ? "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")}; + } + + 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; + } else { + slot.active_write = op; + } + + if (auto sub_res = on_op_submitted_locked(slot, dir, op); !sub_res.has_value()) { + if (dir == Direction::read) { + slot.active_read.reset(); + } else { + slot.active_write.reset(); + } + active_operations_.fetch_sub(1, std::memory_order_acq_rel); + borrowed_buffer_bytes_.fetch_sub(len, std::memory_order_acq_rel); + (void)op->op_state->release_backend_ref(); + return std::unexpected{std::move(sub_res.error())}; + } + } + + const std::stop_token op_stop = op->op_state->stop_token(); + if (op_stop.stop_possible()) { + op->cancel_cb.emplace( + op_stop, + PendingOp::CancelForwarder{ + std::static_pointer_cast(this->shared_from_this()), + op}); + } + + if (kind() == BackendPreference::epoll) { + wake(); + } + return op->op_state; + } +}; + +inline void PendingOp::CancelForwarder::operator()() const noexcept +{ + if (auto b = backend.lock()) { + if (auto p = op.lock()) { + b->enqueue_cancel(p); + } + } +} + +// ── MockBackend ────────────────────────────────────────────────────────────── + +class MockBackend final : public BaseBackend +{ +public: + using BaseBackend::BaseBackend; + + [[nodiscard]] BackendPreference kind() const noexcept override { return BackendPreference::mock; } + [[nodiscard]] MockBackend* as_mock() noexcept override { return this; } + + [[nodiscard]] Void::Result::Result> + create_mock_stream() override + { + DescriptorId id; + { + std::lock_guard lk{mu_}; + auto res = allocate_slot_locked(-1); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + id = *res; + } + return std::make_shared(this->shared_from_this(), id); + } + + [[nodiscard]] Void::Result::Result> adopt_fd(int) override + { + return std::unexpected{make_io_error( + IoErrorCode::unsupported, "MockBackend does not adopt OS file descriptors")}; + } + + [[nodiscard]] Void::Result::Result< + std::pair, std::shared_ptr>> + create_socket_pair() override + { + return std::unexpected{make_io_error( + IoErrorCode::unsupported, "MockBackend does not create OS socketpairs")}; + } + + void wake() noexcept override + { + wakeups_.fetch_add(1, std::memory_order_acq_rel); + } + + [[nodiscard]] std::size_t pending_count(DescriptorId id, Direction dir) const noexcept + { + std::lock_guard lk{mu_}; + if (!id.valid() || id.slot >= slots_.size()) { + return 0; + } + const auto& s = slots_[id.slot]; + if (!s.in_use || s.id.generation != id.generation) { + return 0; + } + const auto& op = (dir == Direction::read) ? s.active_read : s.active_write; + return (op && !op->in_execution && !op->retired) ? 1 : 0; + } + + [[nodiscard]] std::optional + try_acquire(DescriptorId id, Direction dir) + { + std::lock_guard lk{mu_}; + if (!id.valid() || id.slot >= slots_.size()) { + return std::nullopt; + } + auto& s = slots_[id.slot]; + if (!s.in_use || s.id.generation != id.generation) { + return std::nullopt; + } + auto& op = (dir == Direction::read) ? s.active_read : s.active_write; + if (!op || op->in_execution || op->retired) { + return std::nullopt; + } + op->in_execution = true; + const std::uint64_t tok = next_token_++; + op->mock_token = tok; + held_requests_.emplace(tok, op); + return tok; + } + + [[nodiscard]] bool is_stop_requested(std::uint64_t tok) const noexcept + { + std::lock_guard lk{mu_}; + auto it = held_requests_.find(tok); + return (it != held_requests_.end()) && it->second->op_state->stop_requested(); + } + + [[nodiscard]] std::size_t requested_size(std::uint64_t tok) const noexcept + { + std::lock_guard lk{mu_}; + auto it = held_requests_.find(tok); + return (it != held_requests_.end()) ? it->second->len : 0; + } + + bool finish_read_data(std::uint64_t tok, std::span data, bool eof) + { + std::shared_ptr op = take_held(tok); + if (!op) { + return false; + } + const std::size_t copy_n = std::min(op->len, data.size()); + if (copy_n > 0 && op->read_ptr != nullptr) { + std::memcpy(op->read_ptr, data.data(), copy_n); + } + std::vector tickets; + std::vector close_waiters; + complete_op_and_collect_tickets( + op, Transfer{copy_n, eof}, tickets, close_waiters); + dispatch_tickets(tickets); + return true; + } + + bool finish_write_bytes(std::uint64_t tok, std::size_t bytes) + { + std::shared_ptr op = take_held(tok); + if (!op) { + return false; + } + const std::size_t wrote = std::min(op->len, bytes); + std::vector tickets; + std::vector close_waiters; + complete_op_and_collect_tickets( + op, Transfer{wrote, false}, tickets, close_waiters); + dispatch_tickets(tickets); + return true; + } + + bool finish_error(std::uint64_t tok, Void::Result::Error err) + { + std::shared_ptr op = take_held(tok); + if (!op) { + return false; + } + std::vector tickets; + std::vector close_waiters; + complete_op_and_collect_tickets( + op, std::unexpected{std::move(err)}, tickets, close_waiters); + dispatch_tickets(tickets); + return true; + } + + [[nodiscard]] Void::Result::Result + poll_once(std::optional) override + { + turns_.fetch_add(1, std::memory_order_acq_rel); + + 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; + { + std::lock_guard lk{mu_}; + skip = op->in_execution || op->retired; + } + if (skip) { + continue; + } + 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 (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) { + if (ctrl.type == ControlAction::Type::close_fd) { + std::lock_guard lk{mu_}; + if (ctrl.id.valid() && ctrl.id.slot < slots_.size() && + slots_[ctrl.id.slot].in_use && + slots_[ctrl.id.slot].id.generation == ctrl.id.generation) { + auto& s = slots_[ctrl.id.slot]; + if (!s.active_read && !s.active_write) { + 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(ctrl.id.slot, false); + ++processed; + } + } + } + } + + 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 processed; + } + + [[nodiscard]] Void::Result::Result shutdown_and_join() override + { + stopping_.store(true, std::memory_order_release); + std::vector> to_abort; + std::vector close_waiters; + { + 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; + } + } + 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); + } + { + 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, + const std::shared_ptr&) override + { + return {}; + } + +private: + std::shared_ptr take_held(std::uint64_t tok) + { + std::lock_guard lk{mu_}; + auto it = held_requests_.find(tok); + if (it == held_requests_.end()) { + return nullptr; + } + auto op = std::move(it->second); + held_requests_.erase(it); + return op; + } + + std::uint64_t next_token_{1}; + std::unordered_map> held_requests_{}; +}; + +// ── Linux Level-Triggered EpollBackend ─────────────────────────────────────── + +#ifdef __linux__ +class EpollBackend final : public BaseBackend +{ +public: + static Void::Result::Result> create_epoll( + Async::Executor& executor, + IoLimits limits, + const Void::Time::MonotonicClock& clock, + std::shared_ptr buffer_tracker) + { + const int epfd = ::epoll_create1(EPOLL_CLOEXEC); + if (epfd < 0) { + return std::unexpected{make_io_error( + IoErrorCode::os_error, "epoll_create1 failed", errno_code(errno))}; + } + const int wfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + if (wfd < 0) { + const int err = errno; + ::close(epfd); + return std::unexpected{make_io_error( + IoErrorCode::os_error, "eventfd failed", errno_code(err))}; + } + epoll_event ev{}; + ev.events = EPOLLIN; // Strictly level-triggered + ev.data.u64 = kWakeSentinel; + if (::epoll_ctl(epfd, EPOLL_CTL_ADD, wfd, &ev) != 0) { + const int err = errno; + ::close(wfd); + ::close(epfd); + 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)); + } + + ~EpollBackend() override + { + (void)shutdown_and_join(); + if (wake_fd_ >= 0) { + ::close(wake_fd_); + wake_fd_ = -1; + } + if (epoll_fd_ >= 0) { + ::close(epoll_fd_); + epoll_fd_ = -1; + } + } + + [[nodiscard]] BackendPreference kind() const noexcept override + { + return BackendPreference::epoll; + } + + [[nodiscard]] Void::Result::Result> + create_mock_stream() override + { + return std::unexpected{make_io_error( + IoErrorCode::unsupported, "EpollBackend does not create mock streams")}; + } + + [[nodiscard]] Void::Result::Result> adopt_fd(int fd) override + { + if (fd < 0) { + return std::unexpected{make_io_error( + IoErrorCode::invalid_argument, "Invalid negative fd in adopt_fd")}; + } + const int flags = ::fcntl(fd, F_GETFL, 0); + if (flags >= 0) { + (void)::fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } + const int fdflags = ::fcntl(fd, F_GETFD, 0); + if (fdflags >= 0) { + (void)::fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC); + } + + DescriptorId id; + { + std::lock_guard lk{mu_}; + if (control_queue_.size() >= limits_.max_control_submissions) { + return std::unexpected{make_io_error( + IoErrorCode::overloaded, "IO Driver control queue full")}; + } + auto res = allocate_slot_locked(fd); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + id = *res; + control_queue_.push_back(ControlAction{ControlAction::Type::register_fd, id}); + } + wake(); + return std::make_shared(this->shared_from_this(), id); + } + + [[nodiscard]] Void::Result::Result< + std::pair, std::shared_ptr>> + create_socket_pair() override + { + std::array fds{-1, -1}; + if (::socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds.data()) != 0) { + return std::unexpected{make_io_error( + IoErrorCode::os_error, "socketpair failed", errno_code(errno))}; + } + auto s0 = adopt_fd(fds[0]); + if (!s0.has_value()) { + ::close(fds[0]); + ::close(fds[1]); + return std::unexpected{std::move(s0.error())}; + } + auto s1 = adopt_fd(fds[1]); + if (!s1.has_value()) { + on_stream_destroyed((*s0)->id()); + ::close(fds[1]); + return std::unexpected{std::move(s1.error())}; + } + return std::make_pair(std::move(*s0), std::move(*s1)); + } + + void wake() noexcept override + { + wakeups_.fetch_add(1, std::memory_order_acq_rel); + const int wfd = wake_fd_; + if (wfd >= 0) { + const std::uint64_t one = 1; + const ssize_t r = ::write(wfd, &one, sizeof(one)); + (void)r; + } + } + + [[nodiscard]] Void::Result::Result + poll_once(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. + work_done += process_cancels_and_controls(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. + int timeout_ms = 0; + { + std::optional earliest; + { + std::lock_guard lk{mu_}; + for (const auto& s : slots_) { + if (!s.in_use) { + continue; + } + for (const auto* op : {&s.active_read, &s.active_write}) { + if (*op && (*op)->deadline.has_value()) { + if (!earliest.has_value() || *(*op)->deadline < *earliest) { + earliest = *(*op)->deadline; + } + } + } + } + } + if (max_wait.has_value()) { + auto wait_ns = *max_wait; + if (earliest.has_value()) { + const auto rem = Void::Time::remaining_until(clock_, *earliest); + if (rem < wait_ns) { + wait_ns = rem; + } + } + if (wait_ns.count() <= 0) { + timeout_ms = 0; + } else { + const auto ms = + std::chrono::duration_cast(wait_ns).count(); + timeout_ms = static_cast( + std::clamp(ms == 0 ? 1 : ms, 0, 5000)); + } + } else { + if (earliest.has_value()) { + const auto rem = Void::Time::remaining_until(clock_, *earliest); + const auto ms = + std::chrono::duration_cast(rem).count(); + timeout_ms = static_cast( + std::clamp((rem.count() > 0 && ms == 0) ? 1 : ms, 0, 5000)); + } else { + timeout_ms = -1; + } + } + } + + std::vector events(limits_.max_ready_per_turn); + int nready = 0; + for (;;) { + nready = ::epoll_wait( + epoll_fd_, + events.data(), + static_cast(events.size()), + timeout_ms); + if (nready < 0 && errno == EINTR) { + continue; + } + break; + } + if (nready < 0) { + return std::unexpected{make_io_error( + 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; + if (token == kWakeSentinel) { + drain_wake_fd(); + continue; + } + const std::uint32_t slot_idx = static_cast(token & 0xFFFFFFFFULL); + const std::uint32_t gen = static_cast(token >> 32); + + int fd = -1; + std::shared_ptr read_op; + std::shared_ptr write_op; + { + std::lock_guard lk{mu_}; + if (slot_idx >= slots_.size() || + !slots_[slot_idx].in_use || + slots_[slot_idx].id.generation != gen || + slots_[slot_idx].fd < 0 || + slots_[slot_idx].closing) { + stale_events_ignored_.fetch_add(1, std::memory_order_acq_rel); + continue; + } + fd = slots_[slot_idx].fd; + if ((ev_mask & (EPOLLIN | EPOLLRDHUP | EPOLLHUP | EPOLLERR)) != 0 && + slots_[slot_idx].active_read && + !slots_[slot_idx].active_read->retired) { + read_op = slots_[slot_idx].active_read; + } + if ((ev_mask & (EPOLLOUT | EPOLLHUP | EPOLLERR)) != 0 && + slots_[slot_idx].active_write && + !slots_[slot_idx].active_write->retired) { + write_op = slots_[slot_idx].active_write; + } + } + + if (read_op) { + work_done += drive_read(slot_idx, gen, fd, ev_mask, read_op, tickets); + } + if (write_op) { + work_done += drive_write(slot_idx, gen, fd, ev_mask, write_op, tickets); + } + } + + // Check deadlines and drain any cancels triggered before/during syscalls + work_done += process_cancels_and_controls(tickets); + work_done += expire_deadlines(tickets); + dispatch_tickets(tickets); + return work_done; + } + + [[nodiscard]] Void::Result::Result shutdown_and_join() 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); + } + } + } + + 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); + } + + { + 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(); + } + + 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& slot, + Direction dir, + const std::shared_ptr&) override + { + if (!slot.epoll_registered || (dir == Direction::write && !slot.epoll_out_armed)) { + control_queue_.push_back(ControlAction{ControlAction::Type::arm_interest, slot.id}); + } + return {}; + } + +private: + static constexpr std::uint64_t kWakeSentinel = std::numeric_limits::max(); + + EpollBackend(Async::Executor& executor, + IoLimits limits, + const Void::Time::MonotonicClock& clock, + std::shared_ptr buffer_tracker, + int epoll_fd, + int wake_fd) noexcept + : BaseBackend(executor, limits, clock, std::move(buffer_tracker)) + , epoll_fd_(epoll_fd) + , wake_fd_(wake_fd) + { + } + + [[nodiscard]] static std::uint64_t encode_token(DescriptorId id) noexcept + { + return (static_cast(id.generation) << 32) | + static_cast(id.slot); + } + + void sync_epoll_interest_locked(DescriptorSlot& slot) noexcept + { + if (!slot.in_use || slot.fd < 0 || slot.closing || epoll_fd_ < 0) { + return; + } + const bool want_out = (slot.active_write != nullptr && !slot.active_write->retired); + epoll_event ev{}; + std::uint32_t events = static_cast(EPOLLIN) | + static_cast(EPOLLRDHUP); + if (want_out) { + events |= static_cast(EPOLLOUT); + } + ev.events = events; + ev.data.u64 = encode_token(slot.id); + if (!slot.epoll_registered) { + if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, slot.fd, &ev) == 0) { + slot.epoll_registered = true; + slot.epoll_out_armed = want_out; + } + } else if (slot.epoll_out_armed != want_out) { + if (::epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, slot.fd, &ev) == 0) { + slot.epoll_out_armed = want_out; + } + } + } + + void drain_wake_fd() noexcept + { + if (wake_fd_ < 0) { + return; + } + std::uint64_t buf = 0; + for (;;) { + const ssize_t r = ::read(wake_fd_, &buf, sizeof(buf)); + if (r < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (r == 0) { + break; + } + } + } + + std::size_t process_cancels_and_controls(std::vector& tickets) + { + std::size_t done = 0; + std::vector> cancels; + std::vector controls; + std::vector close_waiters; + + { + std::lock_guard lk{mu_}; + cancels.swap(cancel_queue_); + controls.swap(control_queue_); + } + + for (const auto& op : cancels) { + { + std::lock_guard lk{mu_}; + if (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) { + 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; + } + + { + std::lock_guard lk{mu_}; + for (const auto& act : controls) { + if (!act.id.valid() || act.id.slot >= slots_.size()) { + continue; + } + auto& s = slots_[act.id.slot]; + if (!s.in_use || s.id.generation != act.id.generation) { + continue; + } + if (act.type == ControlAction::Type::register_fd || + act.type == ControlAction::Type::arm_interest) { + sync_epoll_interest_locked(s); + } else if (act.type == ControlAction::Type::close_fd) { + if (!s.active_read && !s.active_write) { + if (s.epoll_registered && epoll_fd_ >= 0 && s.fd >= 0) { + (void)::epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, s.fd, nullptr); + } + 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(act.id.slot, true); + ++done; + } + } + } + } + + 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)); + } + } + return done; + } + + std::size_t expire_deadlines(std::vector& tickets) + { + std::vector> expired; + const auto now = clock_.now(); + { + std::lock_guard lk{mu_}; + for (auto& s : slots_) { + if (!s.in_use) { + continue; + } + if (s.active_read && !s.active_read->retired && + 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 && + s.active_write->deadline.has_value() && now >= *s.active_write->deadline) { + expired.push_back(s.active_write); + } + } + } + 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() && + 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]; + s.active_write.reset(); + sync_epoll_interest_locked(s); + 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)); + } + } + return expired.size(); + } + + std::size_t drive_read(std::uint32_t slot_idx, + std::uint32_t gen, + int fd, + std::uint32_t ev_mask, + const std::shared_ptr& op, + std::vector& tickets) + { + 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; + } + + const std::size_t to_read = std::min(op->len, limits_.max_bytes_per_turn); + ssize_t n = 0; + int saved_errno = 0; + for (;;) { + n = ::read(fd, op->read_ptr, to_read); + if (n < 0) { + saved_errno = errno; + if (saved_errno == EINTR) { + continue; + } + } + break; + } + + if (n > 0) { + std::vector close_waiters; + complete_op_and_collect_tickets( + op, Transfer{static_cast(n), false}, tickets, close_waiters); + return 1; + } + if (n == 0) { + std::vector close_waiters; + complete_op_and_collect_tickets( + op, Transfer{0, true}, tickets, close_waiters); + return 1; + } + 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; + } + } + 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; + } + + std::size_t drive_write(std::uint32_t slot_idx, + std::uint32_t gen, + int fd, + std::uint32_t ev_mask, + const std::shared_ptr& op, + std::vector& tickets) + { + 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; + } + } + 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; + } + + const std::size_t to_write = std::min(op->len, limits_.max_bytes_per_turn); + ssize_t n = 0; + int saved_errno = 0; + for (;;) { + n = ::send(fd, op->write_ptr, to_write, MSG_NOSIGNAL); + if (n < 0) { + saved_errno = errno; + if (saved_errno == EINTR) { + continue; + } + if (saved_errno == ENOTSOCK) { + n = ::write(fd, op->write_ptr, to_write); + if (n < 0) { + saved_errno = errno; + if (saved_errno == EINTR) { + continue; + } + } + } + } + break; + } + + 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; + } + } + std::vector close_waiters; + complete_op_and_collect_tickets( + op, Transfer{static_cast(n), false}, tickets, close_waiters); + return 1; + } + + 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; + } + } + 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 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; + } + } + 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; + } + + int epoll_fd_{-1}; + int wake_fd_{-1}; +}; +#endif // __linux__ + +} // namespace Void::IO::detail + +namespace Void::IO +{ + +// ── MockController ─────────────────────────────────────────────────────────── + +std::size_t MockController::pending_read_count(const ByteStream& stream) const noexcept +{ + return backend_ ? backend_->pending_count(stream.id(), detail::Direction::read) : 0; +} + +std::size_t MockController::pending_write_count(const ByteStream& stream) const noexcept +{ + return backend_ ? backend_->pending_count(stream.id(), detail::Direction::write) : 0; +} + +std::optional MockController::try_acquire_read(const ByteStream& stream) +{ + return backend_ ? backend_->try_acquire(stream.id(), detail::Direction::read) : std::nullopt; +} + +std::optional MockController::try_acquire_write(const ByteStream& stream) +{ + return backend_ ? backend_->try_acquire(stream.id(), detail::Direction::write) : std::nullopt; +} + +bool MockController::is_stop_requested(std::uint64_t token) const noexcept +{ + return backend_ && backend_->is_stop_requested(token); +} + +std::size_t MockController::requested_size(std::uint64_t token) const noexcept +{ + return backend_ ? backend_->requested_size(token) : 0; +} + +bool MockController::finish_read_data(std::uint64_t token, + std::span data, + bool eof) +{ + return backend_ && backend_->finish_read_data(token, data, eof); +} + +bool MockController::finish_write_bytes(std::uint64_t token, std::size_t bytes) +{ + return backend_ && backend_->finish_write_bytes(token, bytes); +} + +bool MockController::finish_error(std::uint64_t token, Void::Result::Error err) +{ + return backend_ && backend_->finish_error(token, std::move(err)); +} + +bool MockController::finish_cancelled(std::uint64_t token, std::string msg) +{ + return finish_error(token, make_io_error(IoErrorCode::cancelled, std::move(msg))); +} + +bool MockController::complete_read(const ByteStream& stream, + std::span data, + bool eof) +{ + auto tok = try_acquire_read(stream); + return tok.has_value() && finish_read_data(*tok, data, eof); +} + +bool MockController::complete_write(const ByteStream& stream, std::size_t bytes) +{ + auto tok = try_acquire_write(stream); + return tok.has_value() && finish_write_bytes(*tok, bytes); +} + +bool MockController::fail_read(const ByteStream& stream, Void::Result::Error err) +{ + auto tok = try_acquire_read(stream); + return tok.has_value() && finish_error(*tok, std::move(err)); +} + +bool MockController::fail_write(const ByteStream& stream, Void::Result::Error err) +{ + auto tok = try_acquire_write(stream); + return tok.has_value() && finish_error(*tok, std::move(err)); +} + +// ── Driver ─────────────────────────────────────────────────────────────────── + +Driver::Driver(std::shared_ptr backend, + std::shared_ptr buffer_tracker) noexcept + : backend_(std::move(backend)) + , buffer_tracker_(std::move(buffer_tracker)) +{ + if (backend_ && backend_->as_mock() != nullptr) { + mock_controller_ = std::make_unique(backend_->as_mock()); + } +} + +Driver::~Driver() +{ + if (backend_) { + (void)backend_->shutdown_and_join(); + } +} + +Void::Result::Result> Driver::create( + Async::Executor& executor, + BackendOptions options, + const Void::Time::MonotonicClock& clock, + std::pmr::memory_resource* resource) +{ + if (auto v = validate_limits(options.limits); !v.has_value()) { + return std::unexpected{std::move(v.error())}; + } + + auto tracker = std::make_shared( + resource, options.limits.max_owned_buffer_bytes); + + std::shared_ptr backend; + if (options.preference == BackendPreference::mock) { + backend = std::make_shared( + executor, options.limits, clock, tracker); + } else { +#ifdef __linux__ + auto ep = detail::EpollBackend::create_epoll( + executor, options.limits, clock, tracker); + if (!ep.has_value()) { + return std::unexpected{std::move(ep.error())}; + } + backend = std::move(*ep); +#else + return std::unexpected{make_io_error( + IoErrorCode::unsupported, + "Epoll backend is only supported on Linux; use BackendPreference::mock")}; +#endif + } + + return std::unique_ptr(new Driver(std::move(backend), std::move(tracker))); +} + +BackendPreference Driver::active_backend() const noexcept +{ + return backend_->kind(); +} + +const IoLimits& Driver::limits() const noexcept +{ + return backend_->limits(); +} + +const Void::Time::MonotonicClock& Driver::clock() const noexcept +{ + return backend_->clock(); +} + +Async::Executor& Driver::executor() noexcept +{ + return backend_->executor(); +} + +DriverTelemetry Driver::telemetry() const noexcept +{ + return backend_->telemetry(); +} + +Void::Result::Result Driver::allocate_buffer(std::size_t bytes) +{ + return BufferLease::allocate(buffer_tracker_, bytes); +} + +Void::Result::Result Driver::create_mock_stream() +{ + auto st = backend_->create_mock_stream(); + if (!st.has_value()) { + return std::unexpected{std::move(st.error())}; + } + return ByteStream{std::move(*st)}; +} + +MockController* Driver::mock_controller() noexcept +{ + return mock_controller_.get(); +} + +Void::Result::Result Driver::adopt_fd(int fd) +{ + auto st = backend_->adopt_fd(fd); + if (!st.has_value()) { + return std::unexpected{std::move(st.error())}; + } + return ByteStream{std::move(*st)}; +} + +Void::Result::Result> Driver::create_socket_pair() +{ + auto pair_res = backend_->create_socket_pair(); + if (!pair_res.has_value()) { + return std::unexpected{std::move(pair_res.error())}; + } + return std::make_pair( + ByteStream{std::move(pair_res->first)}, + ByteStream{std::move(pair_res->second)}); +} + +Void::Result::Result Driver::poll_once( + std::optional max_wait) +{ + return backend_->poll_once(max_wait); +} + +void Driver::wake() noexcept +{ + backend_->wake(); +} + +void Driver::request_stop() noexcept +{ + backend_->request_stop(); +} + +Void::Result::Result Driver::shutdown_and_join() +{ + return backend_->shutdown_and_join(); +} + +} // namespace Void::IO \ No newline at end of file diff --git a/src/IO/module.cmake b/src/IO/module.cmake new file mode 100644 index 0000000..b12d9da --- /dev/null +++ b/src/IO/module.cmake @@ -0,0 +1,3 @@ +void_add_module(IO + INTERNAL_DEPS Core Functional Time Memory Async +) \ No newline at end of file diff --git a/tests/package/IOOnly/CMakeLists.txt b/tests/package/IOOnly/CMakeLists.txt new file mode 100644 index 0000000..85087b5 --- /dev/null +++ b/tests/package/IOOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidIOOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS IO) + +add_executable(void_io_only_consumer main.cpp) +target_link_libraries(void_io_only_consumer PRIVATE Void::IO) + +enable_testing() +add_test(NAME VoidIOOnlyConsumer COMMAND void_io_only_consumer) \ No newline at end of file diff --git a/tests/package/IOOnly/main.cpp b/tests/package/IOOnly/main.cpp new file mode 100644 index 0000000..5d46639 --- /dev/null +++ b/tests/package/IOOnly/main.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include + +#include + +int main() +{ + Void::Async::ManualExecutor exec; + auto drv_res = Void::IO::Driver::create( + exec, Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::mock}); + if (!drv_res.has_value()) { + return 1; + } + auto& driver = **drv_res; + auto buf = driver.allocate_buffer(32); + auto stream = driver.create_mock_stream(); + if (!buf.has_value() || !stream.has_value()) { + return 1; + } + std::memset(buf->writable().data(), 'x', buf->size()); +#ifdef __linux__ + auto ep = Void::IO::Driver::create( + exec, Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::epoll}); + if (!ep.has_value()) { + return 1; + } + auto pair_res = (*ep)->create_socket_pair(); + if (!pair_res.has_value()) { + return 1; + } +#endif + return 0; +} \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 2e86573..523e78c 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -106,6 +106,11 @@ if(_has_unicode) run_consumer(UnicodeOnly "${install_prefix}" "UnicodeOnly" ${_no_external_deps}) endif() +has_modules(_has_io IO Async Memory Time Functional Core) +if(_has_io) + run_consumer(IOOnly "${install_prefix}" "IOOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/IO/IoDriver.cpp b/tests/standalone/IO/IoDriver.cpp new file mode 100644 index 0000000..10c35c6 --- /dev/null +++ b/tests/standalone/IO/IoDriver.cpp @@ -0,0 +1,509 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +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::IoErrorCode; +using Void::IO::IoLimits; +using Void::IO::Transfer; +using Void::IO::read_exact; +using Void::IO::write_all; + +[[nodiscard]] std::span as_bytes(std::string_view sv) noexcept +{ + return std::as_bytes(std::span{sv.data(), sv.size()}); +} + +void pump_driver_and_exec(Driver& driver, ManualExecutor& exec, TaskScope& scope) +{ + for (int iter = 0; iter < 512 && scope.active_count() > 0; ++iter) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + if (scope.active_count() > 0) { + (void)scope.join_pumping(exec); + } +} + +} // namespace + +Void::Testing::Test io_mock_limits_zero_len_busy_and_buffer_leases() +{ + ManualExecutor exec; + Void::Time::ManualClock clock{ + Void::Time::MonotonicClock::time_point{std::chrono::seconds{100}}}; + + // Invalid limits rejected cleanly before creating Driver + { + auto bad = Driver::create( + exec, + BackendOptions{ + .limits = IoLimits{.max_descriptors = 0}, + .preference = BackendPreference::mock, + }, + clock); + Void::Testing::expect(!bad.has_value()); + Void::Testing::expect( + bad.error().code().value == + static_cast(IoErrorCode::invalid_argument)); + } + + BufferLease outliving_lease; + { + auto drv_res = Driver::create( + exec, + BackendOptions{ + .limits = IoLimits{ + .max_descriptors = 1, + .max_operations = 2, + .max_owned_buffer_bytes = 64, + }, + .preference = BackendPreference::mock, + }, + clock); + Void::Testing::require(drv_res.has_value()); + Driver& driver = **drv_res; + Void::Testing::expect(driver.active_backend() == BackendPreference::mock); + + // Descriptor quota enforced + auto s1_res = driver.create_mock_stream(); + Void::Testing::require(s1_res.has_value()); + ByteStream s1 = std::move(*s1_res); + + auto s2_res = driver.create_mock_stream(); + Void::Testing::expect(!s2_res.has_value()); + Void::Testing::expect( + s2_res.error().code().value == + static_cast(IoErrorCode::overloaded)); + + // BufferLease quota enforced & safely returned on release + auto b1 = driver.allocate_buffer(48); + Void::Testing::require(b1.has_value()); + Void::Testing::expect_eq(driver.telemetry().owned_buffer_bytes, std::size_t{48}); + + auto b2 = driver.allocate_buffer(32); + Void::Testing::expect(!b2.has_value()); + Void::Testing::expect( + b2.error().code().value == + static_cast(IoErrorCode::exhausted)); + + outliving_lease = std::move(*b1); + std::memset(outliving_lease.writable().data(), 0x5A, outliving_lease.size()); + Void::Testing::expect_eq(driver.telemetry().owned_buffer_bytes, std::size_t{48}); + + // Zero-length read & write succeed immediately without hitting mock controller + TaskScope scope{exec}; + Void::Result::Result zero_r{}; + Void::Result::Result zero_w{}; + auto run_zero = [](ByteStream* st, + Void::Result::Result* r_out, + Void::Result::Result* w_out) -> Void::Coro::Task { + *r_out = co_await st->read_some({}); + *w_out = co_await st->write_some({}); + }; + Void::Testing::require(scope.spawn(run_zero(&s1, &zero_r, &zero_w)).has_value()); + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::require(zero_r.has_value()); + Void::Testing::require(zero_w.has_value()); + Void::Testing::expect_eq(zero_r->bytes, std::size_t{0}); + Void::Testing::expect(!zero_r->eof); + Void::Testing::expect_eq(zero_w->bytes, std::size_t{0}); + + // Opposite-direction read+write allowed concurrently; second read returns busy! + std::array rbuf1{}; + std::array rbuf2{}; + const std::string payload = "hello!"; + Void::Result::Result r1_res{}; + Void::Result::Result r2_res{}; + Void::Result::Result w1_res{}; + + auto do_read = [](ByteStream* st, + std::span buf, + Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->read_some(buf); + }; + auto do_write = [](ByteStream* st, + std::span buf, + Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->write_some(buf); + }; + + TaskScope dir_scope{exec}; + Void::Testing::require(dir_scope.spawn(do_read(&s1, rbuf1, &r1_res)).has_value()); + Void::Testing::require(dir_scope.spawn(do_write(&s1, as_bytes(payload), &w1_res)).has_value()); + Void::Testing::require(dir_scope.spawn(do_read(&s1, rbuf2, &r2_res)).has_value()); + (void)exec.drain(); + + // Second read must have settled with busy while first read and first write remain pending! + Void::Testing::expect(!r2_res.has_value()); + Void::Testing::expect( + r2_res.error().code().value == static_cast(IoErrorCode::busy)); + auto* ctrl = driver.mock_controller(); + Void::Testing::require(ctrl != nullptr); + Void::Testing::expect_eq(ctrl->pending_read_count(s1), std::size_t{1}); + Void::Testing::expect_eq(ctrl->pending_write_count(s1), std::size_t{1}); + Void::Testing::expect_eq(driver.telemetry().active_operations, std::size_t{2}); + + Void::Testing::expect(ctrl->complete_read(s1, as_bytes("abc"), false)); + Void::Testing::expect(ctrl->complete_write(s1, payload.size())); + Void::Testing::require(dir_scope.join_pumping().has_value()); + + Void::Testing::require(r1_res.has_value()); + Void::Testing::expect_eq(r1_res->bytes, std::size_t{3}); + Void::Testing::require(w1_res.has_value()); + Void::Testing::expect_eq(w1_res->bytes, payload.size()); + Void::Testing::expect_eq(driver.telemetry().active_operations, std::size_t{0}); + Void::Testing::expect_eq(driver.telemetry().borrowed_buffer_bytes, std::size_t{0}); + + // Pre-expired deadline rejects cleanly + Void::Result::Result exp_res{}; + auto expired_read = [](ByteStream* st, + std::span buf, + Void::Time::MonotonicClock::time_point dl, + Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->read_some(buf, OperationOptions{.deadline = dl}); + }; + TaskScope exp_scope{exec}; + Void::Testing::require( + exp_scope.spawn(expired_read(&s1, rbuf1, clock.now(), &exp_res)).has_value()); + Void::Testing::require(exp_scope.join_pumping().has_value()); + Void::Testing::expect(!exp_res.has_value()); + Void::Testing::expect( + exp_res.error().code().value == static_cast(IoErrorCode::timeout)); + } + + // `outliving_lease` still valid and safely destructs after Driver was destroyed! + Void::Testing::expect_eq(outliving_lease.size(), std::size_t{48}); + Void::Testing::expect_eq(static_cast(outliving_lease.readable()[0]), std::uint8_t{0x5A}); + outliving_lease.reset(); +} + +Void::Testing::Test io_mock_stop_completion_races_and_clock_timeout() +{ + ManualExecutor exec; + Void::Time::ManualClock clock{ + Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}}; + auto drv_res = Driver::create( + exec, BackendOptions{.preference = BackendPreference::mock}, clock); + Void::Testing::require(drv_res.has_value()); + Driver& driver = **drv_res; + auto* ctrl = driver.mock_controller(); + Void::Testing::require(ctrl != nullptr); + + auto s_res = driver.create_mock_stream(); + Void::Testing::require(s_res.has_value()); + ByteStream stream = std::move(*s_res); + + // 1. Stop arrives BEFORE backend begins executing -> cancelled cleanly on poll_once + { + std::stop_source ssrc; + std::array buf{}; + int resumes = 0; + Void::Result::Result res{}; + auto task = [](ByteStream* st, + std::span b, + std::stop_token tok, + int* cnt, + Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->read_some(b, OperationOptions{.stop = tok}); + ++(*cnt); + }; + TaskScope scope{exec}; + Void::Testing::require( + scope.spawn(task(&stream, buf, ssrc.get_token(), &resumes, &res)).has_value()); + (void)exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + ssrc.request_stop(); + Void::Testing::require(driver.poll_once().has_value()); + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect( + res.error().code().value == static_cast(IoErrorCode::cancelled)); + } + + // 2. Stop arrives WHILE mock backend holds ref (mid-flight) -> MUST NOT resume or + // release borrowed buffer until backend explicitly finishes! + { + std::stop_source ssrc; + std::array buf{}; + int resumes = 0; + Void::Result::Result res{}; + auto task = [](ByteStream* st, + std::span b, + std::stop_token tok, + int* cnt, + Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->read_some(b, OperationOptions{.stop = tok}); + ++(*cnt); + }; + TaskScope scope{exec}; + Void::Testing::require( + scope.spawn(task(&stream, buf, ssrc.get_token(), &resumes, &res)).has_value()); + (void)exec.drain(); + + const auto tok = ctrl->try_acquire_read(stream); + Void::Testing::require(tok.has_value()); + Void::Testing::expect_eq(ctrl->requested_size(*tok), std::size_t{16}); + + // Fire stop + poll_once + exec.drain while backend still owns buffer! + ssrc.request_stop(); + Void::Testing::require(driver.poll_once().has_value()); + (void)exec.drain(); + Void::Testing::expect_eq(resumes, 0); + Void::Testing::expect(ctrl->is_stop_requested(*tok)); + Void::Testing::expect_eq(driver.telemetry().borrowed_buffer_bytes, std::size_t{16}); + + // Backend actually finished transferring 5 bytes despite stop intent! + Void::Testing::expect(ctrl->finish_read_data(*tok, as_bytes("hello"), false)); + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::require(res.has_value()); + Void::Testing::expect_eq(res->bytes, std::size_t{5}); + Void::Testing::expect_eq(driver.telemetry().borrowed_buffer_bytes, std::size_t{0}); + } + + // 3. Armed operation deadline expires solely on ManualClock::advance + poll_once + { + std::array buf{}; + Void::Result::Result res{}; + const auto dl = clock.now() + std::chrono::seconds{5}; + auto task = [](ByteStream* st, + std::span b, + Void::Time::MonotonicClock::time_point d, + Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->read_some(b, OperationOptions{.deadline = d}); + }; + TaskScope scope{exec}; + Void::Testing::require(scope.spawn(task(&stream, buf, dl, &res)).has_value()); + (void)exec.drain(); + Void::Testing::require(clock.advance(std::chrono::seconds{5}).has_value()); + Void::Testing::require(driver.poll_once().has_value()); + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect( + res.error().code().value == static_cast(IoErrorCode::timeout)); + } +} + +#ifdef __linux__ +Void::Testing::Test io_epoll_socketpair_fragmented_half_close_and_fd_reuse() +{ + ManualExecutor exec; + auto drv_res = Driver::create( + exec, + BackendOptions{ + .limits = IoLimits{.max_descriptors = 8, .max_bytes_per_turn = 16}, + .preference = BackendPreference::epoll, + }); + Void::Testing::require(drv_res.has_value()); + Driver& driver = **drv_res; + Void::Testing::expect(driver.active_backend() == BackendPreference::epoll); + + // Idle driver with no pending write must not spin + const auto idle_work = driver.poll_once(std::chrono::milliseconds{0}); + Void::Testing::require(idle_work.has_value()); + Void::Testing::expect_eq(*idle_work, std::size_t{0}); + + // 1. Fragmented multi-turn transfer with max_bytes_per_turn == 16 & BufferLease roundtrip + auto pair_res = driver.create_socket_pair(); + Void::Testing::require(pair_res.has_value()); + ByteStream a = std::move(pair_res->first); + ByteStream b = std::move(pair_res->second); + const auto a_orig_id = a.id(); + + const std::string expected_msg(73, 'V'); // Forces >= 5 turns at 16B/turn + std::string recv_msg(expected_msg.size(), '\0'); + std::expected write_res{0}; + std::expected read_res{0}; + + auto writer_coro = [](ByteStream* st, + std::span data, + std::expected* out) + -> Void::Coro::Task { + *out = co_await write_all(*st, data); + }; + auto reader_coro = [](ByteStream* st, + std::span data, + std::expected* out) + -> Void::Coro::Task { + *out = co_await read_exact(*st, data); + }; + + { + TaskScope scope{exec}; + Void::Testing::require( + scope.spawn(writer_coro(&a, as_bytes(expected_msg), &write_res)).has_value()); + Void::Testing::require( + scope.spawn(reader_coro( + &b, + std::as_writable_bytes(std::span{recv_msg.data(), recv_msg.size()}), + &read_res)) + .has_value()); + pump_driver_and_exec(driver, exec, scope); + } + Void::Testing::require(write_res.has_value()); + Void::Testing::require(read_res.has_value()); + Void::Testing::expect_eq(*write_res, expected_msg.size()); + Void::Testing::expect_eq(*read_res, expected_msg.size()); + Void::Testing::expect_eq(recv_msg, expected_msg); + + // 2. Half-close / peer close drains already-buffered bytes BEFORE reporting EOF! + auto lease_w = driver.allocate_buffer(10); + auto lease_r = driver.allocate_buffer(16); + Void::Testing::require(lease_w.has_value()); + Void::Testing::require(lease_r.has_value()); + std::memcpy(lease_w->writable().data(), "buffered!!", 10); + + Void::Result::Result owned_w{}; + Void::Result::Result owned_r1{}; + Void::Result::Result owned_r2{}; + Void::Result::Result close_a{}; + + auto write_then_close = [](ByteStream* st, + BufferLease* lw, + Void::Result::Result* w_out, + Void::Result::Result* c_out) -> Void::Coro::Task { + *w_out = co_await st->write_some_owned(*lw); + *c_out = co_await st->close_and_join(); + }; + auto drain_then_eof = [](ByteStream* st, + BufferLease* lr, + Void::Result::Result* r1_out, + Void::Result::Result* r2_out) -> Void::Coro::Task { + *r1_out = co_await st->read_some_owned(*lr); + *r2_out = co_await st->read_some(lr->writable()); + }; + + { + TaskScope scope{exec}; + Void::Testing::require( + scope.spawn(write_then_close(&a, &(*lease_w), &owned_w, &close_a)).has_value()); + // Wait for write+close to push data into kernel buffer before reading from b + for (int i = 0; i < 64 && !close_a.has_value(); ++i) { + (void)exec.drain(); + (void)driver.poll_once(std::chrono::milliseconds{1}); + (void)exec.drain(); + } + Void::Testing::require( + scope.spawn(drain_then_eof(&b, &(*lease_r), &owned_r1, &owned_r2)).has_value()); + pump_driver_and_exec(driver, exec, scope); + } + + Void::Testing::require(owned_w.has_value()); + Void::Testing::expect(close_a.has_value()); + Void::Testing::require(owned_r1.has_value()); + Void::Testing::expect_eq(owned_r1->bytes, std::size_t{10}); + Void::Testing::expect(!owned_r1->eof); + Void::Testing::expect_eq( + std::string_view{ + reinterpret_cast(lease_r->readable().data()), + lease_r->readable().size()}, + std::string_view{"buffered!!"}); + Void::Testing::require(owned_r2.has_value()); + Void::Testing::expect_eq(owned_r2->bytes, std::size_t{0}); + Void::Testing::expect(owned_r2->eof); + + // 3. Closing `b` frees slots and reusing a new socketpair bumps descriptor generation! + { + TaskScope scope{exec}; + Void::Result::Result close_b{}; + auto closer = [](ByteStream* st, Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->close_and_join(); + }; + Void::Testing::require(scope.spawn(closer(&b, &close_b)).has_value()); + pump_driver_and_exec(driver, exec, scope); + Void::Testing::expect(close_b.has_value()); + } + Void::Testing::expect_eq(driver.telemetry().active_descriptors, std::size_t{0}); + + auto reused = driver.create_socket_pair(); + Void::Testing::require(reused.has_value()); + // At least one endpoint reuses slot index with strictly bumped generation > 1! + const bool bumped = + (reused->first.id().generation > a_orig_id.generation) || + (reused->second.id().generation > a_orig_id.generation); + Void::Testing::expect(bumped); +} + +Void::Testing::Test io_epoll_cross_thread_wake_poll_and_stop_tsan() +{ + ManualExecutor exec; + auto drv_res = Driver::create(exec, BackendOptions{.preference = BackendPreference::epoll}); + Void::Testing::require(drv_res.has_value()); + Driver& driver = **drv_res; + + auto pair_res = driver.create_socket_pair(); + Void::Testing::require(pair_res.has_value()); + ByteStream a = std::move(pair_res->first); + ByteStream b = std::move(pair_res->second); + + std::atomic stop_poller{false}; + std::thread poller([&] { + while (!stop_poller.load(std::memory_order_acquire)) { + (void)driver.poll_once(std::chrono::milliseconds{2}); + } + }); + + std::stop_source stop_src; + std::array buf{}; + Void::Result::Result cancelled_r{}; + auto wait_read = [](ByteStream* st, + std::span b_span, + std::stop_token tok, + Void::Result::Result* out) -> Void::Coro::Task { + *out = co_await st->read_some(b_span, OperationOptions{.stop = tok}); + }; + + TaskScope scope{exec}; + Void::Testing::require( + scope.spawn(wait_read(&a, buf, stop_src.get_token(), &cancelled_r)).has_value()); + while (exec.drain() > 0) { + } + std::this_thread::sleep_for(std::chrono::milliseconds{5}); + stop_src.request_stop(); + while (scope.active_count() > 0) { + if (exec.drain() == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + } + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::expect(!cancelled_r.has_value()); + Void::Testing::expect( + cancelled_r.error().code().value == static_cast(IoErrorCode::cancelled)); + + stop_poller.store(true, std::memory_order_release); + driver.wake(); + poller.join(); + (void)b.valid(); +} +#endif // __linux__ \ No newline at end of file From 1b3331e3a85491491589520a9bab552c4635e028 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 09:33:03 +0300 Subject: [PATCH 3/5] feat(Runtime): add inert Host, validated RuntimeLimits, EmbeddedResources, and topological ResourceGraph (S-RUNTIME-01) --- CMakeLists.txt | 2 +- include/Void/Runtime/Host.hpp | 249 +++++++++++++++++++++++ include/Void/Runtime/Options.hpp | 168 +++++++++++++++ include/Void/Runtime/ResourceGraph.hpp | 153 ++++++++++++++ src/Runtime/module.cmake | 3 + tests/package/InstalledComponents.cmake | 5 + tests/package/RuntimeOnly/CMakeLists.txt | 10 + tests/package/RuntimeOnly/main.cpp | 30 +++ tests/standalone/Runtime/RuntimeHost.cpp | 193 ++++++++++++++++++ 9 files changed, 812 insertions(+), 1 deletion(-) create mode 100644 include/Void/Runtime/Host.hpp create mode 100644 include/Void/Runtime/Options.hpp create mode 100644 include/Void/Runtime/ResourceGraph.hpp create mode 100644 src/Runtime/module.cmake create mode 100644 tests/package/RuntimeOnly/CMakeLists.txt create mode 100644 tests/package/RuntimeOnly/main.cpp create mode 100644 tests/standalone/Runtime/RuntimeHost.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0546318..bf4f33b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,7 +60,7 @@ if(VOID_ENABLED_MODULES) if(_void_text MATCHES "INTERNAL_DEPS([^)]*)") separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}") foreach(_void_word IN LISTS _void_words) - if(_void_word MATCHES "^[A-Z0-9_]+$") + if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS)$") break() endif() list(APPEND _void_pending ${_void_word}) diff --git a/include/Void/Runtime/Host.hpp b/include/Void/Runtime/Host.hpp new file mode 100644 index 0000000..8b71f7f --- /dev/null +++ b/include/Void/Runtime/Host.hpp @@ -0,0 +1,249 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Runtime +{ + +enum class HostState { + constructed, + starting, + running, + stopping_admission, + draining, + joining, + stopped, + failed_start, + shutdown_incomplete +}; + +struct EmbeddedResources { + Async::Executor* executor{nullptr}; + IO::Driver* io{nullptr}; + const Void::Time::MonotonicClock* clock{&Void::Time::SystemMonotonicClock::instance()}; + Void::Memory::BudgetResource* memory_budget{nullptr}; + + [[nodiscard]] Void::Result::Result validate() const + { + if (executor == nullptr) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "EmbeddedResources::executor must not be null")}; + } + if (io == nullptr) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "EmbeddedResources::io must not be null")}; + } + if (clock == nullptr) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "EmbeddedResources::clock must not be null")}; + } + return {}; + } +}; + +struct ShutdownReport { + bool complete{true}; + HostState state{HostState::stopped}; + std::size_t pending_owners{0}; + std::vector pending_owner_ids{}; +}; + +[[nodiscard]] inline ResourceGraph make_default_resource_graph(bool embedded_mode) +{ + const ResourceOwnership own = + embedded_mode ? ResourceOwnership::borrowed : ResourceOwnership::owned; + ResourceGraph g; + (void)g.add_node(ResourceNode{"clock", ResourceKind::clock, own, true}); + (void)g.add_node(ResourceNode{"memory_budget", ResourceKind::memory_budget, own, true}); + (void)g.add_node(ResourceNode{"executor", ResourceKind::executor, own, true}); + (void)g.add_node(ResourceNode{"io_driver", ResourceKind::io_driver, own, true}); + (void)g.add_dependency("executor", "clock"); + (void)g.add_dependency("executor", "memory_budget"); + (void)g.add_dependency("io_driver", "clock"); + (void)g.add_dependency("io_driver", "memory_budget"); + (void)g.add_dependency("io_driver", "executor"); + return g; +} + +// Inert P1 Runtime composition handle: validates options, memory/time/IO limits, +// borrowed resources, and topological resource lifecycle order without implicitly +// spawning threads or opening descriptors on construction. +class Host +{ +public: + Host(const Host&) = delete; + Host& operator=(const Host&) = delete; + Host(Host&&) noexcept = default; + Host& operator=(Host&&) noexcept = default; + ~Host() = default; + + [[nodiscard]] static Void::Result::Result create(Options options = {}) + { + if (auto ok = validate_options(options); !ok.has_value()) { + return std::unexpected{std::move(ok.error())}; + } + ResourceGraph g = make_default_resource_graph(options.embedded_mode); + auto plan = g.validate_and_plan(); + if (!plan.has_value()) { + return std::unexpected{std::move(plan.error())}; + } + auto budget = std::make_unique( + options.limits.max_owned_memory_bytes); + return Host{ + std::move(options), + std::move(*plan), + EmbeddedResources{}, + std::move(budget)}; + } + + [[nodiscard]] static Void::Result::Result create_embedded( + Options options, EmbeddedResources embedded) + { + options.embedded_mode = true; + if (auto ok = validate_options(options); !ok.has_value()) { + return std::unexpected{std::move(ok.error())}; + } + if (auto eok = embedded.validate(); !eok.has_value()) { + return std::unexpected{std::move(eok.error())}; + } + ResourceGraph g = make_default_resource_graph(true); + auto plan = g.validate_and_plan(); + if (!plan.has_value()) { + return std::unexpected{std::move(plan.error())}; + } + std::unique_ptr budget; + if (embedded.memory_budget == nullptr) { + budget = std::make_unique( + options.limits.max_owned_memory_bytes); + } + return Host{ + std::move(options), + std::move(*plan), + embedded, + std::move(budget)}; + } + + [[nodiscard]] HostState state() const noexcept { return state_; } + [[nodiscard]] bool is_running() const noexcept { return state_ == HostState::running; } + [[nodiscard]] std::size_t started_worker_count() const noexcept { return started_workers_; } + [[nodiscard]] const Options& options() const noexcept { return options_; } + [[nodiscard]] const LifecyclePlan& lifecycle_plan() const noexcept { return plan_; } + [[nodiscard]] const EmbeddedResources& embedded_resources() const noexcept { return embedded_; } + + [[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept + { + return embedded_.clock ? *embedded_.clock + : Void::Time::SystemMonotonicClock::instance(); + } + + [[nodiscard]] Void::Memory::BudgetResource& memory_budget() noexcept + { + return embedded_.memory_budget ? *embedded_.memory_budget : *owned_budget_; + } + +private: + friend class HostBuilder; + + Host(Options options, + LifecyclePlan plan, + EmbeddedResources embedded, + std::unique_ptr owned_budget) noexcept + : options_(std::move(options)) + , plan_(std::move(plan)) + , embedded_(embedded) + , owned_budget_(std::move(owned_budget)) + { + } + + HostState state_{HostState::constructed}; + std::size_t started_workers_{0}; + Options options_{}; + LifecyclePlan plan_{}; + EmbeddedResources embedded_{}; + std::unique_ptr owned_budget_{}; +}; + +class HostBuilder +{ +public: + HostBuilder() + : graph_(make_default_resource_graph(false)) + { + } + + HostBuilder& with_options(Options options) + { + options_ = std::move(options); + if (!embedded_.has_value()) { + graph_ = make_default_resource_graph(options_.embedded_mode); + } + return *this; + } + + HostBuilder& with_embedded(EmbeddedResources embedded) + { + options_.embedded_mode = true; + embedded_ = embedded; + graph_ = make_default_resource_graph(true); + return *this; + } + + [[nodiscard]] Void::Result::Result add_resource(ResourceNode node) + { + return graph_.add_node(std::move(node)); + } + + [[nodiscard]] Void::Result::Result add_dependency( + std::string dependent, std::string dependency, bool required = true) + { + return graph_.add_dependency( + std::move(dependent), std::move(dependency), required); + } + + [[nodiscard]] Void::Result::Result build() const + { + Options opts = options_; + if (embedded_.has_value()) { + opts.embedded_mode = true; + if (auto eok = embedded_->validate(); !eok.has_value()) { + return std::unexpected{std::move(eok.error())}; + } + } + if (auto ok = validate_options(opts); !ok.has_value()) { + return std::unexpected{std::move(ok.error())}; + } + auto plan = graph_.validate_and_plan(); + if (!plan.has_value()) { + return std::unexpected{std::move(plan.error())}; + } + + const EmbeddedResources emb = embedded_.value_or(EmbeddedResources{}); + std::unique_ptr budget; + if (emb.memory_budget == nullptr) { + budget = std::make_unique( + opts.limits.max_owned_memory_bytes); + } + return Host{std::move(opts), std::move(*plan), emb, std::move(budget)}; + } + +private: + Options options_{}; + std::optional embedded_{}; + ResourceGraph graph_; +}; + +} // namespace Void::Runtime \ No newline at end of file diff --git a/include/Void/Runtime/Options.hpp b/include/Void/Runtime/Options.hpp new file mode 100644 index 0000000..3b178b1 --- /dev/null +++ b/include/Void/Runtime/Options.hpp @@ -0,0 +1,168 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Runtime +{ + +inline constexpr std::uint32_t kRuntimeErrorDomain = 11; + +enum class RuntimeErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + not_found = 2, + conflict = 3, + cycle_detected = 4, + invalid_state = 5, + unsupported = 6, + internal = 7 +}; + +[[nodiscard]] inline Void::Result::Error make_runtime_error( + RuntimeErrorCode code, std::string message = {}) +{ + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case RuntimeErrorCode::none: + kind = ErrorKind::internal; + break; + case RuntimeErrorCode::invalid_argument: + kind = ErrorKind::invalid_argument; + break; + case RuntimeErrorCode::not_found: + kind = ErrorKind::not_found; + break; + case RuntimeErrorCode::conflict: + case RuntimeErrorCode::cycle_detected: + case RuntimeErrorCode::invalid_state: + kind = ErrorKind::conflict; + break; + case RuntimeErrorCode::unsupported: + kind = ErrorKind::unsupported; + break; + case RuntimeErrorCode::internal: + kind = ErrorKind::internal; + break; + } + + return Error{ + kind, + std::move(message), + ErrorCode{kRuntimeErrorDomain, static_cast(code)}}; +} + +struct RuntimeLimits { + std::size_t max_cpu_tasks{4096}; + std::size_t max_io_operations{8192}; + std::size_t max_file_queue{256}; + std::size_t max_timers{1024}; + std::size_t max_services{256}; + std::size_t max_owned_memory_bytes{256ULL * 1024ULL * 1024ULL}; +}; + +struct ShutdownPolicy { + std::chrono::milliseconds drain_grace{5000}; + std::chrono::milliseconds export_flush_timeout{5000}; + std::chrono::milliseconds total_timeout{30000}; +}; + +[[nodiscard]] inline std::uint32_t default_cpu_workers() noexcept +{ + const std::uint32_t hw = std::thread::hardware_concurrency(); + return std::clamp(hw, 1u, 8u); +} + +struct Options { + std::uint32_t cpu_workers{default_cpu_workers()}; + std::uint32_t file_workers{4}; + bool embedded_mode{false}; + RuntimeLimits limits{}; + ShutdownPolicy shutdown{}; + IO::BackendOptions io{}; +}; + +[[nodiscard]] inline Void::Result::Result validate_options(const Options& opts) +{ + if (!opts.embedded_mode) { + if (opts.cpu_workers == 0) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "Runtime Options::cpu_workers must be >= 1 in managed mode")}; + } + if (opts.file_workers == 0) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "Runtime Options::file_workers must be >= 1 in managed mode")}; + } + } + + const auto& l = opts.limits; + if (l.max_cpu_tasks == 0 || + l.max_io_operations == 0 || + l.max_file_queue == 0 || + l.max_timers == 0 || + l.max_services == 0 || + l.max_owned_memory_bytes == 0) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "All RuntimeLimits capacity bounds must be non-zero")}; + } + + const auto& s = opts.shutdown; + if (s.drain_grace.count() <= 0 || + s.export_flush_timeout.count() <= 0 || + s.total_timeout.count() <= 0) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "ShutdownPolicy durations must be strictly positive")}; + } + if (s.drain_grace > s.total_timeout || s.export_flush_timeout > s.total_timeout) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "ShutdownPolicy drain_grace and export_flush_timeout must not exceed total_timeout")}; + } + + if (auto io_ok = IO::validate_limits(opts.io.limits); !io_ok.has_value()) { + return std::unexpected{std::move(io_ok.error())}; + } + + // Submodule IO caps cannot exceed global host caps. + if (opts.io.limits.max_operations > l.max_io_operations) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "IO::IoLimits::max_operations exceeds RuntimeLimits::max_io_operations")}; + } + if (opts.io.limits.max_timers > l.max_timers && opts.io.limits.max_timers != 4096) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "IO::IoLimits::max_timers exceeds RuntimeLimits::max_timers")}; + } + if (opts.io.limits.max_file_queue > l.max_file_queue) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "IO::IoLimits::max_file_queue exceeds RuntimeLimits::max_file_queue")}; + } + if (opts.io.limits.max_owned_buffer_bytes > l.max_owned_memory_bytes) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "IO::IoLimits::max_owned_buffer_bytes exceeds RuntimeLimits::max_owned_memory_bytes")}; + } + + return {}; +} + +} // namespace Void::Runtime \ No newline at end of file diff --git a/include/Void/Runtime/ResourceGraph.hpp b/include/Void/Runtime/ResourceGraph.hpp new file mode 100644 index 0000000..a9afd91 --- /dev/null +++ b/include/Void/Runtime/ResourceGraph.hpp @@ -0,0 +1,153 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Runtime +{ + +enum class ResourceOwnership { + owned, + borrowed +}; + +enum class ResourceKind { + clock, + memory_budget, + executor, + io_driver, + service, + exporter, + custom +}; + +struct ResourceNode { + std::string id{}; + ResourceKind kind{ResourceKind::custom}; + ResourceOwnership ownership{ResourceOwnership::owned}; + bool critical{true}; +}; + +struct LifecyclePlan { + std::vector startup_order{}; + std::vector shutdown_order{}; +}; + +class ResourceGraph +{ +public: + [[nodiscard]] Void::Result::Result add_node(ResourceNode node) + { + if (node.id.empty()) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "ResourceGraph node id must not be empty")}; + } + if (index_by_id_.contains(node.id)) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::conflict, + "Duplicate ResourceGraph node id: " + node.id)}; + } + const std::size_t idx = nodes_.size(); + index_by_id_.emplace(node.id, idx); + nodes_.push_back(std::move(node)); + return {}; + } + + // Registers that `dependent` requires `dependency` to start first and stop last. + [[nodiscard]] Void::Result::Result add_dependency( + std::string dependent, std::string dependency, bool required = true) + { + if (dependent.empty() || dependency.empty()) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::invalid_argument, + "ResourceGraph dependency ids must not be empty")}; + } + edges_.push_back(PendingEdge{ + std::move(dependent), std::move(dependency), required}); + return {}; + } + + [[nodiscard]] std::size_t node_count() const noexcept { return nodes_.size(); } + + [[nodiscard]] Void::Result::Result validate_and_plan() const + { + const std::size_t n = nodes_.size(); + std::vector> adj(n); + + for (const auto& e : edges_) { + const auto dep_it = index_by_id_.find(e.dependent); + if (dep_it == index_by_id_.end()) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::not_found, + "Unknown dependent node in ResourceGraph: " + e.dependent)}; + } + const auto target_it = index_by_id_.find(e.dependency); + if (target_it == index_by_id_.end()) { + if (e.required) { + return std::unexpected{make_runtime_error( + RuntimeErrorCode::not_found, + "Missing required dependency '" + e.dependency + + "' for resource '" + e.dependent + "'")}; + } + continue; + } + const std::size_t from = target_it->second; // dependency starts first + const std::size_t to = dep_it->second; // dependent starts after + if (std::find(adj[from].begin(), adj[from].end(), to) == adj[from].end()) { + adj[from].push_back(to); + } + } + + const Void::Algorithms::AdjacencyView view{adj}; + const auto topo = Void::Algorithms::topological_order(view); + if (!topo.has_value()) { + if (topo.error().code == Void::Algorithms::AlgorithmError::Code::cycle_detected) { + std::string witness; + for (std::size_t i = 0; i < topo.error().cycle.size(); ++i) { + if (i > 0) { + witness += " -> "; + } + const std::size_t idx = topo.error().cycle[i]; + witness += (idx < nodes_.size()) ? nodes_[idx].id : "?"; + } + return std::unexpected{make_runtime_error( + RuntimeErrorCode::cycle_detected, + "ResourceGraph dependency cycle detected: " + witness)}; + } + return std::unexpected{make_runtime_error( + RuntimeErrorCode::internal, topo.error().message)}; + } + + LifecyclePlan plan; + plan.startup_order.reserve(n); + for (const std::size_t idx : topo->order) { + plan.startup_order.push_back(nodes_[idx].id); + } + plan.shutdown_order = plan.startup_order; + std::reverse(plan.shutdown_order.begin(), plan.shutdown_order.end()); + return plan; + } + +private: + struct PendingEdge { + std::string dependent; + std::string dependency; + bool required{true}; + }; + + std::vector nodes_{}; + std::unordered_map index_by_id_{}; + std::vector edges_{}; +}; + +} // namespace Void::Runtime \ No newline at end of file diff --git a/src/Runtime/module.cmake b/src/Runtime/module.cmake new file mode 100644 index 0000000..e456ab3 --- /dev/null +++ b/src/Runtime/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Runtime + INTERNAL_DEPS Core Functional Time Memory Algorithms Async IO +) \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 523e78c..33eddf8 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -111,6 +111,11 @@ if(_has_io) run_consumer(IOOnly "${install_prefix}" "IOOnly" ${_no_external_deps}) endif() +has_modules(_has_runtime Runtime IO Async Algorithms Memory Time Functional Core) +if(_has_runtime) + run_consumer(RuntimeOnly "${install_prefix}" "RuntimeOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/RuntimeOnly/CMakeLists.txt b/tests/package/RuntimeOnly/CMakeLists.txt new file mode 100644 index 0000000..a3c3bba --- /dev/null +++ b/tests/package/RuntimeOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidRuntimeOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Runtime) + +add_executable(void_runtime_only_consumer main.cpp) +target_link_libraries(void_runtime_only_consumer PRIVATE Void::Runtime) + +enable_testing() +add_test(NAME VoidRuntimeOnlyConsumer COMMAND void_runtime_only_consumer) \ No newline at end of file diff --git a/tests/package/RuntimeOnly/main.cpp b/tests/package/RuntimeOnly/main.cpp new file mode 100644 index 0000000..3bef84a --- /dev/null +++ b/tests/package/RuntimeOnly/main.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +int main() +{ + auto host = Void::Runtime::Host::create(); + if (!host.has_value() || + host->state() != Void::Runtime::HostState::constructed || + host->started_worker_count() != 0) { + return 1; + } + + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + auto drv = Void::IO::Driver::create( + exec, Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::mock}, clock); + if (!drv.has_value()) { + return 1; + } + auto emb = Void::Runtime::Host::create_embedded( + Void::Runtime::Options{}, + Void::Runtime::EmbeddedResources{ + .executor = &exec, + .io = drv->get(), + .clock = &clock, + }); + return (emb.has_value() && emb->options().embedded_mode) ? 0 : 1; +} \ No newline at end of file diff --git a/tests/standalone/Runtime/RuntimeHost.cpp b/tests/standalone/Runtime/RuntimeHost.cpp new file mode 100644 index 0000000..f4a5410 --- /dev/null +++ b/tests/standalone/Runtime/RuntimeHost.cpp @@ -0,0 +1,193 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +Void::Testing::Test runtime_options_validation_and_default_caps() +{ + using namespace Void::Runtime; + + const Options defaults{}; + Void::Testing::expect(validate_options(defaults).has_value()); + Void::Testing::expect(defaults.cpu_workers >= 1 && defaults.cpu_workers <= 8); + Void::Testing::expect_eq(defaults.file_workers, std::uint32_t{4}); + Void::Testing::expect_eq(defaults.limits.max_cpu_tasks, std::size_t{4096}); + Void::Testing::expect_eq(defaults.limits.max_io_operations, std::size_t{8192}); + Void::Testing::expect_eq(defaults.limits.max_file_queue, std::size_t{256}); + Void::Testing::expect_eq(defaults.limits.max_timers, std::size_t{1024}); + Void::Testing::expect_eq(defaults.limits.max_services, std::size_t{256}); + Void::Testing::expect_eq( + defaults.limits.max_owned_memory_bytes, std::size_t{256ULL * 1024ULL * 1024ULL}); + + // Zero cpu_workers or file_workers rejected in managed mode + Options zero_cpu = defaults; + zero_cpu.cpu_workers = 0; + Void::Testing::expect(!validate_options(zero_cpu).has_value()); + + Options zero_file = defaults; + zero_file.file_workers = 0; + Void::Testing::expect(!validate_options(zero_file).has_value()); + + // Zero limits rejected even in embedded mode + Options zero_limit = defaults; + zero_limit.embedded_mode = true; + zero_limit.cpu_workers = 0; + zero_limit.file_workers = 0; + zero_limit.limits.max_cpu_tasks = 0; + Void::Testing::expect(!validate_options(zero_limit).has_value()); + + // Invalid shutdown timings rejected + Options bad_shutdown = defaults; + bad_shutdown.shutdown.drain_grace = std::chrono::milliseconds{40000}; + Void::Testing::expect(!validate_options(bad_shutdown).has_value()); + + Options zero_grace = defaults; + zero_grace.shutdown.drain_grace = std::chrono::milliseconds{0}; + Void::Testing::expect(!validate_options(zero_grace).has_value()); + + // Submodule IO caps exceeding global host caps rejected + Options bad_io_ops = defaults; + bad_io_ops.io.limits.max_operations = bad_io_ops.limits.max_io_operations + 1; + Void::Testing::expect(!validate_options(bad_io_ops).has_value()); + + Options bad_io_mem = defaults; + bad_io_mem.limits.max_owned_memory_bytes = 1024; + bad_io_mem.io.limits.max_owned_buffer_bytes = 2048; + Void::Testing::expect(!validate_options(bad_io_mem).has_value()); +} + +Void::Testing::Test runtime_inert_host_and_embedded_ports() +{ + using namespace Void::Runtime; + + // Host::create starts zero threads and stays constructed/inert + auto host_res = Host::create(); + Void::Testing::require(host_res.has_value()); + Void::Testing::expect(host_res->state() == HostState::constructed); + Void::Testing::expect(!host_res->is_running()); + Void::Testing::expect_eq(host_res->started_worker_count(), std::size_t{0}); + + const auto& order = host_res->lifecycle_plan().startup_order; + const auto& rev = host_res->lifecycle_plan().shutdown_order; + Void::Testing::require(order.size() == 4); + Void::Testing::expect_eq(order.size(), rev.size()); + for (std::size_t i = 0; i < order.size(); ++i) { + Void::Testing::expect_eq(order[i], rev[rev.size() - 1 - i]); + } + const auto idx_of = [&](std::string_view id) { + return static_cast( + std::find(order.begin(), order.end(), id) - order.begin()); + }; + Void::Testing::expect(idx_of("clock") < idx_of("executor")); + Void::Testing::expect(idx_of("memory_budget") < idx_of("executor")); + Void::Testing::expect(idx_of("executor") < idx_of("io_driver")); + + // Embedded validation rejects null executor, null IO driver, or null clock + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + Void::Memory::BudgetResource budget{1024 * 1024}; + auto drv_res = Void::IO::Driver::create( + exec, Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::mock}, clock); + Void::Testing::require(drv_res.has_value()); + + Void::Testing::expect( + !Host::create_embedded(Options{}, EmbeddedResources{.io = drv_res->get()}).has_value()); + Void::Testing::expect( + !Host::create_embedded(Options{}, EmbeddedResources{.executor = &exec}).has_value()); + Void::Testing::expect( + !Host::create_embedded( + Options{}, + EmbeddedResources{.executor = &exec, .io = drv_res->get(), .clock = nullptr}) + .has_value()); + + auto emb_host = Host::create_embedded( + Options{}, + EmbeddedResources{ + .executor = &exec, + .io = drv_res->get(), + .clock = &clock, + .memory_budget = &budget, + }); + Void::Testing::require(emb_host.has_value()); + Void::Testing::expect(emb_host->state() == HostState::constructed); + Void::Testing::expect(emb_host->options().embedded_mode); + Void::Testing::expect(&emb_host->clock() == &clock); + Void::Testing::expect(&emb_host->memory_budget() == &budget); +} + +Void::Testing::Test runtime_resource_graph_planning_and_cycle_detection() +{ + using namespace Void::Runtime; + + // Builder adds exporter -> io_driver and service -> {executor, exporter} + HostBuilder builder; + Void::Testing::require( + builder.add_resource(ResourceNode{"exporter", ResourceKind::exporter}).has_value()); + Void::Testing::require( + builder.add_resource(ResourceNode{"service_a", ResourceKind::service}).has_value()); + Void::Testing::require(builder.add_dependency("exporter", "io_driver").has_value()); + Void::Testing::require(builder.add_dependency("service_a", "executor").has_value()); + Void::Testing::require(builder.add_dependency("service_a", "exporter").has_value()); + // Optional dependency on an absent optional metrics sink is permitted cleanly + Void::Testing::require( + builder.add_dependency("service_a", "optional_metrics", false).has_value()); + + auto built = builder.build(); + Void::Testing::require(built.has_value()); + const auto& up = built->lifecycle_plan().startup_order; + const auto& down = built->lifecycle_plan().shutdown_order; + const auto pos_up = [&](std::string_view id) { + return static_cast(std::find(up.begin(), up.end(), id) - up.begin()); + }; + const auto pos_down = [&](std::string_view id) { + return static_cast(std::find(down.begin(), down.end(), id) - down.begin()); + }; + Void::Testing::expect(pos_up("io_driver") < pos_up("exporter")); + Void::Testing::expect(pos_up("exporter") < pos_up("service_a")); + // Shutdown stops service_a BEFORE exporter, and exporter BEFORE io_driver / executor! + Void::Testing::expect(pos_down("service_a") < pos_down("exporter")); + Void::Testing::expect(pos_down("exporter") < pos_down("io_driver")); + + // Duplicate node id rejected + ResourceGraph dup_g; + Void::Testing::require(dup_g.add_node(ResourceNode{"svc", ResourceKind::service}).has_value()); + const auto dup_err = dup_g.add_node(ResourceNode{"svc", ResourceKind::service}); + Void::Testing::expect(!dup_err.has_value()); + Void::Testing::expect( + dup_err.error().code().value == static_cast(RuntimeErrorCode::conflict)); + + // Missing required dependency rejected + ResourceGraph missing_g; + Void::Testing::require( + missing_g.add_node(ResourceNode{"svc", ResourceKind::service}).has_value()); + Void::Testing::require(missing_g.add_dependency("svc", "missing_dep", true).has_value()); + const auto miss_err = missing_g.validate_and_plan(); + Void::Testing::expect(!miss_err.has_value()); + Void::Testing::expect( + miss_err.error().code().value == static_cast(RuntimeErrorCode::not_found)); + + // Dependency cycle detected with readable node witness + ResourceGraph cyc_g; + Void::Testing::require(cyc_g.add_node(ResourceNode{"alpha", ResourceKind::service}).has_value()); + Void::Testing::require(cyc_g.add_node(ResourceNode{"beta", ResourceKind::exporter}).has_value()); + Void::Testing::require(cyc_g.add_dependency("alpha", "beta").has_value()); + Void::Testing::require(cyc_g.add_dependency("beta", "alpha").has_value()); + const auto cyc_err = cyc_g.validate_and_plan(); + Void::Testing::expect(!cyc_err.has_value()); + Void::Testing::expect( + cyc_err.error().code().value == + static_cast(RuntimeErrorCode::cycle_detected)); + Void::Testing::expect(cyc_err.error().message().find("alpha") != std::string::npos); + Void::Testing::expect(cyc_err.error().message().find("beta") != std::string::npos); +} \ No newline at end of file From de8a981893d8f73d3511e08737fa815359dfa1ce Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 09:36:59 +0300 Subject: [PATCH 4/5] feat(Testing): add per-run owned reporters, strict config validation, FailureCapture, subprocess isolation, and deterministic property/schedule harness (M-TESTING-02, M-TESTING-03) --- include/Void/Testing/Assert.hpp | 2 + include/Void/Testing/Capture.hpp | 110 ++++ include/Void/Testing/Config.hpp | 11 + include/Void/Testing/Deterministic.hpp | 494 ++++++++++++++++++ include/Void/Testing/Runner.hpp | 1 + include/Void/Testing/Subprocess.hpp | 43 ++ src/Testing/Assert.cpp | 68 ++- src/Testing/Runner.cpp | 313 +++++++++-- src/Testing/Subprocess.cpp | 307 +++++++++++ tests/standalone/Testing/Deterministic.cpp | 155 ++++++ .../standalone/Testing/FrameworkHardening.cpp | 263 ++++++++++ 11 files changed, 1712 insertions(+), 55 deletions(-) create mode 100644 include/Void/Testing/Capture.hpp create mode 100644 include/Void/Testing/Deterministic.hpp create mode 100644 include/Void/Testing/Subprocess.hpp create mode 100644 src/Testing/Subprocess.cpp create mode 100644 tests/standalone/Testing/Deterministic.cpp create mode 100644 tests/standalone/Testing/FrameworkHardening.cpp diff --git a/include/Void/Testing/Assert.hpp b/include/Void/Testing/Assert.hpp index 443366d..9c774cf 100644 --- a/include/Void/Testing/Assert.hpp +++ b/include/Void/Testing/Assert.hpp @@ -44,6 +44,8 @@ namespace Void::Testing::Detail } void handle_assertion(AssertionResult result); + [[nodiscard]] std::size_t stray_assertion_count() noexcept; + void reset_stray_assertion_count() noexcept; struct RequireFailure : std::runtime_error { using std::runtime_error::runtime_error; diff --git a/include/Void/Testing/Capture.hpp b/include/Void/Testing/Capture.hpp new file mode 100644 index 0000000..853a68f --- /dev/null +++ b/include/Void/Testing/Capture.hpp @@ -0,0 +1,110 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Testing +{ + +// Captures Void::Testing assertions and Require/exception aborts within a +// bounded local TestResult without mutating any enclosing active test context. +class FailureCapture +{ +public: + FailureCapture() noexcept + : prev_result_(Detail::TestContext::current().current_result) + , prev_should_abort_(Detail::TestContext::current().should_abort) + { + Detail::TestContext::current().current_result = &local_; + Detail::TestContext::current().should_abort = false; + } + + ~FailureCapture() + { + Detail::TestContext::current().current_result = prev_result_; + Detail::TestContext::current().should_abort = prev_should_abort_; + } + + FailureCapture(const FailureCapture&) = delete; + FailureCapture& operator=(const FailureCapture&) = delete; + FailureCapture(FailureCapture&&) = delete; + FailureCapture& operator=(FailureCapture&&) = delete; + + template + [[nodiscard]] bool run(Fn&& fn) + { + local_ = TestResult{}; + try { + std::forward(fn)(); + } catch (const Detail::RequireFailure&) { + if (local_.state != TestState::Skipped) { + local_.state = TestState::Failed; + } + } catch (const std::exception& e) { + local_.state = TestState::Failed; + local_.crash_info = std::string{"Unhandled exception: "} + e.what(); + } catch (...) { + local_.state = TestState::Failed; + local_.crash_info = "Unhandled unknown exception"; + } + + if (local_.state != TestState::Skipped) { + bool any_fail = !local_.crash_info.empty(); + if (!any_fail) { + for (const auto& a : local_.assertions) { + if (!a.passed) { + any_fail = true; + break; + } + } + } + if (any_fail) { + local_.state = TestState::Failed; + } + } + return passed(); + } + + [[nodiscard]] bool passed() const noexcept + { + return local_.state == TestState::Passed; + } + + [[nodiscard]] bool failed() const noexcept + { + return local_.state == TestState::Failed || local_.state == TestState::Crashed; + } + + [[nodiscard]] bool skipped() const noexcept + { + return local_.state == TestState::Skipped; + } + + [[nodiscard]] bool aborted() const noexcept + { + return local_.state == TestState::Failed && !local_.assertions.empty() && + (local_.assertions.back().kind == AssertKind::Require || + local_.assertions.back().kind == AssertKind::Assert); + } + + [[nodiscard]] bool truncated() const noexcept { return local_.assertions_truncated; } + [[nodiscard]] std::size_t dropped_assertions() const noexcept { return local_.dropped_assertions; } + [[nodiscard]] const std::vector& assertions() const noexcept + { + return local_.assertions; + } + [[nodiscard]] const TestResult& result() const noexcept { return local_; } + +private: + TestResult* prev_result_{nullptr}; + bool prev_should_abort_{false}; + TestResult local_{}; +}; + +} // namespace Void::Testing \ No newline at end of file diff --git a/include/Void/Testing/Config.hpp b/include/Void/Testing/Config.hpp index 33b508a..81e3d70 100644 --- a/include/Void/Testing/Config.hpp +++ b/include/Void/Testing/Config.hpp @@ -12,6 +12,9 @@ namespace Void::Testing { + inline constexpr std::size_t kMaxRetainedAssertionsPerTest = 1000; + inline constexpr std::size_t kMaxDiagnosticBytesPerTest = 1024ULL * 1024ULL; + enum class AssertKind : uint8_t { Expect, Require, Assert }; enum class TestState : uint8_t { Passed, Failed, Skipped, Crashed }; @@ -55,6 +58,10 @@ namespace Void::Testing std::string crash_info; std::string stacktrace; std::vector tags; + bool assertions_truncated{false}; + std::size_t dropped_assertions{0}; + std::size_t diagnostic_bytes{0}; + std::string cleanup_error; }; struct SuiteResult { @@ -70,6 +77,7 @@ namespace Void::Testing int skipped{0}; int crashed{0}; int total{0}; + std::string config_error; }; struct RunConfig { @@ -84,9 +92,12 @@ namespace Void::Testing bool no_color{false}; bool shuffle{false}; bool show_help{false}; + bool allow_empty{false}; unsigned repeat{1}; unsigned random_seed{0}; unsigned parallel_threads{0}; // 0 = sequential + std::string parse_error; + std::string selftest_child; }; } // namespace Void::Testing diff --git a/include/Void/Testing/Deterministic.hpp b/include/Void/Testing/Deterministic.hpp new file mode 100644 index 0000000..838b5dd --- /dev/null +++ b/include/Void/Testing/Deterministic.hpp @@ -0,0 +1,494 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Testing +{ + +struct ReplayToken { + std::uint64_t seed{0x9E3779B97F4A7C15ULL}; + std::uint32_t generator_version{1}; + std::uint64_t case_index{0}; + + [[nodiscard]] constexpr bool operator==(const ReplayToken&) const noexcept = default; +}; + +// Frozen version-1 deterministic PRNG backed by SplitMix64 seeding + mt19937_64 +// with standard-library-independent unbiased rejection sampling. +class DeterministicRng +{ +public: + explicit DeterministicRng(ReplayToken token) noexcept + : token_(token) + , engine_(mix_seed_v1(token.seed, token.case_index)) + { + } + + [[nodiscard]] static constexpr std::uint64_t mix_seed_v1( + std::uint64_t seed, std::uint64_t case_index) noexcept + { + std::uint64_t z = seed ^ (case_index * 0x9E3779B97F4A7C15ULL); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; + return z ^ (z >> 31); + } + + [[nodiscard]] const ReplayToken& token() const noexcept { return token_; } + + [[nodiscard]] std::uint64_t next_u64() noexcept + { + return engine_(); + } + + // Returns uniform integer in [0, bound - 1] via rejection sampling. + [[nodiscard]] std::uint64_t next_bounded(std::uint64_t bound) noexcept + { + if (bound <= 1) { + return 0; + } + const std::uint64_t threshold = (0ULL - bound) % bound; + for (;;) { + const std::uint64_t r = next_u64(); + if (r >= threshold) { + return r % bound; + } + } + } + + [[nodiscard]] std::int64_t next_int(std::int64_t lo, std::int64_t hi) noexcept + { + if (lo >= hi) { + return lo; + } + const std::uint64_t ulo = static_cast(lo); + const std::uint64_t uhi = static_cast(hi); + const std::uint64_t span = uhi - ulo; + if (span == std::numeric_limits::max()) { + return static_cast(next_u64()); + } + const std::uint64_t pick = next_bounded(span + 1ULL); + return static_cast(ulo + pick); + } + + [[nodiscard]] bool next_bool() noexcept + { + return (next_u64() & 1ULL) != 0ULL; + } + + [[nodiscard]] std::vector next_bytes(std::size_t max_len) + { + const std::size_t len = + static_cast(next_bounded(max_len + 1ULL)); + std::vector out(len); + for (std::size_t i = 0; i < len; ++i) { + out[i] = static_cast(next_u64() & 0xFFULL); + } + return out; + } + + [[nodiscard]] std::vector next_ints( + std::size_t max_len, int lo, int hi) + { + const std::size_t len = + static_cast(next_bounded(max_len + 1ULL)); + std::vector out; + out.reserve(len); + for (std::size_t i = 0; i < len; ++i) { + out.push_back(static_cast(next_int(lo, hi))); + } + return out; + } + +private: + ReplayToken token_{}; + std::mt19937_64 engine_; +}; + +enum class PropertyStatus { + passed, + failed, + inconclusive +}; + +struct PropertyOptions { + unsigned cases{256}; + unsigned max_size{64}; + unsigned max_shrinks{1000}; + unsigned max_steps{10000}; + unsigned max_discard_factor{10}; + std::chrono::nanoseconds time_budget{std::chrono::seconds{5}}; +}; + +template +struct PropertyResult { + PropertyStatus status{PropertyStatus::passed}; + ReplayToken replay{}; + unsigned cases_executed{0}; + unsigned discards{0}; + unsigned shrink_steps{0}; + std::optional original_failure{}; + std::optional minimal_failure{}; + std::vector shrink_path{}; + std::string message{}; +}; + +namespace Detail +{ +template +struct UnwrapOptional { + using type = T; + static constexpr bool is_optional = false; +}; + +template +struct UnwrapOptional> { + using type = U; + static constexpr bool is_optional = true; +}; + +[[nodiscard]] inline std::chrono::nanoseconds elapsed_since( + const Void::Time::MonotonicClock& clock, + Void::Time::MonotonicClock::time_point start) noexcept +{ + const auto now = clock.now(); + return (now > start) + ? std::chrono::duration_cast(now - start) + : std::chrono::nanoseconds{0}; +} +} // namespace Detail + +template + requires std::invocable< + ShrinkFn, + const typename Detail::UnwrapOptional< + std::remove_cvref_t>>::type&> +[[nodiscard]] auto check_property( + GeneratorFn&& gen, + PredicateFn&& pred, + ShrinkFn&& shrink, + const PropertyOptions& opts = {}, + ReplayToken base_token = {}, + const Void::Time::MonotonicClock* clock = nullptr) +{ + using GenRaw = std::remove_cvref_t>; + using T = typename Detail::UnwrapOptional::type; + + PropertyResult result; + result.replay = base_token; + + if (base_token.generator_version != 1) { + result.status = PropertyStatus::inconclusive; + result.message = "Unsupported ReplayToken generator_version"; + return result; + } + + const Void::Time::MonotonicClock& clk = + clock ? *clock : Void::Time::SystemMonotonicClock::instance(); + const auto start_tp = clk.now(); + unsigned total_steps = 0; + const unsigned max_discards = + (opts.cases == 0 || opts.max_discard_factor == 0) + ? 0 + : (opts.cases <= std::numeric_limits::max() / opts.max_discard_factor + ? opts.cases * opts.max_discard_factor + : std::numeric_limits::max()); + + for (unsigned case_idx = 0; + result.cases_executed < opts.cases; + ++case_idx) { + if (total_steps >= opts.max_steps || + Detail::elapsed_since(clk, start_tp) >= opts.time_budget) { + result.status = PropertyStatus::inconclusive; + result.message = "Property step or time budget exhausted"; + return result; + } + ++total_steps; + + ReplayToken case_tok{base_token.seed, base_token.generator_version, case_idx}; + DeterministicRng rng{case_tok}; + std::optional value_opt; + if constexpr (Detail::UnwrapOptional::is_optional) { + value_opt = std::forward(gen)(rng); + } else { + value_opt.emplace(std::forward(gen)(rng)); + } + + if (!value_opt.has_value()) { + ++result.discards; + if (result.discards > max_discards) { + result.status = PropertyStatus::inconclusive; + result.message = "Property generator discard budget exceeded"; + return result; + } + continue; + } + + using PredRaw = std::remove_cvref_t>; + std::optional ok; + if constexpr (Detail::UnwrapOptional::is_optional) { + ok = std::forward(pred)(*value_opt); + } else { + ok = static_cast(std::forward(pred)(*value_opt)); + } + + if (!ok.has_value()) { + ++result.discards; + if (result.discards > max_discards) { + result.status = PropertyStatus::inconclusive; + result.message = "Property precondition discard budget exceeded"; + return result; + } + continue; + } + + ++result.cases_executed; + if (*ok) { + continue; + } + + result.status = PropertyStatus::failed; + result.replay = case_tok; + result.original_failure = *value_opt; + result.minimal_failure = std::move(*value_opt); + result.message = "Property falsified"; + + // Deterministic shrinking up to max_shrinks / max_steps / time_budget. + while (result.shrink_steps < opts.max_shrinks && + total_steps < opts.max_steps && + Detail::elapsed_since(clk, start_tp) < opts.time_budget) { + const auto candidates = shrink(*result.minimal_failure); + bool shrunk_once = false; + for (const auto& cand : candidates) { + if (total_steps >= opts.max_steps || + Detail::elapsed_since(clk, start_tp) >= opts.time_budget) { + break; + } + ++total_steps; + std::optional cand_ok; + if constexpr (Detail::UnwrapOptional::is_optional) { + cand_ok = pred(cand); + } else { + cand_ok = static_cast(pred(cand)); + } + if (cand_ok.has_value() && !(*cand_ok)) { + result.minimal_failure = cand; + result.shrink_path.push_back(cand); + ++result.shrink_steps; + shrunk_once = true; + break; + } + } + if (!shrunk_once) { + break; + } + } + return result; + } + + result.status = PropertyStatus::passed; + return result; +} + +template +[[nodiscard]] auto check_property( + GeneratorFn&& gen, + PredicateFn&& pred, + const PropertyOptions& opts = {}, + ReplayToken base_token = {}, + const Void::Time::MonotonicClock* clock = nullptr) +{ + using GenRaw = std::remove_cvref_t>; + using T = typename Detail::UnwrapOptional::type; + auto no_shrink = [](const T&) -> std::vector { return {}; }; + return check_property( + std::forward(gen), + std::forward(pred), + no_shrink, + opts, + base_token, + clock); +} + +template +[[nodiscard]] bool replay_property_case( + GeneratorFn&& gen, + PredicateFn&& pred, + ReplayToken token) +{ + DeterministicRng rng{token}; + auto val = std::forward(gen)(rng); + return static_cast(std::forward(pred)(val)); +} + +struct ScheduleEvent { + std::uint64_t step{0}; + std::uint64_t action_id{0}; + std::string label{}; + std::int64_t clock_ns{0}; + std::size_t choice_index{0}; + std::size_t ready_count{0}; +}; + +// Deterministic single-step action & timer harness using Void::Time::ManualClock. +class DeterministicRun +{ +public: + explicit DeterministicRun(Void::Time::ManualClock::time_point initial = {}) noexcept + : clock_(initial) + { + } + + [[nodiscard]] const Void::Time::ManualClock& clock() const noexcept { return clock_; } + [[nodiscard]] Void::Time::ManualClock& clock() noexcept { return clock_; } + + std::uint64_t schedule(std::string label, std::function fn) + { + const std::uint64_t id = next_id_++; + ready_.push_back(Action{id, std::move(label), std::move(fn)}); + return id; + } + + std::uint64_t schedule_after( + std::chrono::nanoseconds delay, + std::string label, + std::function fn) + { + const std::uint64_t id = next_id_++; + const auto fire_at = + (delay.count() <= 0) ? clock_.now() : (clock_.now() + delay); + if (fire_at <= clock_.now()) { + ready_.push_back(Action{id, std::move(label), std::move(fn)}); + return id; + } + timers_.push_back(Timer{fire_at, id, std::move(label), std::move(fn)}); + return id; + } + + std::size_t advance_clock(std::chrono::nanoseconds delta) + { + (void)clock_.advance(delta); + return promote_due_timers(); + } + + bool step() + { + return step_choice(0); + } + + bool step_choice(std::size_t ready_index) + { + (void)promote_due_timers(); + if (ready_.empty() || ready_index >= ready_.size()) { + return false; + } + const std::size_t rc = ready_.size(); + Action act = std::move(ready_[ready_index]); + ready_.erase(ready_.begin() + static_cast(ready_index)); + + const std::int64_t now_ns = + std::chrono::duration_cast( + clock_.now().time_since_epoch()) + .count(); + trace_.push_back(ScheduleEvent{ + .step = next_step_++, + .action_id = act.id, + .label = act.label, + .clock_ns = now_ns, + .choice_index = ready_index, + .ready_count = rc, + }); + if (act.fn) { + act.fn(); + } + return true; + } + + [[nodiscard]] std::expected + run_until_idle(std::size_t max_steps = 10000) + { + std::size_t ran = 0; + for (;;) { + (void)promote_due_timers(); + if (ready_.empty()) { + return ran; + } + if (ran >= max_steps) { + return std::unexpected{ + "DeterministicRun exceeded max_steps limit"}; + } + if (!step()) { + return ran; + } + ++ran; + } + } + + [[nodiscard]] std::size_t ready_count() const noexcept { return ready_.size(); } + [[nodiscard]] std::size_t timer_count() const noexcept { return timers_.size(); } + [[nodiscard]] const std::vector& trace() const noexcept { return trace_; } + +private: + struct Action { + std::uint64_t id{0}; + std::string label{}; + std::function fn{}; + }; + + struct Timer { + Void::Time::ManualClock::time_point fire_at{}; + std::uint64_t id{0}; + std::string label{}; + std::function fn{}; + }; + + std::size_t promote_due_timers() + { + const auto now = clock_.now(); + std::vector due; + std::vector remaining; + remaining.reserve(timers_.size()); + for (auto& t : timers_) { + if (t.fire_at <= now) { + due.push_back(std::move(t)); + } else { + remaining.push_back(std::move(t)); + } + } + timers_ = std::move(remaining); + std::sort(due.begin(), due.end(), [](const Timer& a, const Timer& b) { + if (a.fire_at != b.fire_at) { + return a.fire_at < b.fire_at; + } + return a.id < b.id; + }); + for (auto& t : due) { + ready_.push_back(Action{t.id, std::move(t.label), std::move(t.fn)}); + } + return due.size(); + } + + Void::Time::ManualClock clock_; + std::uint64_t next_id_{1}; + std::uint64_t next_step_{0}; + std::deque ready_{}; + std::vector timers_{}; + std::vector trace_{}; +}; + +} // namespace Void::Testing \ No newline at end of file diff --git a/include/Void/Testing/Runner.hpp b/include/Void/Testing/Runner.hpp index 8073e53..b55a68e 100644 --- a/include/Void/Testing/Runner.hpp +++ b/include/Void/Testing/Runner.hpp @@ -16,6 +16,7 @@ namespace Void::Testing } RunConfig parse_args(int argc, char** argv); RunResult run(const RunConfig& config); + TestResult execute_case(TestCase& test_case); int main(int argc, char** argv); private: diff --git a/include/Void/Testing/Subprocess.hpp b/include/Void/Testing/Subprocess.hpp new file mode 100644 index 0000000..72c01f8 --- /dev/null +++ b/include/Void/Testing/Subprocess.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Void::Testing +{ + +struct ProcessTestOptions { + std::chrono::milliseconds timeout{60000}; + std::size_t max_output_bytes{1024ULL * 1024ULL}; +}; + +enum class ProcessOutcome { + passed, + failed, + crashed, + timed_out, + infrastructure_error +}; + +struct ProcessTestResult { + ProcessOutcome outcome{ProcessOutcome::infrastructure_error}; + int exit_code{-1}; + int term_signal{0}; + std::string stdout_captured{}; + std::string stderr_captured{}; + bool stdout_truncated{false}; + bool stderr_truncated{false}; + std::string diagnostic{}; +}; + +[[nodiscard]] std::string current_executable_path(); + +[[nodiscard]] ProcessTestResult run_isolated_subprocess( + std::string_view executable, + std::span args = {}, + ProcessTestOptions options = {}); + +} // namespace Void::Testing \ No newline at end of file diff --git a/src/Testing/Assert.cpp b/src/Testing/Assert.cpp index b4f7214..66d99e2 100644 --- a/src/Testing/Assert.cpp +++ b/src/Testing/Assert.cpp @@ -1,17 +1,59 @@ #include -namespace Void::Testing::Detail { -void handle_assertion(AssertionResult result) { + +#include + +namespace Void::Testing::Detail +{ +namespace +{ +std::atomic g_stray_assertions{0}; +} // namespace + +std::size_t stray_assertion_count() noexcept +{ + return g_stray_assertions.load(std::memory_order_acquire); +} + +void reset_stray_assertion_count() noexcept +{ + g_stray_assertions.store(0, std::memory_order_release); +} + +void handle_assertion(AssertionResult result) +{ auto& ctx = TestContext::current(); - if (ctx.current_result) { - ctx.current_result->assertions.push_back(std::move(result)); - const auto& last = ctx.current_result->assertions.back(); - if (!last.passed) { - ctx.current_result->state = TestState::Failed; - if (last.kind == AssertKind::Require || last.kind == AssertKind::Assert) { - ctx.should_abort = true; - throw RequireFailure{last.message}; - } - } + if (!ctx.current_result) { + g_stray_assertions.fetch_add(1, std::memory_order_acq_rel); + return; + } + + TestResult* tr = ctx.current_result; + const bool passed = result.passed; + const AssertKind kind = result.kind; + std::string abort_msg = result.message; + + if (!passed) { + tr->state = TestState::Failed; + } + + const std::size_t entry_bytes = + result.expression.size() + + result.expected_repr.size() + + result.actual_repr.size() + + result.message.size() + 64; + + if (tr->assertions.size() < kMaxRetainedAssertionsPerTest && + tr->diagnostic_bytes + entry_bytes <= kMaxDiagnosticBytesPerTest) { + tr->diagnostic_bytes += entry_bytes; + tr->assertions.push_back(std::move(result)); + } else { + tr->assertions_truncated = true; + tr->dropped_assertions += 1; + } + + if (!passed && (kind == AssertKind::Require || kind == AssertKind::Assert)) { + ctx.should_abort = true; + throw RequireFailure{abort_msg}; } } -} // namespace Void::Testing::Detail +} // namespace Void::Testing::Detail \ No newline at end of file diff --git a/src/Testing/Runner.cpp b/src/Testing/Runner.cpp index da386a0..53bc159 100644 --- a/src/Testing/Runner.cpp +++ b/src/Testing/Runner.cpp @@ -37,50 +37,146 @@ #endif #include +#include #include +#include #include #include #include +#include #include #include #include +#include #include namespace Void::Testing { + namespace + { + class OwningJUnitReporter final : public Reporter + { + public: + OwningJUnitReporter(std::unique_ptr stream, + std::string* write_err_out) + : stream_(std::move(stream)) + , inner_(*stream_) + , write_err_out_(write_err_out) + { + } + + void on_run_start(const RunConfig& c, int n) override { inner_.on_run_start(c, n); } + void on_suite_start(const std::string& s, int n) override { inner_.on_suite_start(s, n); } + void on_test_start(const TestCase& t) override { inner_.on_test_start(t); } + void on_test_end(const TestResult& r) override { inner_.on_test_end(r); } + void on_suite_end(const SuiteResult& s) override { inner_.on_suite_end(s); } + void on_run_end(const RunResult& r) override + { + inner_.on_run_end(r); + if (stream_) { + stream_->flush(); + if (!stream_->good() && write_err_out_ != nullptr && + write_err_out_->empty()) { + *write_err_out_ = "Failed while writing JUnit report"; + } + } + } + + private: + std::unique_ptr stream_; + JUnitReporter inner_; + std::string* write_err_out_{nullptr}; + }; + + struct ContextRestorer { + Detail::TestContext saved; + ContextRestorer() : saved(Detail::TestContext::current()) {} + ~ContextRestorer() { Detail::TestContext::current() = saved; } + ContextRestorer(const ContextRestorer&) = delete; + ContextRestorer& operator=(const ContextRestorer&) = delete; + }; + + [[nodiscard]] bool parse_unsigned_strict(const std::string& text, + unsigned& out) noexcept + { + if (text.empty() || text[0] == '-') { + return false; + } + try { + std::size_t pos = 0; + const unsigned long val = std::stoul(text, &pos, 10); + if (pos != text.size() || val > std::numeric_limits::max()) { + return false; + } + out = static_cast(val); + return true; + } catch (...) { + return false; + } + } + } // namespace + RunConfig Runner::parse_args(int argc, char** argv) { RunConfig config; + auto need_val = [&](const std::string& flag, int& i, std::string& out) -> bool { + if (i + 1 >= argc) { + if (config.parse_error.empty()) { + config.parse_error = std::format("Missing value for option {}", flag); + } + return false; + } + out = argv[++i]; + return true; + }; + for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; - if ((arg == "--filter" || arg == "--suite" || - arg == "--reporter" || arg == "--output" || - arg == "--tag" || arg == "--seed" || arg == "--repeat" || - arg == "--log-file" || arg == "--parallel") && - i + 1 < argc) { - std::string val = argv[++i]; - if (arg == "--filter") { - config.filter_pattern = val; - } else if (arg == "--suite") { - config.suite_filter = val; - } else if (arg == "--reporter") { - config.reporter = val; - } else if (arg == "--output") { - config.output_file = val; - } else if (arg == "--tag") { - config.tag_filter = val; - } else if (arg == "--log-file") { - config.log_file = val; - } else if (arg == "--seed") { - config.shuffle = true; - config.random_seed = - static_cast(std::stoul(val)); - } else if (arg == "--repeat") { - config.repeat = static_cast(std::stoul(val)); - } else if (arg == "--parallel") { - config.parallel_threads = - static_cast(std::stoul(val)); + if (arg == "--filter") { + (void)need_val(arg, i, config.filter_pattern); + } else if (arg == "--suite") { + (void)need_val(arg, i, config.suite_filter); + } else if (arg == "--reporter") { + (void)need_val(arg, i, config.reporter); + } else if (arg == "--output") { + (void)need_val(arg, i, config.output_file); + } else if (arg == "--tag") { + (void)need_val(arg, i, config.tag_filter); + } else if (arg == "--log-file") { + (void)need_val(arg, i, config.log_file); + } else if (arg == "--selftest-child") { + (void)need_val(arg, i, config.selftest_child); + } else if (arg == "--seed") { + std::string val; + if (need_val(arg, i, val)) { + unsigned parsed = 0; + if (!parse_unsigned_strict(val, parsed)) { + config.parse_error = std::format("Invalid --seed value: {}", val); + } else { + config.shuffle = true; + config.random_seed = parsed; + } + } + } else if (arg == "--repeat") { + std::string val; + if (need_val(arg, i, val)) { + unsigned parsed = 0; + if (!parse_unsigned_strict(val, parsed)) { + config.parse_error = std::format("Invalid --repeat value: {}", val); + } else { + config.repeat = parsed; + } + } + } else if (arg == "--parallel") { + std::string val; + if (need_val(arg, i, val)) { + unsigned parsed = 0; + if (!parse_unsigned_strict(val, parsed)) { + config.parse_error = std::format("Invalid --parallel value: {}", val); + } else { + config.parallel_threads = parsed; + } } } else if (arg == "--help") { config.show_help = true; @@ -90,10 +186,16 @@ namespace Void::Testing config.verbose = true; } else if (arg == "--no-color") { config.no_color = true; + } else if (arg == "--allow-empty") { + config.allow_empty = true; } else if (arg == "--shuffle") { config.shuffle = true; std::random_device rd; config.random_seed = rd(); + } else if (!arg.empty() && arg[0] == '-') { + if (config.parse_error.empty()) { + config.parse_error = std::format("Unknown option: {}", arg); + } } } return config; @@ -142,14 +244,19 @@ namespace Void::Testing std::unique_ptr Runner::create_reporter(const RunConfig& config) { if (config.reporter == "junit") { - static std::ofstream file{config.output_file.empty() - ? "test_results.xml" - : config.output_file}; - return std::make_unique(file); + const std::string path = + config.output_file.empty() ? "test_results.xml" : config.output_file; + auto file = std::make_unique(path, std::ios::out | std::ios::trunc); + return std::make_unique(std::move(file), nullptr); } return std::make_unique(std::cout, !config.no_color); } + TestResult Runner::execute_case(TestCase& test_case) + { + return execute_test(test_case); + } + TestResult Runner::execute_test(TestCase& test_case) { TestResult result; @@ -163,6 +270,7 @@ namespace Void::Testing : test_case.skip_reason; return result; } + ContextRestorer ctx_restorer; Detail::TestContext::current().current_result = &result; Detail::TestContext::current().should_abort = false; @@ -214,7 +322,6 @@ namespace Void::Testing auto end = std::chrono::high_resolution_clock::now(); result.duration = end - start; Detail::uninstall_signal_handlers(); - Detail::TestContext::current().current_result = nullptr; if (result.state != TestState::Skipped && result.state != TestState::Crashed) { @@ -223,7 +330,7 @@ namespace Void::Testing [](const auto& a) { return !a.passed; }); // An exception that escaped the body fails it too, with no failed // assertion recorded. - const bool unhandled = !result.crash_info.empty(); + const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty(); result.state = any || unhandled ? TestState::Failed : TestState::Passed; } @@ -245,6 +352,7 @@ namespace Void::Testing : test_case.skip_reason; return result; } + ContextRestorer ctx_restorer; Detail::TestContext::current().current_result = &result; Detail::TestContext::current().should_abort = false; @@ -265,7 +373,6 @@ namespace Void::Testing } auto end = std::chrono::high_resolution_clock::now(); result.duration = end - start; - Detail::TestContext::current().current_result = nullptr; if (result.state != TestState::Skipped && result.state != TestState::Crashed) { @@ -274,29 +381,58 @@ namespace Void::Testing [](const auto& a) { return !a.passed; }); // An exception that escaped the body fails it too, with no failed // assertion recorded. - const bool unhandled = !result.crash_info.empty(); + const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty(); result.state = any || unhandled ? TestState::Failed : TestState::Passed; } return result; } - void Runner::run_test_body(TestCase& test_case, TestResult&) + void Runner::run_test_body(TestCase& test_case, TestResult& result) { if (test_case.fixture_create) { void* fixture = test_case.fixture_create(); Detail::TestContext::current().fixture = fixture; + bool teardown_attempted = false; + auto run_teardown_once = [&]() { + if (teardown_attempted) { + return; + } + teardown_attempted = true; + try { + if (test_case.fixture_teardown) { + test_case.fixture_teardown(fixture); + } + } catch (const std::exception& e) { + result.cleanup_error = + std::format("Fixture teardown error: {}", e.what()); + if (result.state == TestState::Passed) { + result.state = TestState::Failed; + } + } catch (...) { + result.cleanup_error = "Fixture teardown unknown exception"; + if (result.state == TestState::Passed) { + result.state = TestState::Failed; + } + } + }; try { - test_case.fixture_setup(fixture); + if (test_case.fixture_setup) { + test_case.fixture_setup(fixture); + } test_case.run(); - test_case.fixture_teardown(fixture); + run_teardown_once(); } catch (...) { - test_case.fixture_teardown(fixture); - test_case.fixture_destroy(fixture); + run_teardown_once(); + if (test_case.fixture_destroy) { + test_case.fixture_destroy(fixture); + } Detail::TestContext::current().fixture = nullptr; throw; } - test_case.fixture_destroy(fixture); + if (test_case.fixture_destroy) { + test_case.fixture_destroy(fixture); + } Detail::TestContext::current().fixture = nullptr; } else { test_case.run(); @@ -401,6 +537,8 @@ namespace Void::Testing << apply(dim, "Enable verbose output") << "\n" << " " << opt("--no-color") << apply(dim, "Disable colored console output") << "\n" + << " " << opt("--allow-empty") + << apply(dim, "Do not fail when selection matches zero tests") << "\n" << " " << opt("--help") << apply(dim, "Show this help message") << "\n" << "\n" @@ -417,9 +555,72 @@ namespace Void::Testing return {}; } + + if (!config.parse_error.empty()) { + RunResult err_res; + err_res.config_error = config.parse_error; + std::cerr << "error: " << err_res.config_error << "\n"; + return err_res; + } + if (config.reporter != "console" && config.reporter != "junit") { + RunResult err_res; + err_res.config_error = + std::format("Unknown reporter: {}", config.reporter); + std::cerr << "error: " << err_res.config_error << "\n"; + return err_res; + } + if (config.repeat == 0) { + RunResult err_res; + err_res.config_error = "--repeat must be >= 1"; + std::cerr << "error: " << err_res.config_error << "\n"; + return err_res; + } + if (!config.filter_pattern.empty()) { + try { + (void)std::regex{config.filter_pattern}; + } catch (const std::regex_error& e) { + RunResult err_res; + err_res.config_error = std::format( + "Invalid --filter regex '{}': {}", config.filter_pattern, e.what()); + std::cerr << "error: " << err_res.config_error << "\n"; + return err_res; + } + } + auto all_tests = Detail::Registry::instance().tests(); auto tests = filter_tests(all_tests, config); - auto reporter = create_reporter(config); + const bool has_explicit_selection = + !config.filter_pattern.empty() || + !config.suite_filter.empty() || + !config.tag_filter.empty(); + if (!config.list_only && has_explicit_selection && + tests.empty() && !config.allow_empty) { + RunResult err_res; + err_res.config_error = + "Test selection matched 0 tests (pass --allow-empty to permit empty selection)"; + std::cerr << "error: " << err_res.config_error << "\n"; + return err_res; + } + + std::string report_write_error; + std::unique_ptr reporter; + if (config.reporter == "junit") { + const std::string path = + config.output_file.empty() ? "test_results.xml" : config.output_file; + auto file = std::make_unique( + path, std::ios::out | std::ios::trunc); + if (!file->is_open()) { + RunResult err_res; + err_res.config_error = + std::format("Failed to open JUnit output file: {}", path); + std::cerr << "error: " << err_res.config_error << "\n"; + return err_res; + } + reporter = std::make_unique( + std::move(file), &report_write_error); + } else { + reporter = create_reporter(config); + } // ── Optional: file logger sink (requires Void::Logging) ────────────────── #ifdef VOID_HAS_LOG @@ -661,6 +862,11 @@ namespace Void::Testing } run_result.total_duration = end_time - start_time; reporter->on_run_end(run_result); + reporter.reset(); + if (!report_write_error.empty()) { + run_result.config_error = std::move(report_write_error); + std::cerr << "error: " << run_result.config_error << "\n"; + } #ifdef VOID_HAS_LOG if (log_sink) { log_sink->info( @@ -680,7 +886,30 @@ namespace Void::Testing int Runner::main(int argc, char** argv) { auto config = parse_args(argc, argv); + if (!config.selftest_child.empty()) { + if (config.selftest_child == "abort") { + std::signal(SIGSEGV, SIG_DFL); + std::signal(SIGABRT, SIG_DFL); + std::abort(); + } + if (config.selftest_child == "hang") { + std::this_thread::sleep_for(std::chrono::seconds{5}); + return 0; + } + if (config.selftest_child == "flood") { + const std::string out_chunk(131072, 'O'); + const std::string err_chunk(131072, 'E'); + std::cout << out_chunk << std::flush; + std::cerr << err_chunk << std::flush; + return 0; + } + std::cerr << "Unknown --selftest-child mode: " << config.selftest_child << "\n"; + return 2; + } auto result = run(config); + if (!result.config_error.empty()) { + return 2; + } return (result.failed + result.crashed > 0) ? 1 : 0; } } // namespace Void::Testing diff --git a/src/Testing/Subprocess.cpp b/src/Testing/Subprocess.cpp new file mode 100644 index 0000000..9dc2f73 --- /dev/null +++ b/src/Testing/Subprocess.cpp @@ -0,0 +1,307 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#endif + +namespace Void::Testing +{ + +std::string current_executable_path() +{ +#ifdef __linux__ + std::error_code ec; + const auto p = std::filesystem::read_symlink("/proc/self/exe", ec); + if (!ec) { + return p.string(); + } +#endif + return {}; +} + +#ifndef _WIN32 +namespace +{ + +void close_fd_safe(int& fd) noexcept +{ + if (fd >= 0) { + ::close(fd); + fd = -1; + } +} + +bool create_cloexec_pipe(int fds[2]) noexcept +{ +#ifdef __linux__ + if (::pipe2(fds, O_CLOEXEC) == 0) { + return true; + } +#endif + if (::pipe(fds) != 0) { + return false; + } + for (int i = 0; i < 2; ++i) { + const int fl = ::fcntl(fds[i], F_GETFD, 0); + if (fl >= 0) { + (void)::fcntl(fds[i], F_SETFD, fl | FD_CLOEXEC); + } + } + return true; +} + +void drain_fd_chunk(int& fd, + std::string& dst, + bool& truncated, + std::size_t limit) noexcept +{ + std::array buf{}; + for (;;) { + const ssize_t n = ::read(fd, buf.data(), buf.size()); + if (n > 0) { + const std::size_t got = static_cast(n); + if (dst.size() < limit) { + const std::size_t take = std::min(got, limit - dst.size()); + dst.append(buf.data(), take); + if (take < got) { + truncated = true; + } + } else { + truncated = true; + } + continue; + } + if (n == 0) { + close_fd_safe(fd); + return; + } + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + return; + } + close_fd_safe(fd); + return; + } +} + +} // namespace + +ProcessTestResult run_isolated_subprocess( + std::string_view executable, + std::span args, + ProcessTestOptions options) +{ + ProcessTestResult res; + if (executable.empty()) { + res.diagnostic = "Subprocess executable path is empty"; + return res; + } + + int out_pipe[2]{-1, -1}; + int err_pipe[2]{-1, -1}; + if (!create_cloexec_pipe(out_pipe) || !create_cloexec_pipe(err_pipe)) { + res.diagnostic = std::string{"pipe failed: "} + std::strerror(errno); + close_fd_safe(out_pipe[0]); + close_fd_safe(out_pipe[1]); + close_fd_safe(err_pipe[0]); + close_fd_safe(err_pipe[1]); + return res; + } + + // Build execv arguments before fork so child stays async-signal-safe. + std::string exe_str{executable}; + std::vector arg_storage; + arg_storage.reserve(args.size() + 1); + arg_storage.push_back(exe_str); + for (const auto& a : args) { + arg_storage.push_back(a); + } + std::vector argv_ptrs; + argv_ptrs.reserve(arg_storage.size() + 1); + for (auto& s : arg_storage) { + argv_ptrs.push_back(s.data()); + } + argv_ptrs.push_back(nullptr); + + const pid_t pid = ::fork(); + if (pid < 0) { + res.diagnostic = std::string{"fork failed: "} + std::strerror(errno); + close_fd_safe(out_pipe[0]); + close_fd_safe(out_pipe[1]); + close_fd_safe(err_pipe[0]); + close_fd_safe(err_pipe[1]); + return res; + } + + if (pid == 0) { + close_fd_safe(out_pipe[0]); + close_fd_safe(err_pipe[0]); + (void)::dup2(out_pipe[1], STDOUT_FILENO); + (void)::dup2(err_pipe[1], STDERR_FILENO); + close_fd_safe(out_pipe[1]); + close_fd_safe(err_pipe[1]); + ::execv(exe_str.c_str(), argv_ptrs.data()); + ::_exit(127); + } + + close_fd_safe(out_pipe[1]); + close_fd_safe(err_pipe[1]); + + for (int fd : {out_pipe[0], err_pipe[0]}) { + const int fl = ::fcntl(fd, F_GETFL, 0); + if (fl >= 0) { + (void)::fcntl(fd, F_SETFL, fl | O_NONBLOCK); + } + } + + const auto start = std::chrono::steady_clock::now(); + const auto deadline = start + std::max(options.timeout, std::chrono::milliseconds{1}); + bool timed_out = false; + bool child_reaped = false; + int wait_status = 0; + + while (out_pipe[0] >= 0 || err_pipe[0] >= 0 || !child_reaped) { + if (!child_reaped) { + const pid_t wr = ::waitpid(pid, &wait_status, WNOHANG); + if (wr == pid) { + child_reaped = true; + } + } + + if (out_pipe[0] < 0 && err_pipe[0] < 0) { + if (child_reaped) { + break; + } + } + + const auto now = std::chrono::steady_clock::now(); + if (now >= deadline && !timed_out) { + timed_out = true; + (void)::kill(pid, SIGKILL); + } + + if (out_pipe[0] >= 0 || err_pipe[0] >= 0) { + std::array pfds{}; + nfds_t nfds = 0; + if (out_pipe[0] >= 0) { + pfds[nfds++] = pollfd{out_pipe[0], POLLIN | POLLHUP | POLLERR, 0}; + } + if (err_pipe[0] >= 0) { + pfds[nfds++] = pollfd{err_pipe[0], POLLIN | POLLHUP | POLLERR, 0}; + } + int wait_ms = 5; + if (!timed_out) { + const auto rem_ms = + std::chrono::duration_cast(deadline - now).count(); + wait_ms = static_cast(std::clamp(rem_ms, 1, 20)); + } + const int pr = ::poll(pfds.data(), nfds, wait_ms); + if (pr < 0 && errno != EINTR) { + break; + } + if (out_pipe[0] >= 0) { + drain_fd_chunk(out_pipe[0], res.stdout_captured, res.stdout_truncated, options.max_output_bytes); + } + if (err_pipe[0] >= 0) { + drain_fd_chunk(err_pipe[0], res.stderr_captured, res.stderr_truncated, options.max_output_bytes); + } + if (timed_out) { + // Reap killed child and finish draining pipes cleanly. + if (!child_reaped) { + for (;;) { + const pid_t wr = ::waitpid(pid, &wait_status, 0); + if (wr == pid) { + child_reaped = true; + break; + } + if (wr < 0 && errno == EINTR) { + continue; + } + break; + } + } + if (out_pipe[0] >= 0) { + drain_fd_chunk(out_pipe[0], res.stdout_captured, res.stdout_truncated, options.max_output_bytes); + } + if (err_pipe[0] >= 0) { + drain_fd_chunk(err_pipe[0], res.stderr_captured, res.stderr_truncated, options.max_output_bytes); + } + break; + } + } else if (!child_reaped) { + ::poll(nullptr, 0, 2); + } + } + + close_fd_safe(out_pipe[0]); + close_fd_safe(err_pipe[0]); + + if (!child_reaped) { + for (;;) { + const pid_t wr = ::waitpid(pid, &wait_status, 0); + if (wr == pid) { + child_reaped = true; + break; + } + if (wr < 0 && errno == EINTR) { + continue; + } + break; + } + } + + if (timed_out) { + res.outcome = ProcessOutcome::timed_out; + res.diagnostic = "Subprocess exceeded timeout"; + return res; + } + if (!child_reaped) { + res.outcome = ProcessOutcome::infrastructure_error; + res.diagnostic = "Failed to waitpid on subprocess"; + return res; + } + if (WIFSIGNALED(wait_status)) { + res.outcome = ProcessOutcome::crashed; + res.term_signal = WTERMSIG(wait_status); + return res; + } + if (WIFEXITED(wait_status)) { + res.exit_code = WEXITSTATUS(wait_status); + res.outcome = (res.exit_code == 0) ? ProcessOutcome::passed : ProcessOutcome::failed; + return res; + } + + res.outcome = ProcessOutcome::infrastructure_error; + res.diagnostic = "Subprocess exited in unexpected state"; + return res; +} +#else +ProcessTestResult run_isolated_subprocess( + std::string_view, + std::span, + ProcessTestOptions) +{ + ProcessTestResult res; + res.outcome = ProcessOutcome::infrastructure_error; + res.diagnostic = "Subprocess isolation not implemented on Windows"; + return res; +} +#endif + +} // namespace Void::Testing \ No newline at end of file diff --git a/tests/standalone/Testing/Deterministic.cpp b/tests/standalone/Testing/Deterministic.cpp new file mode 100644 index 0000000..836f11a --- /dev/null +++ b/tests/standalone/Testing/Deterministic.cpp @@ -0,0 +1,155 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +Void::Testing::Test deterministic_rng_golden_sequence_and_bounds() +{ + using Void::Testing::DeterministicRng; + using Void::Testing::ReplayToken; + + const ReplayToken tok{.seed = 0x123456789ABCDEF0ULL, .generator_version = 1, .case_index = 7}; + DeterministicRng r1{tok}; + DeterministicRng r2{tok}; + + // Identical seed+version+case reproduces identically + for (int i = 0; i < 8; ++i) { + Void::Testing::expect_eq(r1.next_u64(), r2.next_u64()); + } + + // Check frozen v1 reference values remain invariant across compilers/platforms + DeterministicRng ref_rng{ReplayToken{.seed = 42, .generator_version = 1, .case_index = 0}}; + const std::uint64_t g0 = ref_rng.next_u64(); + const std::uint64_t g1 = ref_rng.next_bounded(100); + DeterministicRng verify_rng{ReplayToken{.seed = 42, .generator_version = 1, .case_index = 0}}; + Void::Testing::expect_eq(verify_rng.next_u64(), g0); + Void::Testing::expect_eq(verify_rng.next_bounded(100), g1); + Void::Testing::expect(g1 < 100); + + for (int i = 0; i < 64; ++i) { + const auto v = r1.next_int(-15, 25); + Void::Testing::expect(v >= -15 && v <= 25); + } +} + +Void::Testing::Test deterministic_property_shrink_replay_and_budget_exhaustion() +{ + using namespace Void::Testing; + + // 1. Passing property + const auto pass_res = check_property( + [](DeterministicRng& rng) { return rng.next_ints(16, 0, 100); }, + [](const std::vector& xs) { return xs.size() <= 16; }, + PropertyOptions{.cases = 64}); + expect(pass_res.status == PropertyStatus::passed); + expect_eq(pass_res.cases_executed, 64u); + + // 2. Failing property shrinks to minimal counterexample and replays via ReplayToken + auto gen_vec = [](DeterministicRng& rng) { return rng.next_ints(20, 0, 100); }; + auto pred_no_big = [](const std::vector& xs) { + int sum = 0; + for (int x : xs) { + sum += x; + } + return sum <= 120; + }; + auto shrink_vec = [](const std::vector& xs) { + std::vector> cands; + for (std::size_t i = 0; i < xs.size(); ++i) { + std::vector removed = xs; + removed.erase(removed.begin() + static_cast(i)); + cands.push_back(std::move(removed)); + } + for (std::size_t i = 0; i < xs.size(); ++i) { + if (xs[i] > 0) { + std::vector halved = xs; + halved[i] = xs[i] / 2; + cands.push_back(std::move(halved)); + } + } + return cands; + }; + + const auto fail_res = check_property( + gen_vec, + pred_no_big, + shrink_vec, + PropertyOptions{.cases = 200, .max_shrinks = 500}, + ReplayToken{.seed = 1337, .generator_version = 1, .case_index = 0}); + expect(fail_res.status == PropertyStatus::failed); + require(fail_res.original_failure.has_value()); + require(fail_res.minimal_failure.has_value()); + expect(!pred_no_big(*fail_res.minimal_failure)); + expect(fail_res.minimal_failure->size() <= fail_res.original_failure->size()); + expect(fail_res.shrink_steps > 0); + expect(!replay_property_case(gen_vec, pred_no_big, fail_res.replay)); + + // 3. Time/step/discard budget exhaustion produces inconclusive (NEVER passed) + Void::Time::ManualClock mclock; + const auto time_exh = check_property( + [](DeterministicRng& rng) { return static_cast(rng.next_bounded(10)); }, + [&](const int&) { + (void)mclock.advance(std::chrono::seconds{2}); + return true; + }, + PropertyOptions{.cases = 50, .time_budget = std::chrono::seconds{5}}, + ReplayToken{}, + &mclock); + expect(time_exh.status == PropertyStatus::inconclusive); + + const auto discard_exh = check_property( + [](DeterministicRng& rng) -> std::optional { + (void)rng; + return std::nullopt; + }, + [](const int&) { return true; }, + PropertyOptions{.cases = 5, .max_discard_factor = 3}); + expect(discard_exh.status == PropertyStatus::inconclusive); +} + +Void::Testing::Test deterministic_run_clock_timers_and_interleavings() +{ + using Void::Testing::DeterministicRun; + + // 1. Timer ordering (fire_at, sequence) and alternate ready-queue choice exploration + DeterministicRun run; + std::vector log; + run.schedule("first", [&] { log.push_back("first"); }); + run.schedule("second", [&] { log.push_back("second"); }); + (void)run.schedule_after(std::chrono::milliseconds{20}, "t20", [&] { log.push_back("t20"); }); + (void)run.schedule_after(std::chrono::milliseconds{10}, "t10_a", [&] { log.push_back("t10_a"); }); + (void)run.schedule_after(std::chrono::milliseconds{10}, "t10_b", [&] { log.push_back("t10_b"); }); + + // Choose index 1 ("second") ahead of index 0 ("first") explicitly! + Void::Testing::expect(run.step_choice(1)); + Void::Testing::expect(run.step()); + Void::Testing::expect(!run.step()); // Ready empty; timers still waiting + + Void::Testing::expect_eq(run.timer_count(), std::size_t{3}); + const std::size_t promoted1 = run.advance_clock(std::chrono::milliseconds{10}); + Void::Testing::expect_eq(promoted1, std::size_t{2}); + Void::Testing::expect(run.run_until_idle().has_value()); + + const std::size_t promoted2 = run.advance_clock(std::chrono::milliseconds{10}); + Void::Testing::expect_eq(promoted2, std::size_t{1}); + Void::Testing::expect(run.run_until_idle().has_value()); + + const std::vector expected{"second", "first", "t10_a", "t10_b", "t20"}; + Void::Testing::expect(log == expected); + Void::Testing::expect_eq(run.trace().size(), std::size_t{5}); + Void::Testing::expect_eq(run.trace()[0].label, std::string{"second"}); + Void::Testing::expect_eq(run.trace()[4].clock_ns, 20'000'000LL); + + // 2. Infinite self-rescheduling bounded cleanly by max_steps + DeterministicRun inf_run; + std::function loop_fn = [&] { inf_run.schedule("spin", loop_fn); }; + inf_run.schedule("spin", loop_fn); + const auto bound_res = inf_run.run_until_idle(25); + Void::Testing::expect(!bound_res.has_value()); +} \ No newline at end of file diff --git a/tests/standalone/Testing/FrameworkHardening.cpp b/tests/standalone/Testing/FrameworkHardening.cpp new file mode 100644 index 0000000..2ba9904 --- /dev/null +++ b/tests/standalone/Testing/FrameworkHardening.cpp @@ -0,0 +1,263 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +struct TempDirGuard { + std::filesystem::path dir; + explicit TempDirGuard(std::string_view suffix) + : dir(std::filesystem::temp_directory_path() / suffix) + { + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + } + ~TempDirGuard() + { + std::error_code ec; + std::filesystem::remove_all(dir, ec); + } +}; + +} // namespace + +Void::Testing::Test testing_failure_capture_and_bounded_assertions() +{ + using namespace Void::Testing; + + // FailureCapture catches expect and require aborts locally without failing the outer test + { + FailureCapture cap; + const bool ok = cap.run([] { + expect_eq(1, 2); + require(false); + }); + expect(!ok); + expect(cap.failed()); + expect(cap.aborted()); + expect_eq(cap.assertions().size(), std::size_t{2}); + } + + // Assertions above kMaxRetainedAssertionsPerTest truncate cleanly without losing failure state + { + FailureCapture cap; + const bool ok = cap.run([] { + for (std::size_t i = 0; i < kMaxRetainedAssertionsPerTest + 50; ++i) { + expect(true); + } + expect(false); + }); + expect(!ok); + expect(cap.failed()); + expect(cap.truncated()); + expect_eq(cap.assertions().size(), kMaxRetainedAssertionsPerTest); + expect_eq(cap.dropped_assertions(), std::size_t{51}); + } +} + +Void::Testing::Test testing_fixture_single_teardown_and_cleanup_error() +{ + using namespace Void::Testing; + + struct State { + int setup_count{0}; + int run_count{0}; + int teardown_count{0}; + int destroy_count{0}; + }; + + // Case 1: body succeeds, teardown throws -> teardown runs once, destroy runs once, Failed + cleanup_error + { + State st; + TestCase tc{ + .run = [&] { ++st.run_count; }, + .name = "teardown_throws", + .suite = "HardeningFixture", + .fixture_create = [&]() -> void* { return &st; }, + .fixture_destroy = [](void* p) { ++static_cast(p)->destroy_count; }, + .fixture_setup = [](void* p) { ++static_cast(p)->setup_count; }, + .fixture_teardown = + [](void* p) { + ++static_cast(p)->teardown_count; + throw std::runtime_error{"teardown boom"}; + }, + }; + const TestResult res = Runner::instance().execute_case(tc); + expect(res.state == TestState::Failed); + expect_eq(st.setup_count, 1); + expect_eq(st.run_count, 1); + expect_eq(st.teardown_count, 1); + expect_eq(st.destroy_count, 1); + expect(res.cleanup_error.find("teardown boom") != std::string::npos); + } + + // Case 2: primary body fails AND teardown throws -> BOTH primary failure and cleanup_error preserved! + { + State st; + TestCase tc{ + .run = [&] { + ++st.run_count; + throw std::runtime_error{"body boom"}; + }, + .name = "both_throw", + .suite = "HardeningFixture", + .fixture_create = [&]() -> void* { return &st; }, + .fixture_destroy = [](void* p) { ++static_cast(p)->destroy_count; }, + .fixture_setup = [](void* p) { ++static_cast(p)->setup_count; }, + .fixture_teardown = + [](void* p) { + ++static_cast(p)->teardown_count; + throw std::runtime_error{"cleanup boom"}; + }, + }; + const TestResult res = Runner::instance().execute_case(tc); + expect(res.state == TestState::Failed); + expect_eq(st.teardown_count, 1); + expect_eq(st.destroy_count, 1); + expect(res.crash_info.find("body boom") != std::string::npos); + expect(res.cleanup_error.find("cleanup boom") != std::string::npos); + } +} + +Void::Testing::Test testing_junit_distinct_files_and_config_validation() +{ + using namespace Void::Testing; + + TempDirGuard tmp{"void_testing_junit_check"}; + const auto file1 = tmp.dir / "run1.xml"; + const auto file2 = tmp.dir / "run2.xml"; + + // Two sequential JUnit runs to different output files write independent valid XMLs + RunConfig c1; + c1.filter_pattern = "^broken_feature$"; + c1.reporter = "junit"; + c1.output_file = file1.string(); + const RunResult r1 = Runner::instance().run(c1); + expect(r1.config_error.empty()); + expect_eq(r1.skipped, 1); + + RunConfig c2; + c2.filter_pattern = "^unquoted_skip$"; + c2.reporter = "junit"; + c2.output_file = file2.string(); + const RunResult r2 = Runner::instance().run(c2); + expect(r2.config_error.empty()); + expect_eq(r2.skipped, 1); + + auto read_all = [](const std::filesystem::path& p) { + std::ifstream f{p}; + return std::string{std::istreambuf_iterator{f}, std::istreambuf_iterator{}}; + }; + const std::string xml1 = read_all(file1); + const std::string xml2 = read_all(file2); + expect(xml1.find("broken_feature") != std::string::npos); + expect(xml1.find("unquoted_skip") == std::string::npos); + expect(xml2.find("unquoted_skip") != std::string::npos); + expect(xml2.find("broken_feature") == std::string::npos); + + // Invalid regex, invalid reporter, unopenable output path, empty selection fail config_error + RunConfig bad_regex; + bad_regex.filter_pattern = "[unclosed"; + expect(!Runner::instance().run(bad_regex).config_error.empty()); + + RunConfig bad_rep; + bad_rep.reporter = "nonexistent"; + expect(!Runner::instance().run(bad_rep).config_error.empty()); + + RunConfig bad_out; + bad_out.filter_pattern = "^broken_feature$"; + bad_out.reporter = "junit"; + bad_out.output_file = (tmp.dir / "missing_dir" / "out.xml").string(); + expect(!Runner::instance().run(bad_out).config_error.empty()); + + RunConfig empty_sel; + empty_sel.filter_pattern = "^definitely_no_such_test_name_12345$"; + expect(!Runner::instance().run(empty_sel).config_error.empty()); + + empty_sel.allow_empty = true; + empty_sel.reporter = "junit"; + empty_sel.output_file = (tmp.dir / "empty.xml").string(); + const RunResult allowed = Runner::instance().run(empty_sel); + expect(allowed.config_error.empty()); + expect_eq(allowed.total, 0); + expect(read_all(tmp.dir / "empty.xml").find(" args{"--filter", "^broken_feature$", "--no-color"}; + const auto res = run_isolated_subprocess(exe, args); + expect(res.outcome == ProcessOutcome::passed); + expect_eq(res.exit_code, 0); + } + + // 2. Empty selection fails cleanly with non-zero exit code 2 + { + const std::vector args{ + "--filter", "^definitely_no_such_test_xyz$", "--no-color"}; + const auto res = run_isolated_subprocess(exe, args); + expect(res.outcome == ProcessOutcome::failed); + expect_eq(res.exit_code, 2); + } + + // 3. --allow-empty turns explicit empty selection into clean exit 0 + { + const std::vector args{ + "--filter", "^definitely_no_such_test_xyz$", "--allow-empty", "--no-color"}; + const auto res = run_isolated_subprocess(exe, args); + expect(res.outcome == ProcessOutcome::passed); + expect_eq(res.exit_code, 0); + } + + // 4. Child abort isolated cleanly as crashed (SIGABRT) + { + const std::vector args{"--selftest-child", "abort"}; + const auto res = run_isolated_subprocess(exe, args); + expect(res.outcome == ProcessOutcome::crashed); + expect_eq(res.term_signal, SIGABRT); + } + + // 5. Child hang terminated on deadline cleanly + { + const std::vector args{"--selftest-child", "hang"}; + const auto res = run_isolated_subprocess( + exe, args, ProcessTestOptions{.timeout = std::chrono::milliseconds{150}}); + expect(res.outcome == ProcessOutcome::timed_out); + } + + // 6. Concurrent stdout+stderr flood drains completely with bounded truncation & zero deadlock + { + const std::vector args{"--selftest-child", "flood"}; + const auto res = run_isolated_subprocess( + exe, + args, + ProcessTestOptions{ + .timeout = std::chrono::milliseconds{5000}, + .max_output_bytes = 4096, + }); + expect(res.outcome == ProcessOutcome::passed); + expect(res.stdout_truncated); + expect(res.stderr_truncated); + expect_eq(res.stdout_captured.size(), std::size_t{4096}); + expect_eq(res.stderr_captured.size(), std::size_t{4096}); + } +} \ No newline at end of file From f6c359400af1a156a93ede0a6a0948cba78d8436 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 09:42:23 +0300 Subject: [PATCH 5/5] docs(workflow): record Wave 4B (P1 IO, Runtime, Testing) verification evidence --- docs/agent-workflow/STATE.md | 41 +++++++++++++++++++++++++---- docs/agent-workflow/TASKS.md | 8 ++++++ docs/agent-workflow/VERIFICATION.md | 14 ++++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 98b83b1..144f441 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,8 @@ # Workflow state Updated: 2026-11-24. -Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4a` (from `main` -at `5754a7f`, merged Waves 1–3 from `feat/roadmap-p0-p1-foundations`). +Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4b` (from `main` +at `2e5d1ef`, merged Waves 1–4A). ## Completed objective @@ -148,8 +148,39 @@ pushing to remote) while leaving local untracked files untouched. `containers_lru_get_put` 21.81 ns, `binary_reader_u64_be` 1.36 ns, `data_json_parse_small_object` 319.83 ns, `data_json_serialize_small_object` 168.13 ns. +## Verification already observed (Wave 4B — P1 IO, Runtime, Testing) + +- Standalone `IO` (`-Werror`, `/tmp/void-w4b-io`, `673bb7e`): `IoDriver` 4/4 passed (7.5 ms); + `ctest` 2/2 passed (`VoidTests` 1.50 s, `VoidInstalledComponentConsumers` including `IOOnly` + 6.08 s); Debug TSan `/tmp/void-w4b-io-tsan` `IoDriver` 4/4 passed (12.8 ms, 0 races). +- Standalone `Runtime` (`-Werror`, `/tmp/void-w4b-runtime`, 11 modules, `1b3331e`): + `RuntimeHost` 3/3 passed (0.5 ms); `ctest` 2/2 passed (`VoidTests` 1.54 s, + `VoidInstalledComponentConsumers` including `RuntimeOnly` 8.01 s). +- Standalone `Testing` (`Core;Testing`, `-Werror`, `/tmp/void-w4b-testing`, `de8a981`): + `FrameworkHardening*|Deterministic*|Math*|ContainerFixture*|StructRepr*` 16 tests — 14 + passed, 2 intentional skips (`broken_feature`, `unquoted_skip`), 0 failed (301.1 ms); + `ctest` 2/2 passed (2.82 s). +- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w4b-full`, 33 modules, + `de8a981`): `VoidTests` 1,359 tests — 1,356 passed, 3 intentional skips + (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (5.08 s); + `ctest` 2/2 passed (`VoidTests` 4.50 s, `VoidInstalledComponentConsumers` 19.77 s, total + 24.27 s). +- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w4b-asan`, 33 modules, + `de8a981`): `VoidTests` 1,359 tests — 1,356 passed, 3 skipped, 0 failed (14.87 s), 0 leaks, + 0 UB. +- Debug TSan subset (`IO;Async;Containers;Time;Testing`, `/tmp/void-w4b-tsan`, 9 active + modules, `de8a981`): `Io*|OperationScope*|Executor*|Ring*|Pool*|Clock*` 80/80 passed + (60.7 ms), 0 TSan data races. +- `VoidFoundationBench` post-W4B (`rev=de8a981893d8`, `/tmp/void-w4b-full`, `post-w4b.json`): + `harness_empty_loop` 0.39 ns, `core_uuid_parse_hyphenated` 25.28 ns, + `core_uuid_to_string` 16.94 ns, `core_hash_fnv1a64_256b` 184.30 ns, + `core_hash_murmur3_256b` 69.63 ns, `functional_result_ok_chain` 1.16 ns, + `functional_error_with_context` 60.17 ns, `math_checked_add_loop` 0.48 ns, + `containers_spsc_ring_push_pop` 9.06 ns, `containers_lru_get_put` 21.30 ns, + `binary_reader_u64_be` 1.35 ns, `data_json_parse_small_object` 316.78 ns, + `data_json_serialize_small_object` 168.16 ns. + ## Ownership and next step -Waves 1–4A (`P0`, `P1 Gate 1`, `P1 Text/Containers/Binary/Data`, and `P1 Algorithms/Unicode/Async`) -are complete and verified on `feat/roadmap-p1-wave4a` and ready to merge locally into `main`, -before planning and executing Wave 4B (`IO`, `Runtime`, `Testing` P1). +Waves 1–4B (`P0` and `P1`) are complete and verified on `feat/roadmap-p1-wave4b` and ready +to merge locally into `main`, before planning and executing **P2 Wave 5**. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 25d2877..64c19c8 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -51,6 +51,14 @@ These tasks author plans. Future feature task IDs inside those plans remain plan | S-UNICODE-01, S-UNICODE-02 | `src/Unicode/module.cmake`, `MANIFEST.md` (Unicode 17.0.0), `Utf.hpp` (`data_version`, `Scalar`, `UtfPolicy`, strict/one-unit-repair codecs, `_into` span transcoders, `Utf8StreamDecoder`/`Utf16StreamDecoder`), `UnicodeOnly` consumer (`4369fde`) | [S-UNICODE-01-02](tasks/S-UNICODE-01-02.md) | VERIFIED | `Utf` 4/4 and `UnicodeOnly` passed in `Unicode;Testing`, full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) | | M-ASYNC-02, M-ASYNC-03 | `src/Async/module.cmake` (`INTERNAL_DEPS Functional Time LogState`), `Detail/Types.hpp`, `Operation.hpp` (`ResumeTicket`, `OperationState`), upgraded `Executor.hpp` (`try_post`, `post_completion`, bounded `ManualExecutor`, clock/stop `schedule_on`), `TaskScope.hpp` (`TaskScope`, `JoinHandle`, `DetachedOwner`) (`c75056f`) | [M-ASYNC-02-03](tasks/M-ASYNC-02-03.md) | VERIFIED | `OperationScope*|Executor*|Coro*` 28/28, Debug TSan 20/20 (0 races), full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) | +## Wave 4B — P1 IO, Runtime, Testing (`feat/roadmap-p1-wave4b`) + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| S-IO-01, S-IO-02 | `src/IO/module.cmake` (`Core Functional Time Memory Async`), `Types.hpp`, `Detail/Backend.hpp`, `Stream.hpp`, `Driver.hpp`, `src/IO/EpollDriver.cpp` (mock + Linux level-triggered epoll, `(slot, generation)` tokens, `eventfd`, `BufferLease` PMR/quota, `MockController`, `read_exact`/`write_all`), `IOOnly` consumer (`673bb7e`) | [S-IO-01-02](tasks/S-IO-01-02.md) | VERIFIED | `IoDriver` 4/4, `IOOnly` & `ctest` 2/2 passed; Debug TSan `IoDriver` 4/4 (0 races), full RelWithDebInfo (1,356 ✔) & ASan+UBSan (0 leaks/UB) | +| S-RUNTIME-01 | `CMakeLists.txt` explicit `void_add_module` keyword matching fix, `src/Runtime/module.cmake` (`Core Functional Time Memory Algorithms Async IO`), `Options.hpp`, `ResourceGraph.hpp`, `Host.hpp`, `RuntimeOnly` consumer (`1b3331e`) | [S-RUNTIME-01](tasks/S-RUNTIME-01.md) | VERIFIED | `RuntimeHost` 3/3, `RuntimeOnly` & `ctest` 2/2 passed (11-module closure); full RelWithDebInfo (1,356 ✔) & ASan+UBSan (0 leaks/UB) | +| M-TESTING-02, M-TESTING-03 | `OwningJUnitReporter`, strict CLI/config validation (`--allow-empty`, `--selftest-child`), bounded assertion/failure capture, `Subprocess` POSIX runner, frozen v1 `DeterministicRng`/`ReplayToken`/`check_property` shrinker & `DeterministicRun` (`de8a981`) | [M-TESTING-02-03](tasks/M-TESTING-02-03.md) | VERIFIED | `Core;Testing` 14 ✔ / 2 ⊘ & `ctest` 2/2 passed; full RelWithDebInfo (1,356 ✔) & ASan+UBSan (0 leaks/UB) | + All workers share the checkout and have disjoint file ownership defined in their persisted task specifications. Root owns all cross-cutting files and resolves contract changes. No worker owns application code, build files, existing docs/short-url.md, or Git diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index ef89ac8..d9c3a08 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -201,3 +201,17 @@ Branch: `feat/roadmap-p1-wave4a` (branched from `main` at `5754a7f`). Toolchain | Full Integrated RelWithDebInfo (`c75056f`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w4a-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w4a-full --output-on-failure --timeout 180` | 31 active modules; `VoidTests`: 1,345 tests — 1,342 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (3.75s); `ctest`: 2/2 passed (`VoidTests` 3.77s + `VoidInstalledComponentConsumers` 14.45s, total 18.21s) | | Full Integrated ASan+UBSan (`c75056f`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w4a-asan/tests/VoidTests` | 1,345 tests — 1,342 passed, 3 skipped, 0 failed (11.00s), 0 leaks, 0 UB | | Post-W4A Benchmark (`c75056f`) | `/tmp/void-w4a-full/benchmarks/VoidFoundationBench --json /tmp/void-w4a-full/post-w4a.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.48ns, `core_uuid_to_string` 17.09ns, `core_hash_fnv1a64_256b` 185.25ns, `core_hash_murmur3_256b` 69.37ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.77ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 9.16ns, `containers_lru_get_put` 21.81ns, `binary_reader_u64_be` 1.36ns, `data_json_parse_small_object` 319.83ns, `data_json_serialize_small_object` 168.13ns | + +## Wave 4B / P1 IO, Runtime, Testing Verification (2026-11-24) + +Branch: `feat/roadmap-p1-wave4b` (branched from `main` at `2e5d1ef`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2. + +| Scope | Command & configuration | Observed outcome | +| --- | --- | --- | +| S-IO-01..02 (`673bb7e`) | `IO` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4b-io` (`VoidTests --filter "IoDriver*"`, `ctest`) & Debug TSan `/tmp/void-w4b-io-tsan` | `IoDriver` 4/4 passed (7.5ms); `ctest` 2/2 passed (`VoidTests` 1.50s, `VoidInstalledComponentConsumers` including `IOOnly` 6.08s); Debug TSan `IoDriver` 4/4 passed (12.8ms, 0 races) | +| S-RUNTIME-01 (`1b3331e`) | `Runtime` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4b-runtime` (`VoidTests --filter "RuntimeHost*"`, `ctest`, 11 modules) | `RuntimeHost` 3/3 passed (0.5ms); `ctest` 2/2 passed (`VoidTests` 1.54s, `VoidInstalledComponentConsumers` including `RuntimeOnly` 8.01s) | +| M-TESTING-02..03 (`de8a981`) | `Core;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4b-testing` (`VoidTests --filter "FrameworkHardening*\|Deterministic*\|Math*\|ContainerFixture*\|StructRepr*"`, `ctest`) | 16 tests: 14 passed, 2 intentional skips (`broken_feature`, `unquoted_skip`), 0 failed (301.1ms); `ctest` 2/2 passed (2.82s) | +| Full Integrated RelWithDebInfo (`de8a981`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w4b-full`, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `VoidTests`, `ctest` | 33 active modules; `VoidTests`: 1,359 tests — 1,356 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (5.08s); `ctest`: 2/2 passed (`VoidTests` 4.50s + `VoidInstalledComponentConsumers` 19.77s, total 24.27s) | +| Full Integrated ASan+UBSan (`de8a981`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w4b-asan`, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w4b-asan/tests/VoidTests` | 33 active modules; `VoidTests`: 1,359 tests — 1,356 passed, 3 skipped, 0 failed (14.87s), 0 leaks, 0 UB | +| Wave 4B TSan Subset (`de8a981`) | `dev cpp-gcc -c` Debug (`IO;Async;Containers;Time;Testing`, `/tmp/void-w4b-tsan`, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w4b-tsan/tests/VoidTests --filter "Io*\|OperationScope*\|Executor*\|Ring*\|Pool*\|Clock*"` | 9 active modules; 80/80 passed (60.7ms), 0 TSan data races | +| Post-W4B Benchmark (`de8a981`, `rev=de8a981893d8`) | `VoidFoundationBench` in `/tmp/void-w4b-full` (`post-w4b.json`) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.28ns, `core_uuid_to_string` 16.94ns, `core_hash_fnv1a64_256b` 184.30ns, `core_hash_murmur3_256b` 69.63ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 60.17ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 9.06ns, `containers_lru_get_put` 21.30ns, `binary_reader_u64_be` 1.35ns, `data_json_parse_small_object` 316.78ns, `data_json_serialize_small_object` 168.16ns |