Merge feat/roadmap-p1-wave4b: P1 IO, Runtime, and Testing foundations

This commit is contained in:
faumaray committed 2026-11-24 09:42:32 +03:00
commit 1e901ce256
35 files changed
+5762 -60

No files matched your search

+1 -1
View File
@@ -60,7 +60,7 @@ if(VOID_ENABLED_MODULES)
if(_void_text MATCHES "INTERNAL_DEPS([^)]*)") if(_void_text MATCHES "INTERNAL_DEPS([^)]*)")
separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}") separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}")
foreach(_void_word IN LISTS _void_words) 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() break()
endif() endif()
list(APPEND _void_pending ${_void_word}) list(APPEND _void_pending ${_void_word})
+36 -5
View File
@@ -1,8 +1,8 @@
# Workflow state # Workflow state
Updated: 2026-11-24. Updated: 2026-11-24.
Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4a` (from `main` Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4b` (from `main`
at `5754a7f`, merged Waves 1–3 from `feat/roadmap-p0-p1-foundations`). at `2e5d1ef`, merged Waves 1–4A).
## Completed objective ## 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, `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. `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 ## Ownership and next step
Waves 1–4A (`P0`, `P1 Gate 1`, `P1 Text/Containers/Binary/Data`, and `P1 Algorithms/Unicode/Async`) Waves 1–4B (`P0` and `P1`) are complete and verified on `feat/roadmap-p1-wave4b` and ready
are complete and verified on `feat/roadmap-p1-wave4a` and ready to merge locally into `main`, to merge locally into `main`, before planning and executing **P2 Wave 5**.
before planning and executing Wave 4B (`IO`, `Runtime`, `Testing` P1).
+8
View File
@@ -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) | | 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) | | 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 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 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 changes. No worker owns application code, build files, existing docs/short-url.md, or Git
+14
View File
@@ -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 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 | | 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 | | 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 |
@@ -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 <abort|hang|flood>` 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'
```
+37
View File
@@ -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'
```
+35
View File
@@ -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'
```
+119
View File
@@ -0,0 +1,119 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <span>
#include <vector>
namespace Void::IO
{
class ByteStream;
namespace detail
{
class StreamState;
enum class Direction {
read,
write
};
class DriverBackend : public std::enable_shared_from_this<DriverBackend>
{
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<std::shared_ptr<StreamState>>
create_mock_stream() = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<StreamState>>
adopt_fd(int fd) = 0;
[[nodiscard]] virtual Void::Result::Result<
std::pair<std::shared_ptr<StreamState>, std::shared_ptr<StreamState>>>
create_socket_pair() = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_read(const std::shared_ptr<StreamState>& stream,
std::span<std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_write(const std::shared_ptr<StreamState>& stream,
std::span<const std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
submit_close(const std::shared_ptr<StreamState>& stream,
Async::OperationOptions options) = 0;
virtual void on_stream_destroyed(const DescriptorId& id) noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<std::size_t>
poll_once(std::optional<std::chrono::nanoseconds> max_wait) = 0;
virtual void wake() noexcept = 0;
virtual void request_stop() noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<void> 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<DriverBackend> 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<DriverBackend> lock_backend() const noexcept
{
return backend_.lock();
}
void mark_explicit_closed() noexcept
{
explicitly_closed_.store(true, std::memory_order_release);
}
private:
std::weak_ptr<DriverBackend> backend_{};
DescriptorId id_{};
std::atomic<bool> explicitly_closed_{false};
};
} // namespace detail
} // namespace Void::IO
+107
View File
@@ -0,0 +1,107 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/IO/Detail/Backend.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <memory_resource>
#include <optional>
#include <span>
#include <string>
#include <utility>
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<std::uint64_t>
try_acquire_read(const ByteStream& stream);
[[nodiscard]] std::optional<std::uint64_t>
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<const std::byte> 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<const std::byte> 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<std::unique_ptr<Driver>> 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<BufferLease> allocate_buffer(std::size_t bytes);
[[nodiscard]] Void::Result::Result<ByteStream> create_mock_stream();
[[nodiscard]] MockController* mock_controller() noexcept;
[[nodiscard]] Void::Result::Result<ByteStream> adopt_fd(int fd);
[[nodiscard]] Void::Result::Result<std::pair<ByteStream, ByteStream>>
create_socket_pair();
[[nodiscard]] Void::Result::Result<std::size_t> poll_once(
std::optional<std::chrono::nanoseconds> max_wait = std::chrono::nanoseconds{0});
void wake() noexcept;
void request_stop() noexcept;
[[nodiscard]] Void::Result::Result<void> shutdown_and_join();
private:
Driver(std::shared_ptr<detail::DriverBackend> backend,
std::shared_ptr<detail::OwnedBufferTracker> buffer_tracker) noexcept;
std::shared_ptr<detail::DriverBackend> backend_{};
std::shared_ptr<detail::OwnedBufferTracker> buffer_tracker_{};
std::unique_ptr<MockController> mock_controller_{};
};
} // namespace Void::IO
+182
View File
@@ -0,0 +1,182 @@
#pragma once
#include <Void/Async/Task.hpp>
#include <Void/IO/Detail/Backend.hpp>
#include <Void/IO/Types.hpp>
#include <cstddef>
#include <expected>
#include <memory>
#include <span>
#include <utility>
namespace Void::IO
{
class ByteStream
{
public:
ByteStream() noexcept = default;
explicit ByteStream(std::shared_ptr<detail::StreamState> 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<Void::Result::Result<Transfer>> read_some(
std::span<std::byte> 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<Void::Result::Result<Transfer>> write_some(
std::span<const std::byte> 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<Void::Result::Result<Transfer>> 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<Void::Result::Result<Transfer>> write_some_owned(
const BufferLease& lease, Async::OperationOptions options = {})
{
co_return co_await write_some(lease.readable(), std::move(options));
}
[[nodiscard]] Coro::Task<Void::Result::Result<void>> 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<detail::StreamState> state_{};
};
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
read_exact(ByteStream& stream,
std::span<std::byte> 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<std::expected<std::size_t, ComposedTransferError>>
write_all(ByteStream& stream,
std::span<const std::byte> 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
+292
View File
@@ -0,0 +1,292 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <memory_resource>
#include <new>
#include <span>
#include <string>
#include <system_error>
#include <utility>
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<std::int32_t>(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<void> 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<std::size_t> 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<BufferLease> allocate(
const std::shared_ptr<detail::OwnedBufferTracker>& 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<std::byte*>(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<std::byte> writable() noexcept
{
return (data_ != nullptr) ? std::span<std::byte>{data_, capacity_} : std::span<std::byte>{};
}
[[nodiscard]] std::span<const std::byte> readable() const noexcept
{
return (data_ != nullptr) ? std::span<const std::byte>{data_, valid_bytes_}
: std::span<const std::byte>{};
}
private:
std::shared_ptr<detail::OwnedBufferTracker> tracker_{};
std::byte* data_{nullptr};
std::size_t capacity_{0};
std::size_t valid_bytes_{0};
};
} // namespace Void::IO
+249
View File
@@ -0,0 +1,249 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Memory/BudgetResource.hpp>
#include <Void/Runtime/Options.hpp>
#include <Void/Runtime/ResourceGraph.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
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<void> 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<std::string> 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<Host> 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<Void::Memory::BudgetResource>(
options.limits.max_owned_memory_bytes);
return Host{
std::move(options),
std::move(*plan),
EmbeddedResources{},
std::move(budget)};
}
[[nodiscard]] static Void::Result::Result<Host> 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<Void::Memory::BudgetResource> budget;
if (embedded.memory_budget == nullptr) {
budget = std::make_unique<Void::Memory::BudgetResource>(
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<Void::Memory::BudgetResource> 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<Void::Memory::BudgetResource> 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<void> add_resource(ResourceNode node)
{
return graph_.add_node(std::move(node));
}
[[nodiscard]] Void::Result::Result<void> 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<Host> 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<Void::Memory::BudgetResource> budget;
if (emb.memory_budget == nullptr) {
budget = std::make_unique<Void::Memory::BudgetResource>(
opts.limits.max_owned_memory_bytes);
}
return Host{std::move(opts), std::move(*plan), emb, std::move(budget)};
}
private:
Options options_{};
std::optional<EmbeddedResources> embedded_{};
ResourceGraph graph_;
};
} // namespace Void::Runtime
+168
View File
@@ -0,0 +1,168 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/IO/Types.hpp>
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <string>
#include <thread>
#include <utility>
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<std::int32_t>(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<std::uint32_t>(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<void> 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
+153
View File
@@ -0,0 +1,153 @@
#pragma once
#include <Void/Algorithms/Graph.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Runtime/Options.hpp>
#include <algorithm>
#include <cstddef>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
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<std::string> startup_order{};
std::vector<std::string> shutdown_order{};
};
class ResourceGraph
{
public:
[[nodiscard]] Void::Result::Result<void> 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<void> 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<LifecyclePlan> validate_and_plan() const
{
const std::size_t n = nodes_.size();
std::vector<std::vector<std::size_t>> 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<ResourceNode> nodes_{};
std::unordered_map<std::string, std::size_t> index_by_id_{};
std::vector<PendingEdge> edges_{};
};
} // namespace Void::Runtime
+2
View File
@@ -44,6 +44,8 @@ namespace Void::Testing::Detail
} }
void handle_assertion(AssertionResult result); void handle_assertion(AssertionResult result);
[[nodiscard]] std::size_t stray_assertion_count() noexcept;
void reset_stray_assertion_count() noexcept;
struct RequireFailure : std::runtime_error { struct RequireFailure : std::runtime_error {
using std::runtime_error::runtime_error; using std::runtime_error::runtime_error;
+110
View File
@@ -0,0 +1,110 @@
#pragma once
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Config.hpp>
#include <cstddef>
#include <exception>
#include <string>
#include <utility>
#include <vector>
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 <typename Fn>
[[nodiscard]] bool run(Fn&& fn)
{
local_ = TestResult{};
try {
std::forward<Fn>(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<AssertionResult>& 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
+11
View File
@@ -12,6 +12,9 @@
namespace Void::Testing 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 AssertKind : uint8_t { Expect, Require, Assert };
enum class TestState : uint8_t { Passed, Failed, Skipped, Crashed }; enum class TestState : uint8_t { Passed, Failed, Skipped, Crashed };
@@ -55,6 +58,10 @@ namespace Void::Testing
std::string crash_info; std::string crash_info;
std::string stacktrace; std::string stacktrace;
std::vector<std::string> tags; std::vector<std::string> tags;
bool assertions_truncated{false};
std::size_t dropped_assertions{0};
std::size_t diagnostic_bytes{0};
std::string cleanup_error;
}; };
struct SuiteResult { struct SuiteResult {
@@ -70,6 +77,7 @@ namespace Void::Testing
int skipped{0}; int skipped{0};
int crashed{0}; int crashed{0};
int total{0}; int total{0};
std::string config_error;
}; };
struct RunConfig { struct RunConfig {
@@ -84,9 +92,12 @@ namespace Void::Testing
bool no_color{false}; bool no_color{false};
bool shuffle{false}; bool shuffle{false};
bool show_help{false}; bool show_help{false};
bool allow_empty{false};
unsigned repeat{1}; unsigned repeat{1};
unsigned random_seed{0}; unsigned random_seed{0};
unsigned parallel_threads{0}; // 0 = sequential unsigned parallel_threads{0}; // 0 = sequential
std::string parse_error;
std::string selftest_child;
}; };
} // namespace Void::Testing } // namespace Void::Testing
+494
View File
@@ -0,0 +1,494 @@
#pragma once
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <chrono>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <expected>
#include <functional>
#include <limits>
#include <optional>
#include <random>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
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<std::uint64_t>(lo);
const std::uint64_t uhi = static_cast<std::uint64_t>(hi);
const std::uint64_t span = uhi - ulo;
if (span == std::numeric_limits<std::uint64_t>::max()) {
return static_cast<std::int64_t>(next_u64());
}
const std::uint64_t pick = next_bounded(span + 1ULL);
return static_cast<std::int64_t>(ulo + pick);
}
[[nodiscard]] bool next_bool() noexcept
{
return (next_u64() & 1ULL) != 0ULL;
}
[[nodiscard]] std::vector<std::byte> next_bytes(std::size_t max_len)
{
const std::size_t len =
static_cast<std::size_t>(next_bounded(max_len + 1ULL));
std::vector<std::byte> out(len);
for (std::size_t i = 0; i < len; ++i) {
out[i] = static_cast<std::byte>(next_u64() & 0xFFULL);
}
return out;
}
[[nodiscard]] std::vector<int> next_ints(
std::size_t max_len, int lo, int hi)
{
const std::size_t len =
static_cast<std::size_t>(next_bounded(max_len + 1ULL));
std::vector<int> out;
out.reserve(len);
for (std::size_t i = 0; i < len; ++i) {
out.push_back(static_cast<int>(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 <typename T>
struct PropertyResult {
PropertyStatus status{PropertyStatus::passed};
ReplayToken replay{};
unsigned cases_executed{0};
unsigned discards{0};
unsigned shrink_steps{0};
std::optional<T> original_failure{};
std::optional<T> minimal_failure{};
std::vector<T> shrink_path{};
std::string message{};
};
namespace Detail
{
template <typename T>
struct UnwrapOptional {
using type = T;
static constexpr bool is_optional = false;
};
template <typename U>
struct UnwrapOptional<std::optional<U>> {
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<std::chrono::nanoseconds>(now - start)
: std::chrono::nanoseconds{0};
}
} // namespace Detail
template <typename GeneratorFn, typename PredicateFn, typename ShrinkFn>
requires std::invocable<
ShrinkFn,
const typename Detail::UnwrapOptional<
std::remove_cvref_t<std::invoke_result_t<GeneratorFn, DeterministicRng&>>>::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<std::invoke_result_t<GeneratorFn, DeterministicRng&>>;
using T = typename Detail::UnwrapOptional<GenRaw>::type;
PropertyResult<T> 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<unsigned>::max() / opts.max_discard_factor
? opts.cases * opts.max_discard_factor
: std::numeric_limits<unsigned>::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<T> value_opt;
if constexpr (Detail::UnwrapOptional<GenRaw>::is_optional) {
value_opt = std::forward<GeneratorFn>(gen)(rng);
} else {
value_opt.emplace(std::forward<GeneratorFn>(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::invoke_result_t<PredicateFn, const T&>>;
std::optional<bool> ok;
if constexpr (Detail::UnwrapOptional<PredRaw>::is_optional) {
ok = std::forward<PredicateFn>(pred)(*value_opt);
} else {
ok = static_cast<bool>(std::forward<PredicateFn>(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<bool> cand_ok;
if constexpr (Detail::UnwrapOptional<PredRaw>::is_optional) {
cand_ok = pred(cand);
} else {
cand_ok = static_cast<bool>(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 <typename GeneratorFn, typename PredicateFn>
[[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<std::invoke_result_t<GeneratorFn, DeterministicRng&>>;
using T = typename Detail::UnwrapOptional<GenRaw>::type;
auto no_shrink = [](const T&) -> std::vector<T> { return {}; };
return check_property(
std::forward<GeneratorFn>(gen),
std::forward<PredicateFn>(pred),
no_shrink,
opts,
base_token,
clock);
}
template <typename GeneratorFn, typename PredicateFn>
[[nodiscard]] bool replay_property_case(
GeneratorFn&& gen,
PredicateFn&& pred,
ReplayToken token)
{
DeterministicRng rng{token};
auto val = std::forward<GeneratorFn>(gen)(rng);
return static_cast<bool>(std::forward<PredicateFn>(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<void()> 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<void()> 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<std::ptrdiff_t>(ready_index));
const std::int64_t now_ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(
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<std::size_t, std::string>
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<ScheduleEvent>& trace() const noexcept { return trace_; }
private:
struct Action {
std::uint64_t id{0};
std::string label{};
std::function<void()> fn{};
};
struct Timer {
Void::Time::ManualClock::time_point fire_at{};
std::uint64_t id{0};
std::string label{};
std::function<void()> fn{};
};
std::size_t promote_due_timers()
{
const auto now = clock_.now();
std::vector<Timer> due;
std::vector<Timer> 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<Action> ready_{};
std::vector<Timer> timers_{};
std::vector<ScheduleEvent> trace_{};
};
} // namespace Void::Testing
+1
View File
@@ -16,6 +16,7 @@ namespace Void::Testing
} }
RunConfig parse_args(int argc, char** argv); RunConfig parse_args(int argc, char** argv);
RunResult run(const RunConfig& config); RunResult run(const RunConfig& config);
TestResult execute_case(TestCase& test_case);
int main(int argc, char** argv); int main(int argc, char** argv);
private: private:
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <span>
#include <string>
#include <string_view>
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<const std::string> args = {},
ProcessTestOptions options = {});
} // namespace Void::Testing
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(IO
INTERNAL_DEPS Core Functional Time Memory Async
)
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Runtime
INTERNAL_DEPS Core Functional Time Memory Algorithms Async IO
)
+54 -12
View File
@@ -1,17 +1,59 @@
#include <Void/Testing/Assert.hpp> #include <Void/Testing/Assert.hpp>
namespace Void::Testing::Detail {
void handle_assertion(AssertionResult result) { #include <atomic>
namespace Void::Testing::Detail
{
namespace
{
std::atomic<std::size_t> 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(); auto& ctx = TestContext::current();
if (ctx.current_result) { if (!ctx.current_result) {
ctx.current_result->assertions.push_back(std::move(result)); g_stray_assertions.fetch_add(1, std::memory_order_acq_rel);
const auto& last = ctx.current_result->assertions.back(); return;
if (!last.passed) { }
ctx.current_result->state = TestState::Failed;
if (last.kind == AssertKind::Require || last.kind == AssertKind::Assert) { TestResult* tr = ctx.current_result;
ctx.should_abort = true; const bool passed = result.passed;
throw RequireFailure{last.message}; 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
+271 -42
View File
@@ -37,50 +37,146 @@
#endif #endif
#include <algorithm> #include <algorithm>
#include <chrono>
#include <csignal> #include <csignal>
#include <cstdlib>
#include <format> #include <format>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <limits>
#include <memory> #include <memory>
#include <random> #include <random>
#include <regex> #include <regex>
#include <thread>
#include <unordered_map> #include <unordered_map>
namespace Void::Testing namespace Void::Testing
{ {
namespace
{
class OwningJUnitReporter final : public Reporter
{
public:
OwningJUnitReporter(std::unique_ptr<std::ofstream> 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<std::ofstream> 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<unsigned>::max()) {
return false;
}
out = static_cast<unsigned>(val);
return true;
} catch (...) {
return false;
}
}
} // namespace
RunConfig Runner::parse_args(int argc, char** argv) RunConfig Runner::parse_args(int argc, char** argv)
{ {
RunConfig config; 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) { for (int i = 1; i < argc; ++i) {
std::string arg = argv[i]; std::string arg = argv[i];
if ((arg == "--filter" || arg == "--suite" || if (arg == "--filter") {
arg == "--reporter" || arg == "--output" || (void)need_val(arg, i, config.filter_pattern);
arg == "--tag" || arg == "--seed" || arg == "--repeat" || } else if (arg == "--suite") {
arg == "--log-file" || arg == "--parallel") && (void)need_val(arg, i, config.suite_filter);
i + 1 < argc) { } else if (arg == "--reporter") {
std::string val = argv[++i]; (void)need_val(arg, i, config.reporter);
if (arg == "--filter") { } else if (arg == "--output") {
config.filter_pattern = val; (void)need_val(arg, i, config.output_file);
} else if (arg == "--suite") { } else if (arg == "--tag") {
config.suite_filter = val; (void)need_val(arg, i, config.tag_filter);
} else if (arg == "--reporter") { } else if (arg == "--log-file") {
config.reporter = val; (void)need_val(arg, i, config.log_file);
} else if (arg == "--output") { } else if (arg == "--selftest-child") {
config.output_file = val; (void)need_val(arg, i, config.selftest_child);
} else if (arg == "--tag") { } else if (arg == "--seed") {
config.tag_filter = val; std::string val;
} else if (arg == "--log-file") { if (need_val(arg, i, val)) {
config.log_file = val; unsigned parsed = 0;
} else if (arg == "--seed") { if (!parse_unsigned_strict(val, parsed)) {
config.shuffle = true; config.parse_error = std::format("Invalid --seed value: {}", val);
config.random_seed = } else {
static_cast<unsigned>(std::stoul(val)); config.shuffle = true;
} else if (arg == "--repeat") { config.random_seed = parsed;
config.repeat = static_cast<unsigned>(std::stoul(val)); }
} else if (arg == "--parallel") { }
config.parallel_threads = } else if (arg == "--repeat") {
static_cast<unsigned>(std::stoul(val)); 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") { } else if (arg == "--help") {
config.show_help = true; config.show_help = true;
@@ -90,10 +186,16 @@ namespace Void::Testing
config.verbose = true; config.verbose = true;
} else if (arg == "--no-color") { } else if (arg == "--no-color") {
config.no_color = true; config.no_color = true;
} else if (arg == "--allow-empty") {
config.allow_empty = true;
} else if (arg == "--shuffle") { } else if (arg == "--shuffle") {
config.shuffle = true; config.shuffle = true;
std::random_device rd; std::random_device rd;
config.random_seed = 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; return config;
@@ -142,14 +244,19 @@ namespace Void::Testing
std::unique_ptr<Reporter> Runner::create_reporter(const RunConfig& config) std::unique_ptr<Reporter> Runner::create_reporter(const RunConfig& config)
{ {
if (config.reporter == "junit") { if (config.reporter == "junit") {
static std::ofstream file{config.output_file.empty() const std::string path =
? "test_results.xml" config.output_file.empty() ? "test_results.xml" : config.output_file;
: config.output_file}; auto file = std::make_unique<std::ofstream>(path, std::ios::out | std::ios::trunc);
return std::make_unique<JUnitReporter>(file); return std::make_unique<OwningJUnitReporter>(std::move(file), nullptr);
} }
return std::make_unique<ConsoleReporter>(std::cout, !config.no_color); return std::make_unique<ConsoleReporter>(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 Runner::execute_test(TestCase& test_case)
{ {
TestResult result; TestResult result;
@@ -163,6 +270,7 @@ namespace Void::Testing
: test_case.skip_reason; : test_case.skip_reason;
return result; return result;
} }
ContextRestorer ctx_restorer;
Detail::TestContext::current().current_result = &result; Detail::TestContext::current().current_result = &result;
Detail::TestContext::current().should_abort = false; Detail::TestContext::current().should_abort = false;
@@ -214,7 +322,6 @@ namespace Void::Testing
auto end = std::chrono::high_resolution_clock::now(); auto end = std::chrono::high_resolution_clock::now();
result.duration = end - start; result.duration = end - start;
Detail::uninstall_signal_handlers(); Detail::uninstall_signal_handlers();
Detail::TestContext::current().current_result = nullptr;
if (result.state != TestState::Skipped && if (result.state != TestState::Skipped &&
result.state != TestState::Crashed) { result.state != TestState::Crashed) {
@@ -223,7 +330,7 @@ namespace Void::Testing
[](const auto& a) { return !a.passed; }); [](const auto& a) { return !a.passed; });
// An exception that escaped the body fails it too, with no failed // An exception that escaped the body fails it too, with no failed
// assertion recorded. // assertion recorded.
const bool unhandled = !result.crash_info.empty(); const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
result.state = result.state =
any || unhandled ? TestState::Failed : TestState::Passed; any || unhandled ? TestState::Failed : TestState::Passed;
} }
@@ -245,6 +352,7 @@ namespace Void::Testing
: test_case.skip_reason; : test_case.skip_reason;
return result; return result;
} }
ContextRestorer ctx_restorer;
Detail::TestContext::current().current_result = &result; Detail::TestContext::current().current_result = &result;
Detail::TestContext::current().should_abort = false; Detail::TestContext::current().should_abort = false;
@@ -265,7 +373,6 @@ namespace Void::Testing
} }
auto end = std::chrono::high_resolution_clock::now(); auto end = std::chrono::high_resolution_clock::now();
result.duration = end - start; result.duration = end - start;
Detail::TestContext::current().current_result = nullptr;
if (result.state != TestState::Skipped && if (result.state != TestState::Skipped &&
result.state != TestState::Crashed) { result.state != TestState::Crashed) {
@@ -274,29 +381,58 @@ namespace Void::Testing
[](const auto& a) { return !a.passed; }); [](const auto& a) { return !a.passed; });
// An exception that escaped the body fails it too, with no failed // An exception that escaped the body fails it too, with no failed
// assertion recorded. // assertion recorded.
const bool unhandled = !result.crash_info.empty(); const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
result.state = result.state =
any || unhandled ? TestState::Failed : TestState::Passed; any || unhandled ? TestState::Failed : TestState::Passed;
} }
return result; 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) { if (test_case.fixture_create) {
void* fixture = test_case.fixture_create(); void* fixture = test_case.fixture_create();
Detail::TestContext::current().fixture = fixture; 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 { try {
test_case.fixture_setup(fixture); if (test_case.fixture_setup) {
test_case.fixture_setup(fixture);
}
test_case.run(); test_case.run();
test_case.fixture_teardown(fixture); run_teardown_once();
} catch (...) { } catch (...) {
test_case.fixture_teardown(fixture); run_teardown_once();
test_case.fixture_destroy(fixture); if (test_case.fixture_destroy) {
test_case.fixture_destroy(fixture);
}
Detail::TestContext::current().fixture = nullptr; Detail::TestContext::current().fixture = nullptr;
throw; throw;
} }
test_case.fixture_destroy(fixture); if (test_case.fixture_destroy) {
test_case.fixture_destroy(fixture);
}
Detail::TestContext::current().fixture = nullptr; Detail::TestContext::current().fixture = nullptr;
} else { } else {
test_case.run(); test_case.run();
@@ -401,6 +537,8 @@ namespace Void::Testing
<< apply(dim, "Enable verbose output") << "\n" << apply(dim, "Enable verbose output") << "\n"
<< " " << opt("--no-color") << " " << opt("--no-color")
<< apply(dim, "Disable colored console output") << "\n" << apply(dim, "Disable colored console output") << "\n"
<< " " << opt("--allow-empty")
<< apply(dim, "Do not fail when selection matches zero tests") << "\n"
<< " " << opt("--help") << " " << opt("--help")
<< apply(dim, "Show this help message") << "\n" << apply(dim, "Show this help message") << "\n"
<< "\n" << "\n"
@@ -417,9 +555,72 @@ namespace Void::Testing
return {}; 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 all_tests = Detail::Registry::instance().tests();
auto tests = filter_tests(all_tests, config); 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> reporter;
if (config.reporter == "junit") {
const std::string path =
config.output_file.empty() ? "test_results.xml" : config.output_file;
auto file = std::make_unique<std::ofstream>(
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<OwningJUnitReporter>(
std::move(file), &report_write_error);
} else {
reporter = create_reporter(config);
}
// ── Optional: file logger sink (requires Void::Logging) ────────────────── // ── Optional: file logger sink (requires Void::Logging) ──────────────────
#ifdef VOID_HAS_LOG #ifdef VOID_HAS_LOG
@@ -661,6 +862,11 @@ namespace Void::Testing
} }
run_result.total_duration = end_time - start_time; run_result.total_duration = end_time - start_time;
reporter->on_run_end(run_result); 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 #ifdef VOID_HAS_LOG
if (log_sink) { if (log_sink) {
log_sink->info( log_sink->info(
@@ -680,7 +886,30 @@ namespace Void::Testing
int Runner::main(int argc, char** argv) int Runner::main(int argc, char** argv)
{ {
auto config = parse_args(argc, 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); auto result = run(config);
if (!result.config_error.empty()) {
return 2;
}
return (result.failed + result.crashed > 0) ? 1 : 0; return (result.failed + result.crashed > 0) ? 1 : 0;
} }
} // namespace Void::Testing } // namespace Void::Testing
+307
View File
@@ -0,0 +1,307 @@
#include <Void/Testing/Subprocess.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <cstring>
#include <filesystem>
#include <system_error>
#include <vector>
#ifndef _WIN32
#include <fcntl.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#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<char, 4096> buf{};
for (;;) {
const ssize_t n = ::read(fd, buf.data(), buf.size());
if (n > 0) {
const std::size_t got = static_cast<std::size_t>(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<const std::string> 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<std::string> 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<char*> 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<pollfd, 2> 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<std::chrono::milliseconds>(deadline - now).count();
wait_ms = static_cast<int>(std::clamp<long long>(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<const std::string>,
ProcessTestOptions)
{
ProcessTestResult res;
res.outcome = ProcessOutcome::infrastructure_error;
res.diagnostic = "Subprocess isolation not implemented on Windows";
return res;
}
#endif
} // namespace Void::Testing
+10
View File
@@ -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)
+35
View File
@@ -0,0 +1,35 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Stream.hpp>
#include <cstring>
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;
}
+10
View File
@@ -106,6 +106,16 @@ if(_has_unicode)
run_consumer(UnicodeOnly "${install_prefix}" "UnicodeOnly" ${_no_external_deps}) run_consumer(UnicodeOnly "${install_prefix}" "UnicodeOnly" ${_no_external_deps})
endif() endif()
has_modules(_has_io IO Async Memory Time Functional Core)
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. # Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation) if(_has_foundation)
+10
View File
@@ -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)
+30
View File
@@ -0,0 +1,30 @@
#include <Void/Async/Executor.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Runtime/Host.hpp>
#include <Void/Time/Clock.hpp>
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;
}
+509
View File
@@ -0,0 +1,509 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <array>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstring>
#include <memory_resource>
#include <stop_token>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
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<const std::byte> as_bytes(std::string_view sv) noexcept
{
return std::as_bytes(std::span<const char>{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<std::int32_t>(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<std::int32_t>(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<std::int32_t>(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<Transfer> zero_r{};
Void::Result::Result<Transfer> zero_w{};
auto run_zero = [](ByteStream* st,
Void::Result::Result<Transfer>* r_out,
Void::Result::Result<Transfer>* w_out) -> Void::Coro::Task<void> {
*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<std::byte, 8> rbuf1{};
std::array<std::byte, 8> rbuf2{};
const std::string payload = "hello!";
Void::Result::Result<Transfer> r1_res{};
Void::Result::Result<Transfer> r2_res{};
Void::Result::Result<Transfer> w1_res{};
auto do_read = [](ByteStream* st,
std::span<std::byte> buf,
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
*out = co_await st->read_some(buf);
};
auto do_write = [](ByteStream* st,
std::span<const std::byte> buf,
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
*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<std::int32_t>(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<Transfer> exp_res{};
auto expired_read = [](ByteStream* st,
std::span<std::byte> buf,
Void::Time::MonotonicClock::time_point dl,
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
*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<std::int32_t>(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<std::uint8_t>(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<std::byte, 16> buf{};
int resumes = 0;
Void::Result::Result<Transfer> res{};
auto task = [](ByteStream* st,
std::span<std::byte> b,
std::stop_token tok,
int* cnt,
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
*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<std::int32_t>(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<std::byte, 16> buf{};
int resumes = 0;
Void::Result::Result<Transfer> res{};
auto task = [](ByteStream* st,
std::span<std::byte> b,
std::stop_token tok,
int* cnt,
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
*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<std::byte, 8> buf{};
Void::Result::Result<Transfer> res{};
const auto dl = clock.now() + std::chrono::seconds{5};
auto task = [](ByteStream* st,
std::span<std::byte> b,
Void::Time::MonotonicClock::time_point d,
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
*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<std::int32_t>(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<std::size_t, ComposedTransferError> write_res{0};
std::expected<std::size_t, ComposedTransferError> read_res{0};
auto writer_coro = [](ByteStream* st,
std::span<const std::byte> data,
std::expected<std::size_t, ComposedTransferError>* out)
-> Void::Coro::Task<void> {
*out = co_await write_all(*st, data);
};
auto reader_coro = [](ByteStream* st,
std::span<std::byte> data,
std::expected<std::size_t, ComposedTransferError>* out)
-> Void::Coro::Task<void> {
*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<Transfer> owned_w{};
Void::Result::Result<Transfer> owned_r1{};
Void::Result::Result<Transfer> owned_r2{};
Void::Result::Result<void> close_a{};
auto write_then_close = [](ByteStream* st,
BufferLease* lw,
Void::Result::Result<Transfer>* w_out,
Void::Result::Result<void>* c_out) -> Void::Coro::Task<void> {
*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<Transfer>* r1_out,
Void::Result::Result<Transfer>* r2_out) -> Void::Coro::Task<void> {
*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<const char*>(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<void> close_b{};
auto closer = [](ByteStream* st, Void::Result::Result<void>* out) -> Void::Coro::Task<void> {
*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<bool> 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<std::byte, 32> buf{};
Void::Result::Result<Transfer> cancelled_r{};
auto wait_read = [](ByteStream* st,
std::span<std::byte> b_span,
std::stop_token tok,
Void::Result::Result<Transfer>* out) -> Void::Coro::Task<void> {
*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<std::int32_t>(IoErrorCode::cancelled));
stop_poller.store(true, std::memory_order_release);
driver.wake();
poller.join();
(void)b.valid();
}
#endif // __linux__
+193
View File
@@ -0,0 +1,193 @@
#include <Void/Async/Executor.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Memory/BudgetResource.hpp>
#include <Void/Runtime/Host.hpp>
#include <Void/Runtime/Options.hpp>
#include <Void/Runtime/ResourceGraph.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <string>
#include <string_view>
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::size_t>(
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::size_t>(std::find(up.begin(), up.end(), id) - up.begin());
};
const auto pos_down = [&](std::string_view id) {
return static_cast<std::size_t>(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<std::int32_t>(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<std::int32_t>(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<std::int32_t>(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);
}
+155
View File
@@ -0,0 +1,155 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Deterministic.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <vector>
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<int>& 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<int>& xs) {
int sum = 0;
for (int x : xs) {
sum += x;
}
return sum <= 120;
};
auto shrink_vec = [](const std::vector<int>& xs) {
std::vector<std::vector<int>> cands;
for (std::size_t i = 0; i < xs.size(); ++i) {
std::vector<int> removed = xs;
removed.erase(removed.begin() + static_cast<std::ptrdiff_t>(i));
cands.push_back(std::move(removed));
}
for (std::size_t i = 0; i < xs.size(); ++i) {
if (xs[i] > 0) {
std::vector<int> 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<int>(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<int> {
(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<std::string> 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<std::string> 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<void()> 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());
}
@@ -0,0 +1,263 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Capture.hpp>
#include <Void/Testing/Runner.hpp>
#include <Void/Testing/Subprocess.hpp>
#include <Void/Testing/Test.hpp>
#include <csignal>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <vector>
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<State*>(p)->destroy_count; },
.fixture_setup = [](void* p) { ++static_cast<State*>(p)->setup_count; },
.fixture_teardown =
[](void* p) {
++static_cast<State*>(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<State*>(p)->destroy_count; },
.fixture_setup = [](void* p) { ++static_cast<State*>(p)->setup_count; },
.fixture_teardown =
[](void* p) {
++static_cast<State*>(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<char>{f}, std::istreambuf_iterator<char>{}};
};
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("<testsuites tests=\"0\"") != std::string::npos);
}
Void::Testing::Test testing_subprocess_isolation_exit_crash_timeout_and_flood()
{
using namespace Void::Testing;
const std::string exe = current_executable_path();
require(!exe.empty());
// 1. Passing self-invocation on skipped/tiny test
{
const std::vector<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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});
}
}