- Audit roadmap vs TASKS (D-033); scope Wave 11 to M-FUNCTIONAL-03, M-TIME-03,
M-ASYNC-04/05, S-IO-03/04, S-RUNTIME-02/03 (D-034..D-036)
- Schedule VoidForge upstream requests after Wave 11 (D-037)
- Persist planner output, PREFLIGHT findings and contract addendum (D-038)
- Add AsyncErrorCode::closed, IoErrorCode::sync_failed,
RuntimeErrorCode::{self_join, shutdown_incomplete}
- Update Functional/IO/Runtime area plans and MIGRATION per C-13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
907 lines
66 KiB
Markdown
907 lines
66 KiB
Markdown
# W11-PLAN output (opus-planner, 2026-11-29)
|
||
|
||
Verbatim planner return for [W11-PLAN](W11-PLAN.md). Advisory input; root decisions are recorded in `DECISIONS.md`.
|
||
|
||
# W11-PLAN: execution-path backfill plan (opus-planner)
|
||
|
||
**Status: DONE.** The plan is ready for opus-reviewer PREFLIGHT. It is not approved, and I don't approve it myself. Nothing was written to the repository.
|
||
|
||
## Summary
|
||
|
||
- All eight tasks can be done without a forbidden dependency edge. **No `INTERNAL_DEPS` change is needed.**
|
||
- The roadmap rows leave out four real dependencies:
|
||
- The library has no thread-backed `Async::Executor`, so S-RUNTIME-02 depends on M-ASYNC-04.
|
||
- The IO `Driver` has no file workers and no run loop, so S-RUNTIME-02 depends on S-IO-03 and S-RUNTIME-03 depends on S-IO-04.
|
||
- Async has no timer primitive. M-TIME-03 adds one, and M-ASYNC-04's timed channel waits then depend on M-TIME-03.
|
||
- **Existing IO defect.** The epoll backend can release one operation's backend reference twice. A cross-thread `shutdown_and_join` can also finish an operation and close its fd while another thread's `poll_once` is inside `::read`/`::write` on it. Both fixes are assigned to S-IO-03 (opus).
|
||
- **Signal gate exists.** It is `Void::Process::SignalWatcher` in System. The plan uses it through a new Runtime port (`SignalGate`), so Runtime does not gain a System dependency.
|
||
- **S-RPC-04: defer.** It is file-disjoint, but it is not a good ride-along (reasons below).
|
||
- **Partition:** two packages by role. Package A is sonnet with the sol rows; package B is opus with the astra rows. A small root "contracts pre-commit" adds the new enumerators first, and five gates sequence the hand-offs between packages.
|
||
|
||
---
|
||
|
||
## 0. Cross-cutting evidence
|
||
|
||
- **Builds and consumers**
|
||
- The selected-module list expands to its dependencies (`CMakeLists.txt:45-71`).
|
||
- A test whose includes need an unselected header is skipped silently (`tests/CMakeLists.txt:12-41`). Every command below therefore enables all modules a new test includes.
|
||
- `--filter` is a regex search over the test name or `suite.name`, where the suite is the file stem (`src/Testing/Runner.cpp:209-225`). Filters below use `^(Stem1|Stem2)\.`.
|
||
- Warnings are `-Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers` (`cmake/Module.cmake:178`). Appending members to aggregates is therefore safe. Every enum switch must be completed; the only switches over the extended enums are the `make_*_error` mappers (`Async/Detail/Types.hpp:65-91,103-134`, `IO/Types.hpp:46-77`, `Runtime/Options.hpp:39-60`).
|
||
- The installed consumers IOOnly and RuntimeOnly run with `-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE` (`tests/package/InstalledComponents.cmake:74-80,109-117`). Adding `Threads::Threads` to IO or Runtime would break them, so the plan doesn't (D-W11-08). IO already calls `pthread_sigmask` without it (`EpollDriver.cpp:47`).
|
||
- **Executors**
|
||
- The only executor in the library is `ManualExecutor` (`Async/Executor.hpp:120-254`).
|
||
- Thread-backed executors exist only inside one test file (`tests/standalone/Async/OperationScope.cpp:25,135`).
|
||
- `ManualExecutor` releases its slot before resuming (`Executor.hpp:226-228`), so its bound excludes running work. Its `post()` bypasses the bound (`:128-135`).
|
||
- **IO**
|
||
- No thread, no run loop, no file API (`IO/Driver.hpp:59-105`). The embedder drives it with `poll_once` (`EpollDriver.cpp:1843-1847`).
|
||
- `IoLimits::file_workers` and `max_file_queue` (`IO/Types.hpp:106-107`) and `IoErrorCode::incomplete_shutdown` (`:32`) are declared but unused in `src/IO`.
|
||
- **Epoll defects (D1)**
|
||
- `complete_op_and_collect_tickets` releases the backend reference unconditionally (`EpollDriver.cpp:448`).
|
||
- The cancel path does not skip operations that already finished (`:1332-1351`).
|
||
- `drive_read`/`drive_write` call `::read` on `op->read_ptr` outside `mu_`, without marking the operation as executing (`:1462-1474`). `in_execution` is used only by the mock (`:653-671`).
|
||
- Cross-thread `EpollBackend::shutdown_and_join` finishes unretired operations and closes their fds (`:1179-1238`, close at `:1221`).
|
||
- Result: a stop arriving just after completion can double-release the reference, and shutdown racing a concurrent poller risks use-after-free or fd reuse. No test covers this; `io_epoll_cross_thread_wake_poll_and_stop_tsan` (`tests/standalone/IO/IoDriver.cpp:458-508`) stops the poller before teardown.
|
||
- **Host**
|
||
- Movable and returned by value, with `~Host() = default` (`Runtime/Host.hpp:88-94`).
|
||
- Header-only (`src/Runtime/` holds only `module.cmake`).
|
||
- `started_workers_` is always 0 (`:173`).
|
||
- **Retry consumers:** ResilienceAsync uses `Void::Retry::ExponentialBackoff` and `JitterMode` (`Resilience/AsyncPolicy.hpp:6,486,533`), so these must stay source-compatible. Its `wait_with_stop` really sleeps in 5 ms slices while reading the injected clock (`:553-575`). That is out of scope and nothing here builds on it.
|
||
|
||
---
|
||
|
||
## 1. Per-task plans
|
||
|
||
### M-FUNCTIONAL-03: pure retry decisions and a named blocking adapter (sol → sonnet)
|
||
|
||
**Baseline**
|
||
- `Functional/Retry.hpp` holds:
|
||
- backoff types in milliseconds (`:18-68`)
|
||
- `Jittered`, which uses a `thread_local mt19937_64` seeded from `random_device`, so results are not reproducible (`:76-95`)
|
||
- `Policy{max_attempts=3, max_elapsed=0 meaning unlimited}` (`:100-110`)
|
||
- `backoff_sleep`, hard-wired to `steady_clock::now()` and `sleep_for` (`:117-142`)
|
||
- `retry`/`retry_while`, which start from a default-constructed result (`:156,197`). With `max_attempts == 0` they return a default-constructed `expected`, i.e. a success, without ever calling `fn` (`:150-170,190-211`).
|
||
- `src/Functional/module.cmake` declares no dependencies.
|
||
- Existing tests: `Retry.cpp` (14 tests) and `RetryJitter.cpp` (4 tests).
|
||
|
||
**Gap:** no pure decision engine, no injected time or URBG, no validation or saturation, no explicit `no_deadline`, zero attempts can succeed, and the blocking path is unnamed.
|
||
|
||
**Minimal scope**
|
||
- A standard-library-only `RetryState`.
|
||
- A `retry_blocking` that takes injected `now` and `sleep` callables. Using callables means no Time dependency (D-W11-02).
|
||
- Every 1.x symbol keeps its behavior.
|
||
|
||
**NEW: `include/Void/Functional/RetryState.hpp`** (no `<thread>`, no Void includes). The 1.x `JitterMode` definition moves here, keeping its name and namespace.
|
||
|
||
```cpp
|
||
namespace Void::Retry {
|
||
using SteadyTimePoint = std::chrono::steady_clock::time_point;
|
||
enum class JitterMode { Full, Equal }; // EXISTING, relocated
|
||
struct NoDeadline { constexpr bool operator==(const NoDeadline&) const noexcept = default; };
|
||
inline constexpr NoDeadline no_deadline{};
|
||
struct BackoffSpec { std::chrono::nanoseconds initial{std::chrono::milliseconds{100}};
|
||
std::chrono::nanoseconds cap{std::chrono::seconds{30}};
|
||
double multiplier{2.0}; std::optional<JitterMode> jitter{}; };
|
||
struct RetrySpec { std::uint32_t max_attempts{3}; // total incl. first
|
||
std::variant<std::chrono::nanoseconds, NoDeadline> budget{std::chrono::seconds{30}};
|
||
BackoffSpec backoff{}; };
|
||
enum class RetryConfigError : std::uint8_t { zero_attempts, negative_duration, zero_budget,
|
||
nonfinite_multiplier, multiplier_below_one, cap_below_initial };
|
||
enum class RetryAction : std::uint8_t { attempt, wait_until, stop };
|
||
enum class RetryStopReason : std::uint8_t { none, succeeded, attempts_exhausted, deadline_exceeded,
|
||
not_retryable, stop_requested };
|
||
enum class AttemptOutcome : std::uint8_t { retryable_failure, permanent_failure };
|
||
struct RetryDecision { RetryAction action{RetryAction::stop}; SteadyTimePoint at{};
|
||
RetryStopReason reason{RetryStopReason::none}; std::uint32_t attempts_started{0}; };
|
||
[[nodiscard]] std::expected<void, RetryConfigError> validate(const RetrySpec&) noexcept;
|
||
[[nodiscard]] std::chrono::nanoseconds backoff_delay(const BackoffSpec&, std::uint32_t retry_index) noexcept; // saturating, unjittered
|
||
[[nodiscard]] constexpr SteadyTimePoint saturating_add(SteadyTimePoint, std::chrono::nanoseconds) noexcept;
|
||
template <std::uniform_random_bit_generator URBG = std::mt19937_64>
|
||
class RetryState {
|
||
public:
|
||
[[nodiscard]] static std::expected<RetryState, RetryConfigError>
|
||
create(const RetrySpec&, SteadyTimePoint start, URBG urbg = URBG{},
|
||
std::optional<SteadyTimePoint> admission_deadline = std::nullopt); // deadline = min(start+budget, admission)
|
||
[[nodiscard]] RetryDecision begin(SteadyTimePoint now, bool stop_requested = false) noexcept;
|
||
[[nodiscard]] RetryDecision next(SteadyTimePoint now, AttemptOutcome, bool stop_requested = false) noexcept;
|
||
[[nodiscard]] RetryDecision resume(SteadyTimePoint now, bool stop_requested = false) noexcept;
|
||
[[nodiscard]] RetryDecision succeed() noexcept;
|
||
[[nodiscard]] std::uint32_t attempts_started() const noexcept;
|
||
[[nodiscard]] std::optional<SteadyTimePoint> deadline() const noexcept;
|
||
};
|
||
template <class E> struct RetryError { RetryStopReason reason{}; std::uint32_t attempts{0};
|
||
std::optional<E> last_error{}; // empty iff no attempt ran
|
||
std::optional<RetryConfigError> config{}; };
|
||
struct RetryEveryError { template <class E> constexpr AttemptOutcome operator()(const E&) const noexcept
|
||
{ return AttemptOutcome::retryable_failure; } };
|
||
}
|
||
```
|
||
|
||
**Fixed semantics**
|
||
- `begin` returns `stop` for a stop request or `now >= deadline`; otherwise `attempt`.
|
||
- `next` checks, in order:
|
||
1. permanent failure → `not_retryable`
|
||
2. `attempts == max` → `attempts_exhausted`
|
||
3. stop requested → `stop_requested`
|
||
4. Otherwise it computes `at = saturating_add(now, jitter(backoff_delay(k)))`. If `at >= deadline` it returns `deadline_exceeded`; else `wait_until(at)`.
|
||
- `next` never returns `attempt` directly. `resume` re-checks stop and deadline and then returns `attempt`.
|
||
- Full jitter draws uniformly from [0, d] ns. Equal jitter is d/2 plus a uniform draw from [0, d − d/2].
|
||
- Backoff saturates at `cap` before conversion. Negative or non-finite inputs and `multiplier < 1` fail `create`.
|
||
|
||
**EDIT: `include/Void/Functional/Retry.hpp`** (add the include and these declarations; leave every 1.x body untouched)
|
||
|
||
```cpp
|
||
struct SteadyNow { SteadyTimePoint operator()() const noexcept { return std::chrono::steady_clock::now(); } };
|
||
struct ThreadSleep{ bool operator()(std::chrono::nanoseconds wait, std::stop_token) const; }; // cv_any+stop; false if stopped
|
||
template <class NowFn = SteadyNow, class SleepFn = ThreadSleep, class Classify = RetryEveryError,
|
||
class URBG = std::mt19937_64>
|
||
struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{}; URBG urbg{};
|
||
std::stop_token stop{}; std::optional<SteadyTimePoint> deadline{}; };
|
||
template <class F, class NowFn, class SleepFn, class Classify, class URBG> // F() -> std::expected<T,E>
|
||
[[nodiscard]] auto retry_blocking(const RetrySpec&, F&& fn, BlockingRetryOptions<NowFn,SleepFn,Classify,URBG> = {})
|
||
-> std::expected<T, RetryError<E>>;
|
||
```
|
||
|
||
- Waits are always `decision.at - options.now()`, measured in the injected domain. The adapter never calls `sleep_until(at)`.
|
||
|
||
**Unchanged 1.x:** `NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`, `Jittered`, `JitterMode`, `Policy`, `Detail::backoff_sleep`, `retry`, `retry_or_throw`, `retry_while`. The zero-attempt defect stays as it is (D-W11-03).
|
||
|
||
**Tests**
|
||
- **NEW `tests/standalone/Functional/RetryState.cpp`:**
|
||
- `retry_state_rejects_invalid_specs` (one check per `RetryConfigError`)
|
||
- `retry_state_exact_three_attempts_default`
|
||
- `retry_state_deadline_at_admission_prevents_first_attempt`
|
||
- `retry_state_backoff_overshooting_deadline_stops`
|
||
- `retry_state_no_deadline_explicit_marker`
|
||
- `retry_state_backoff_saturates_without_overflow` (multiplier 1e300, initial near max)
|
||
- `retry_state_full_equal_jitter_bounds_and_seed_reproducibility` (bounds and same-seed equality only; no exact draws)
|
||
- `retry_state_stop_prevents_next_attempt`
|
||
- `retry_state_permanent_failure_stops`
|
||
- `retry_state_saturating_add_near_max`
|
||
- **NEW `tests/standalone/Functional/RetryBlocking.cpp`.** It uses a fake clock struct local to the test, with no Time include.
|
||
- `retry_blocking_fake_clock_exact_waits_and_attempts` (zero real sleeps; recorded waits equal the backoff)
|
||
- `retry_blocking_zero_attempts_config_error_no_call`
|
||
- `retry_blocking_expired_deadline_no_call_no_success`
|
||
- `retry_blocking_last_error_and_attempt_count`
|
||
- `retry_blocking_stop_during_sleep_no_extra_attempt`
|
||
- `retry_blocking_permanent_failure_single_attempt`
|
||
- `retry_blocking_move_only_value`
|
||
- `legacy_retry_zero_attempts_behavior_pinned`
|
||
- Existing `Retry`, `RetryJitter` and `AsyncPolicy` tests must keep passing.
|
||
|
||
**Commands**
|
||
```sh
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3 -G Ninja -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3 && /tmp/void-w11-fn3/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\." && ctest --test-dir /tmp/void-w11-fn3 --output-on-failure --timeout 60'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-res -G Ninja -DVOID_ENABLED_MODULES="ResilienceAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-res && /tmp/void-w11-fn3-res/tests/VoidTests --filter "^AsyncPolicy\."'
|
||
rg -n "#include <thread>|Void/Time" include/Void/Functional/RetryState.hpp # expect no output
|
||
```
|
||
|
||
### M-TIME-03: injected-deadline domains with Async and blocking retry adapters (astra → opus)
|
||
|
||
**Baseline**
|
||
- Time: `ManualClock` starts at epoch 0 (`Time/Clock.hpp:69-130`); `remaining_until` is at `:188-208`; `src/Time/module.cmake` has no dependencies.
|
||
- Async: `is_deadline_expired(options, clock = System)` (`Async/Detail/Types.hpp:49-55`) and `OperationState::is_deadline_expired` (`Operation.hpp:160-165`) default to the host clock. `ScheduleStatusAwaiter` checks the deadline only in `await_ready`/`await_resume` and never wakes on expiry (`Executor.hpp:304-359`). `include/Void/Async` has no timer.
|
||
- IO already expires operations via the injected `clock_` on poll (`EpollDriver.cpp:739-834,1395-1443`), covered by `io_mock_stop_completion_races_and_clock_timeout`.
|
||
|
||
**Gap:** no awaitable timed wait that expires only through explicit polling, no Async retry adapter, and no conformance tests that manual-domain deadlines are never compared with the host clock.
|
||
|
||
**Minimal scope:**
|
||
- An Async `TimerQueue` (a stable min-heap ordered by `(deadline, seq)`).
|
||
- `Async::retry_async` built on `RetryState`.
|
||
- Time saturation helpers.
|
||
- Cross-adapter conformance tests.
|
||
|
||
**NEW: `include/Void/Async/Timer.hpp`**
|
||
```cpp
|
||
namespace Void::Async {
|
||
struct TimerQueueOptions { std::size_t max_timers{1024}; }; // 0 invalid
|
||
using TimerCallback = std::move_only_function<void() noexcept>;
|
||
class TimerHandle { public: bool cancel() noexcept; /* move-only; true => callback never runs */ };
|
||
class TimerQueue { // non-movable
|
||
public:
|
||
using time_point = Void::Time::MonotonicClock::time_point;
|
||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
|
||
create(Executor& completion_executor, const Void::Time::MonotonicClock& clock, TimerQueueOptions = {});
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_until(time_point when, OperationOptions = {});
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_for(std::chrono::nanoseconds, OperationOptions = {});
|
||
[[nodiscard]] std::expected<TimerHandle, AdmissionError> schedule_at(time_point when, TimerCallback on_expire);
|
||
[[nodiscard]] std::size_t poll_expired(); // fires due timers once, (deadline,seq) order, outside locks
|
||
[[nodiscard]] std::optional<time_point> next_deadline() const;
|
||
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept;
|
||
[[nodiscard]] std::size_t active_timers() const noexcept;
|
||
void close() noexcept; // pending -> stopped; new -> stopped
|
||
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept;
|
||
[[nodiscard]] Executor& executor() noexcept;
|
||
};
|
||
}
|
||
```
|
||
|
||
**Fixed semantics for `sleep_until`**
|
||
- Results: `{}` when `when` is reached and polled; `cancelled` on stop; `timeout` if `options.deadline` comes first; `overloaded` at `max_timers`; `stopped` after `close`.
|
||
- Stop or expiry settles through `OperationState`, and the continuation is dispatched through `post_completion`. A stop callback never resumes inline.
|
||
- Cancelled timers are tombstoned, and the heap is compacted so it never exceeds 2 × `max_timers`.
|
||
- Destroying the queue settles pending sleeps with `stopped`. The executor must outlive the queue.
|
||
|
||
**NEW: `include/Void/Async/Retry.hpp`** (needs gate G1, i.e. A1 integrated)
|
||
```cpp
|
||
template <class F, class Classify = Void::Retry::RetryEveryError, class URBG = std::mt19937_64>
|
||
[[nodiscard]] auto retry_async(Void::Retry::RetrySpec, F fn /* ()->expected<T,E> | Task<expected<T,E>> */,
|
||
TimerQueue& timers, OperationOptions = {}, Classify = {}, URBG = URBG{})
|
||
-> Coro::Task<std::expected<T, Void::Retry::RetryError<E>>>;
|
||
```
|
||
- "Now" comes from `timers.clock()`. The admission deadline is `options.deadline`.
|
||
- If an attempt succeeds after stop was requested, the success is returned. After stop, nothing is retried.
|
||
|
||
**EDIT: `include/Void/Time/Clock.hpp`** (NEW helpers)
|
||
```cpp
|
||
[[nodiscard]] MonotonicClock::time_point saturating_add(MonotonicClock::time_point, std::chrono::nanoseconds) noexcept;
|
||
[[nodiscard]] MonotonicClock::time_point deadline_after(const MonotonicClock&, std::chrono::nanoseconds) noexcept;
|
||
```
|
||
|
||
**Unchanged:** every existing Time and Async symbol, including the default-argument clock parameters.
|
||
|
||
**Tests**
|
||
- **NEW `tests/standalone/Async/TimerQueue.cpp`:**
|
||
- `timer_manual_advance_and_poll_fires_exactly_once`
|
||
- `timer_equal_deadlines_fire_in_submission_order`
|
||
- `timer_not_fired_without_explicit_poll`
|
||
- `timer_manual_epoch_deadline_not_compared_with_host_clock`
|
||
- `timer_manual_clock_far_future_initial_point`
|
||
- `timer_stop_before_admission_and_pending_cancelled_once`
|
||
- `timer_stop_vs_poll_race_single_result_tsan`
|
||
- `timer_capacity_overloaded_and_tombstone_bounded`
|
||
- `timer_schedule_at_cancel_vs_fire_exclusive`
|
||
- `timer_close_settles_pending_stopped`
|
||
- `timer_wait_duration_uses_injected_now`
|
||
- `timer_sleep_for_saturates`
|
||
- **NEW `tests/standalone/Async/AsyncRetry.cpp`:**
|
||
- `async_retry_manual_clock_attempts_only_after_advance_and_poll`
|
||
- `async_retry_total_deadline_expires_once`
|
||
- `async_retry_stop_during_backoff_no_further_attempt`
|
||
- `async_retry_success_after_stop_preserved`
|
||
- `async_retry_zero_attempts_no_call`
|
||
- `async_retry_task_returning_callable`
|
||
- **NEW `tests/standalone/Async/DeadlineDomains.cpp`:**
|
||
- `deadline_domain_blocking_retry_manual_clock` (`now = manual.now`; the sleep callable advances the manual clock)
|
||
- `deadline_domain_schedule_on_and_scope_admission_injected_clock`
|
||
- **NEW `tests/standalone/Time/ClockSaturation.cpp`:** `clock_saturating_add_and_deadline_after_bounds`.
|
||
|
||
**Commands**
|
||
```sh
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3 && /tmp/void-w11-time3/tests/VoidTests --filter "^(TimerQueue|AsyncRetry|DeadlineDomains|ClockSaturation|Clock|Stopwatch|OperationScope|Executor)\." && ctest --test-dir /tmp/void-w11-time3 --output-on-failure --timeout 60'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-tsan && /tmp/void-w11-time3-tsan/tests/VoidTests --filter "^(TimerQueue|AsyncRetry|DeadlineDomains)\."'
|
||
```
|
||
|
||
### M-ASYNC-04: bounded executors, cancellable channels, future pool adapter, ParallelFor (sol → sonnet)
|
||
|
||
**Baseline**
|
||
- `Executor` base: `try_post`, `post_completion` and the reservation API (`Executor.hpp:58-113`). `ManualExecutor`'s bound excludes running work (`:226-228`). No threaded executor exists.
|
||
- `Concurrency::ThreadPool` (`ThreadPool.hpp:20-187`):
|
||
- `max_queue == 0` means unbounded (`:33-38`).
|
||
- Its bound counts only the queue, because a task is popped before it runs (`:164-173`).
|
||
- `submit` throws after stop (`:85-89`).
|
||
- `try_submit` returns `nullopt` for both "full" and "stopped" (`:100-120`).
|
||
- It includes Log (`:2`).
|
||
- `Concurrency::Channel` (`Channel.hpp:13-116`): blocking only; `send(T)` consumes the value even when the channel is closed (`:24-35`); capacity 0 blocks forever (`:27-28`).
|
||
- `parallel_for` (`ParallelFor.hpp:12-26`) creates one future per index, so submission is unbounded. On the first throwing `fut.get()` it returns without joining the remaining tasks.
|
||
|
||
**Gap:** no bound that includes running work, no coroutine channel, no explicit future adapter, and chunk errors don't join.
|
||
|
||
**Minimal scope:** NEW `ThreadExecutor`, `FuturePool`, `AsyncChannel`, and a bounded `parallel_for` overload. Capacity-waiting (`async_wait_for_capacity`) and the 4 MiB channel byte budget are deferred (D-W11-13).
|
||
|
||
**NEW: `include/Void/Async/ThreadExecutor.hpp`**
|
||
```cpp
|
||
namespace Void::Async {
|
||
struct ThreadExecutorOptions { std::size_t workers{1}; std::size_t max_admitted{4096}; // queued+running; >=1
|
||
std::function<Void::Result::Result<void>(std::size_t)> before_worker_start{}; }; // fault-injection hook
|
||
struct ThreadExecutorStats { std::size_t queued, running, completion_queued; std::uint64_t rejected, legacy_posts, inline_after_join; };
|
||
class ThreadExecutor final : public Executor {
|
||
public:
|
||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<ThreadExecutor>> create(ThreadExecutorOptions = {}); // no threads
|
||
[[nodiscard]] Void::Result::Result<void> start(); // once; partial failure joins started workers
|
||
void post(std::coroutine_handle<>) override; // never rejects; counted; may exceed bound (legacy)
|
||
[[nodiscard]] std::expected<void, AdmissionError> try_post(std::coroutine_handle<>) override; // overloaded if queued+running>=max
|
||
void post_completion(std::coroutine_handle<>) override; // reserved lane; drains after close(); prioritized
|
||
[[nodiscard]] bool supports_reservation() const noexcept override; // true
|
||
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override;
|
||
void commit_reserved(std::coroutine_handle<>) override; void release_reserved() noexcept override;
|
||
[[nodiscard]] bool has_background_workers() const noexcept override; // true
|
||
void close() noexcept; // normal admission -> stopped
|
||
[[nodiscard]] Void::Result::Result<void> join(); // close+drain+join; self_join on worker
|
||
[[nodiscard]] std::size_t admitted() const noexcept; [[nodiscard]] ThreadExecutorStats stats() const noexcept;
|
||
};
|
||
}
|
||
```
|
||
|
||
**Mandatory for `ThreadExecutor`**
|
||
- Every resume runs inside `detail::ExecutorThreadGuard`; that is what `is_executor_thread` and self-join detection rely on.
|
||
- A slot is released only after the resumed handle returns.
|
||
- After `join`, `post` and `post_completion` resume inline on the caller (documented and counted). A handle is never dropped.
|
||
|
||
**NEW: `include/Void/Async/FuturePool.hpp`**
|
||
```cpp
|
||
class FuturePool { public: explicit FuturePool(ThreadExecutor&) noexcept;
|
||
template <std::invocable F> [[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
|
||
try_submit(F&& f); }; // reserve-then-transfer: f not moved on rejection; exceptions -> future
|
||
```
|
||
|
||
**NEW: `include/Void/Async/AsyncChannel.hpp`**
|
||
```cpp
|
||
enum class ChannelError : std::uint8_t { closed, empty, full, cancelled, timed_out, overloaded, invalid_argument };
|
||
struct ChannelOptions { std::size_t capacity{1024}; std::size_t max_waiters{1024}; TimerQueue* timers{nullptr}; };
|
||
template <class T> struct SendFailure { ChannelError error; T value; };
|
||
template <class T> class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>> { public:
|
||
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>> create(Executor& resume, ChannelOptions = {});
|
||
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T);
|
||
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>> send(T, OperationOptions = {});
|
||
[[nodiscard]] std::expected<T, ChannelError> try_receive();
|
||
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>> receive(OperationOptions = {});
|
||
void close() noexcept; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool is_closed() const; };
|
||
[[nodiscard]] Void::Result::Error make_async_error(ChannelError, std::string message = {});
|
||
```
|
||
- A wait with a deadline but no `timers` returns `invalid_argument`.
|
||
- `close()` hands waiting senders `closed` together with their value. Receivers drain the buffer in FIFO order, then get `closed`.
|
||
- Resumption always goes through `post_completion`, outside locks.
|
||
- The deadline part depends on gate G2.
|
||
|
||
**EDIT: `include/Void/Async/ParallelFor.hpp`**
|
||
```cpp
|
||
struct ParallelForOptions { std::size_t grain{1}; std::size_t max_concurrency{0}; std::stop_token stop{}; bool stop_on_error{true}; };
|
||
struct ParallelForError { enum class Kind : std::uint8_t { invalid_argument, rejected, stopped, failed } kind;
|
||
std::size_t chunks_total{0}, chunks_started{0}, chunks_failed{0};
|
||
std::optional<std::size_t> first_failed_chunk{}; std::exception_ptr first_exception{}; };
|
||
template <std::integral I, std::invocable<I> F>
|
||
[[nodiscard]] std::expected<void, ParallelForError> parallel_for(I first, I last, F&& f, ThreadPool&, ParallelForOptions);
|
||
```
|
||
- `max_concurrency == 0` means the pool's thread count.
|
||
- Runner tasks are submitted with `try_submit`; if rejected, the caller thread runs chunks itself.
|
||
- No new chunk starts after a stop or (with `stop_on_error`) an error.
|
||
- All started runners are always joined. The reported error is the lowest-indexed failed chunk.
|
||
- D-W11-10: the 1.x overload should wait for all futures before rethrowing.
|
||
|
||
**Root pre-commit:** `AsyncErrorCode::closed = 9`, mapped to `ErrorKind::cancelled`.
|
||
|
||
**Unchanged:** `ManualExecutor`, `Concurrency::{ThreadPool, Channel}`, the existing `parallel_for` signatures, `spawn`, `schedule_on`.
|
||
|
||
**Tests (NEW, `tests/standalone/Async/`)**
|
||
- **`ThreadExecutor.cpp`:**
|
||
- `thread_executor_create_starts_no_threads`
|
||
- `thread_executor_bound_includes_running_work` (1 worker, max 2: blocker running plus 1 queued → `overloaded`; release → accepted)
|
||
- `thread_executor_reservation_with_task_scope_preserves_task`
|
||
- `thread_executor_completion_lane_bypasses_full_normal_lane`
|
||
- `thread_executor_close_rejects_normal_drains_completion`
|
||
- `thread_executor_join_self_join_on_worker`
|
||
- `thread_executor_partial_start_failure_joins_started`
|
||
- `thread_executor_legacy_post_spawn_schedule_on_compat`
|
||
- `thread_executor_stress_tsan`
|
||
- **`FuturePool.cpp`:**
|
||
- `future_pool_overloaded_does_not_consume_callable`
|
||
- `future_pool_stopped_after_close`
|
||
- `future_pool_exception_in_future`
|
||
- `future_pool_bound_includes_running`
|
||
- **`AsyncChannel.cpp`:**
|
||
- `channel_zero_capacity_invalid`
|
||
- `channel_try_send_full_returns_value`
|
||
- `channel_send_waits_resumes_on_receive`
|
||
- `channel_producer_stop_returns_value_cancelled_once`
|
||
- `channel_close_wakes_senders_with_value_and_drains_receivers`
|
||
- `channel_deadline_requires_timers`
|
||
- `channel_deadline_times_out_once_manual_clock_poll`
|
||
- `channel_waiter_bound_overloaded`
|
||
- `channel_move_only_values`
|
||
- `channel_mpmc_fifo_tsan`
|
||
- `channel_stop_vs_send_race_single_outcome_tsan`
|
||
- **`ParallelForBounded.cpp`:**
|
||
- `parallel_for_bounded_grain_and_concurrency_limit`
|
||
- `parallel_for_bounded_stop_joins_started_no_new_chunks`
|
||
- `parallel_for_bounded_errors_join_all_lowest_index_reported`
|
||
- `parallel_for_bounded_zero_grain_invalid`
|
||
- `parallel_for_bounded_rejected_pool_runs_inline`
|
||
- `legacy_parallel_for_exception_joins_all` (only if D-W11-10 is approved)
|
||
|
||
**Commands** (for each tag, `-Werror` on the default build, plus Debug TSan and ASan+UBSan build dirs)
|
||
```sh
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4 && /tmp/void-w11-async4/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor|ThreadPool|ThreadPoolBackpressure|Channel|OperationScope|Executor)\." && ctest --test-dir /tmp/void-w11-async4 --output-on-failure --timeout 60'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-tsan && /tmp/void-w11-async4-tsan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded)\."'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-asan && /tmp/void-w11-async4-asan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."'
|
||
```
|
||
|
||
### M-ASYNC-05: EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling (sol → sonnet)
|
||
|
||
**Baseline**
|
||
- `EventBus` (`EventBus.hpp:37-284`):
|
||
- Sync `publish` iterates the live vector without the lock (`:156-164`). A handler that subscribes or unsubscribes during dispatch therefore causes undefined behavior.
|
||
- Async mode starts a private thread in the constructor (`:43-48`).
|
||
- The snapshot copies `std::function`s, so `unsubscribe` cannot retract queued copies (`:167-169`).
|
||
- A handler exception escapes the worker loop, which terminates the process (`:248-269`).
|
||
- The task queue and handler list are unbounded (`:272-278`).
|
||
- `Subscription::reset` doesn't join (`:115-121`).
|
||
- `Observable` and `Signal` iterate the live vectors (`Observable.hpp:74-77,116-119`); reentrant use is undefined behavior, and there is no threading policy.
|
||
- Existing tests: `EventBus.cpp` (12), `EventBusAsync.cpp` (4), `Observable.cpp` (14).
|
||
|
||
**Gap:** per the row.
|
||
|
||
**Minimal scope:**
|
||
- Subscription state held in `shared_ptr`, with snapshot dispatch gated per entry.
|
||
- A new injected-executor mode.
|
||
- Joins per subscription and per bus.
|
||
- Bounded nested Observable notifications.
|
||
|
||
**NEW (EDIT `EventBus.hpp`)**
|
||
```cpp
|
||
namespace Void::EventBus {
|
||
enum class Mode { Sync, Async, Injected }; // NEW enumerator
|
||
struct BusOptions { std::size_t max_subscriptions{1024}; std::size_t max_admitted_dispatches{1024};
|
||
std::function<void(std::exception_ptr)> error_sink{}; }; // outside locks
|
||
class EventBus { // EXISTING API unchanged, plus:
|
||
explicit EventBus(Void::Async::Executor& executor, BusOptions = {}); // no private thread; internal TaskScope
|
||
template <class Event> [[nodiscard]] Void::Result::Result<Subscription> try_subscribe(std::function<void(const Event&)>);
|
||
template <class Event> [[nodiscard]] Void::Result::Result<void> try_publish(const Event&); // overloaded / closed
|
||
[[nodiscard]] Void::Result::Result<void> close_and_join();
|
||
[[nodiscard]] Void::Result::Result<void> close_and_join_pumping(Void::Async::ManualExecutor&);
|
||
[[nodiscard]] std::uint64_t callback_failures() const noexcept;
|
||
class Subscription { /* EXISTING */ public: [[nodiscard]] Void::Result::Result<void> close_and_join(); };
|
||
};
|
||
}
|
||
```
|
||
|
||
**Semantics (D-W11-06)**
|
||
- 1.x `unsubscribe` stops future publishes from including the handler. In `Mode::Async` it still delivers already-queued copies, as 1.x does.
|
||
- NEW `Subscription::close_and_join` also suppresses admitted deliveries that have not started. It then waits for in-flight callbacks and resets the handler (releasing captured state) before returning.
|
||
- Calling it from the subscription's own callback returns `self_join`. Self-unsubscribe is supported.
|
||
- Callbacks run outside locks. Injected and Async modes catch callback exceptions and route them to `error_sink`, counting them. Sync `publish` still propagates exceptions as in 1.x.
|
||
|
||
**NEW (EDIT `Observable.hpp`)**
|
||
- Documented policy: single-threaded, not thread-safe, safe for reentrancy.
|
||
- `inline constexpr std::size_t kMaxPendingNotifications = 1024;`
|
||
- `Observable::try_set(T) -> Result<void>` returns `overloaded` and leaves the value unchanged.
|
||
- `dropped_notifications()`.
|
||
- A nested `set` updates the value immediately and queues `(old, new)` copies, delivered in FIFO order after the current pass.
|
||
- Unsubscribe during a pass skips that listener for the rest of the pass. Subscribing during a pass doesn't add the listener to the current pass.
|
||
- A throwing listener: its exception propagates out of the outermost `set`/`emit`, after state is restored, and queued notifications are dropped and counted.
|
||
- `Signal::emit` uses the same snapshot rules.
|
||
|
||
**Tests (NEW)**
|
||
- **`tests/standalone/Async/EventBusJoin.cpp`:**
|
||
- `bus_injected_no_private_thread_manual_pumping`
|
||
- `bus_injected_subscription_limit_overloaded`
|
||
- `bus_injected_dispatch_limit_overloaded`
|
||
- `bus_close_and_join_waits_inflight_releases_capture_tsan` (sentinel `use_count == 1` after join)
|
||
- `bus_unsubscribe_during_dispatch_prevents_later_admission`
|
||
- `bus_self_unsubscribe_ok_self_join_rejected`
|
||
- `bus_callback_throw_to_error_sink_others_run`
|
||
- `bus_legacy_async_unsubscribe_keeps_queued_copy` (pins 1.x)
|
||
- `bus_sync_reentrant_subscribe_unsubscribe_asan`
|
||
- `bus_publish_after_close_closed`
|
||
- **`tests/standalone/Async/ObservableReentrancy.cpp`:**
|
||
- `observable_nested_set_fifo`
|
||
- `observable_unsubscribe_in_listener_skips_rest`
|
||
- `observable_subscribe_in_listener_not_current_pass`
|
||
- `observable_try_set_overloaded_when_pending_full`
|
||
- `observable_listener_throw_restores_state`
|
||
- `observable_self_unsubscribe_releases_capture`
|
||
- `signal_reentrant_connect_disconnect_during_emit`
|
||
|
||
**Commands:** same form as M-ASYNC-04 with `--filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."`, plus TSan and ASan dirs `/tmp/void-w11-async5{,-tsan,-asan}`.
|
||
|
||
### S-IO-03: bounded positional file workers, serialization, sync, active-cancel (astra → opus)
|
||
|
||
**Baseline:** see §0, including the D1 defects; there is no pread, pwrite or fsync anywhere in `src/IO`. `validate_limits` ignores the file fields (`IO/Types.hpp:110-122`).
|
||
|
||
**Gap:** the whole file path, plus a shutdown that joins workers safely.
|
||
|
||
**Minimal scope:**
|
||
- A file worker pool in a NEW translation unit, shared by the mock and epoll backends through `BaseBackend`.
|
||
- An injectable syscall shim.
|
||
- Explicit worker start.
|
||
- The D1 correctness fixes.
|
||
|
||
**NEW: `include/Void/IO/File.hpp`**
|
||
```cpp
|
||
namespace Void::IO {
|
||
struct FileOpenOptions { bool read{true}, write{false}, create{false}, truncate{false}, exclusive{false}; std::uint32_t mode{0600}; };
|
||
enum class SyncMode : std::uint8_t { data, full };
|
||
struct FileSyscallResult { std::int64_t value{0}; int error{0}; };
|
||
class FileSyscalls { public: virtual ~FileSyscalls() = default;
|
||
[[nodiscard]] virtual FileSyscallResult pread(int, std::span<std::byte>, std::uint64_t) noexcept;
|
||
[[nodiscard]] virtual FileSyscallResult pwrite(int, std::span<const std::byte>, std::uint64_t) noexcept;
|
||
[[nodiscard]] virtual FileSyscallResult sync(int, SyncMode) noexcept;
|
||
[[nodiscard]] virtual FileSyscallResult close(int) noexcept;
|
||
[[nodiscard]] static FileSyscalls& native() noexcept; };
|
||
class File { public: /* move-only */ [[nodiscard]] bool valid() const noexcept; [[nodiscard]] DescriptorId id() const noexcept;
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(std::uint64_t, BufferLease&, Async::OperationOptions = {});
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at_owned(std::uint64_t, const BufferLease&, Async::OperationOptions = {});
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(SyncMode = SyncMode::full, Async::OperationOptions = {});
|
||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(Async::OperationOptions = {}); };
|
||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> read_exact_at(File&, std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> write_all_at(File&, std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||
}
|
||
```
|
||
|
||
**EDITs**
|
||
- `Driver.hpp` gains:
|
||
- `Result<File> open_file(const std::filesystem::path&, FileOpenOptions = {})`
|
||
- `Result<File> adopt_file_fd(int)`
|
||
- `Result<void> start_file_workers()` (explicit, once; D-W11-11)
|
||
- `Result<std::size_t> run_file_work(std::size_t max_requests = 1)` (manual stepping when no workers are running)
|
||
- `Types.hpp`:
|
||
- `BackendOptions::file_syscalls{nullptr}` (appended; borrowed)
|
||
- `DriverTelemetry` gains `queued_file_requests`, `active_file_requests`, `file_workers_running` (appended)
|
||
- `validate_limits` rejects `max_file_queue == 0`
|
||
- Root pre-commit: `IoErrorCode::sync_failed = 12`, mapped to `ErrorKind::io`
|
||
- `Detail/Backend.hpp` gains file submit virtuals.
|
||
- `EpollDriver.cpp` integrates the pool and the shutdown changes.
|
||
- NEW `src/IO/FileWorkers.{hpp,cpp}`; the `.hpp` is private and not globbed.
|
||
|
||
**Fixed semantics**
|
||
- **Admission:** a stopped or expired request, or a closed driver, is rejected before it is queued. `max_file_queue` counts queued requests; `max_operations` counts queued and active. Either limit returns `overloaded`. A zero-length request returns `{0, false}`. Offset plus length overflowing gives `invalid_argument`.
|
||
- **Ordering:** writes and syncs on one file run in admission order, at most one active at a time. Reads may run concurrently. Each request is exactly one syscall, with EINTR retried. A short transfer returns the bytes actually moved; a 0-byte read of a nonzero length means EOF.
|
||
- **Queued stop or expiry:** the request is removed and completes `cancelled` or `timeout`. Writes and syncs carry `DomainOutcomeKind::not_committed`. Expiry is checked by the driver clock in `poll_once` and again at worker dequeue.
|
||
- **Active stop or expiry:** recorded as intent only. The span or lease and the telemetry stay retained, and the result is the syscall's actual outcome. A sync that succeeds after a stop is a success. A sync that fails returns `sync_failed` with the native errno and `DomainOutcomeKind::unknown`.
|
||
- **`shutdown_and_join`** keeps its 1.x signature with extended behavior:
|
||
1. Close admission.
|
||
2. Cancel queued socket and file operations.
|
||
3. Wait for in-flight syscalls and for any concurrent `poll_once` turn (poll-owner exclusion).
|
||
4. Join the workers.
|
||
5. Only then close the fds, epoll and eventfd.
|
||
Called from a worker, or from inside poll dispatch, it returns `Async::make_async_error(AdmissionError::self_join)`.
|
||
- **D1 fixes (mandatory):**
|
||
- Release the backend reference only if this call retired the operation.
|
||
- The cancel and expire paths skip retired operations.
|
||
- Epoll marks an operation `in_execution` under `mu_` before its syscall.
|
||
|
||
**Tests: NEW `tests/standalone/IO/IoFile.cpp`**
|
||
- `io_file_native_roundtrip_isolated_tmpdir`
|
||
- `io_file_short_write_preserves_progress_write_all_at`
|
||
- `io_file_writes_syncs_serialized_admission_order`
|
||
- `io_file_reads_concurrent_explicit_offsets`
|
||
- `io_file_queue_and_ops_quota_overloaded`
|
||
- `io_file_queued_cancel_not_committed_zero_effects`
|
||
- `io_file_queued_deadline_expires_once_manual_clock_poll`
|
||
- `io_file_active_timeout_retains_buffer_until_syscall_returns`
|
||
- `io_file_sync_success_after_stop_is_success`
|
||
- `io_file_sync_failure_after_stop_sync_failed_unknown_errno`
|
||
- `io_file_manual_stepping_without_workers`
|
||
- `io_file_shutdown_joins_stalled_worker_then_delivers`
|
||
- `io_file_shutdown_from_worker_self_join`
|
||
- `io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan`
|
||
- `io_stop_after_completion_releases_backend_ref_once`
|
||
|
||
**Commands**
|
||
```sh
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3 -G Ninja -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3 && /tmp/void-w11-io3/tests/VoidTests --filter "^(IoFile|IoDriver)\." && ctest --test-dir /tmp/void-w11-io3 --output-on-failure --timeout 60'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-tsan && /tmp/void-w11-io3-tsan/tests/VoidTests --filter "^(IoFile|IoDriver)\."'
|
||
# also an ASan+UBSan dir with the same filter, plus downstream IO users unfiltered:
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-users -G Ninja -DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-users && /tmp/void-w11-io3-users/tests/VoidTests && ctest --test-dir /tmp/void-w11-io3-users --output-on-failure --timeout 120'
|
||
```
|
||
|
||
### S-IO-04: embedded pumping, joined shutdown, optional adapters (sol → sonnet)
|
||
|
||
**Baseline**
|
||
- The only driving entry points are `poll_once`, `wake` and `request_stop` (`Driver.hpp:91-96`).
|
||
- Embedded pumping today is hand-written loops (`IoDriver.cpp:490-499`). `TaskScope::join_pumping` drains the executor but never polls IO (`TaskScope.hpp:645-654`).
|
||
- System adapter already exists: SystemAsync `ProcessManager` borrows a `Driver` (`System/AsyncProcess.hpp:61`, `src/SystemAsync/AsyncProcess.cpp:434`).
|
||
- Net does not use IO at all (rg finds no `Void/IO` in `include/Void/Net` or `src/Net`).
|
||
|
||
**Minimal scope:** a bounded or repeatable `shutdown`, a `run` loop, a `pump_until` helper, and a SystemAsync conformance test. The Net adapter is deferred (D-W11-07).
|
||
|
||
**NEW**
|
||
```cpp
|
||
namespace Void::IO {
|
||
struct DriverShutdownReport { bool complete{false}; std::size_t pending_operations{0}, active_file_requests{0},
|
||
open_descriptors{0}, retained_buffer_bytes{0}; }; // Types.hpp
|
||
void Driver::begin_shutdown() noexcept; // idempotent, never frees
|
||
[[nodiscard]] Void::Result::Result<DriverShutdownReport> Driver::shutdown(Async::OperationOptions); // bounded; repeatable
|
||
[[nodiscard]] Void::Result::Result<std::size_t> Driver::run(std::stop_token, std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5});
|
||
[[nodiscard]] bool Driver::quiescent() const noexcept;
|
||
struct PumpOptions { std::chrono::nanoseconds max_wait{0}; std::size_t max_turns{1u << 20};
|
||
Async::OperationOptions operation{}; Async::TimerQueue* timers{nullptr}; }; // NEW Pump.hpp
|
||
template <class Done> requires std::predicate<Done&>
|
||
[[nodiscard]] Void::Result::Result<std::size_t> pump_until(Driver&, Async::ManualExecutor&, Done&&, PumpOptions = {});
|
||
}
|
||
```
|
||
|
||
**Fixed semantics**
|
||
- `shutdown` evaluates its deadline and stop in `driver.clock()`.
|
||
- When it expires it returns `complete = false` and retains everything: no fd is closed, no buffer is released, and the workers stay alive.
|
||
- It never runs a poll turn while another thread is inside `poll_once`.
|
||
- A misuse case such as self-join is returned as an error.
|
||
- `pump_until` returns `timeout`, `cancelled` or `exhausted` and never frees work.
|
||
|
||
**Tests (NEW)**
|
||
- **`tests/standalone/IO/IoShutdown.cpp`:**
|
||
- `io_shutdown_expired_budget_incomplete_retains_stalled_file_worker`
|
||
- `io_shutdown_pending_socket_read_retains_buffer_until_delivery`
|
||
- `io_shutdown_repeated_idempotent_after_complete`
|
||
- `io_shutdown_concurrent_with_run_loop_tsan`
|
||
- `io_run_stops_on_token_and_on_shutdown`
|
||
- `io_begin_shutdown_rejects_new_admission`
|
||
- **`tests/standalone/IO/IoPump.cpp`:**
|
||
- `io_pump_until_scope_join_mock`
|
||
- `io_pump_until_deadline_injected_clock`
|
||
- `io_pump_until_max_turns_exhausted`
|
||
- `io_pump_until_drives_timer_queue`
|
||
- **`tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`:** `systemasync_driver_shutdown_pending_pipe_read_retains_and_delivers_once`.
|
||
|
||
**Commands:** `-DVOID_ENABLED_MODULES="IO;SystemAsync;Testing"`, `--filter "^(IoShutdown|IoPump|IoFile|IoDriver|SystemAsyncShutdown|SystemAsync)\."`, with a `-Werror` dir and a TSan dir (`/tmp/void-w11-io4{,-tsan}`), plus `ctest` (IOOnly and SystemAsyncOnly).
|
||
|
||
### S-RUNTIME-02: explicit start, readiness, reverse failed-start cleanup (astra → opus)
|
||
|
||
**Baseline:**
|
||
- `Host` is inert (`Host.hpp:85-178`).
|
||
- Options: `Options.hpp:89-96`. `Options::file_workers` duplicates `IoLimits::file_workers` (`:91` vs `IO/Types.hpp:106`). Note the existing exemption quirk for 4096 timers (`:149`).
|
||
- `ResourceKind` includes `service` and `exporter` (`ResourceGraph.hpp:23-31`).
|
||
- Pinned by tests: `started_worker_count() == 0` after `create` (`RuntimeHost.cpp:77-79`), and inert `add_resource` nodes (`:134-138`).
|
||
|
||
**Gap:** everything about start. The executor and file-worker prerequisites come from the hidden edges in the summary.
|
||
|
||
**NEW: `include/Void/Runtime/Lifecycle.hpp`** (plus `Detail/HostCore.hpp`; stays header-only, D-W11-09)
|
||
```cpp
|
||
namespace Void::Runtime {
|
||
enum class StartStep : std::uint8_t { signal_gate, memory_budget, cpu_executor, io_driver, file_workers, reactor, components, readiness };
|
||
class SignalGate { public: virtual ~SignalGate() = default;
|
||
[[nodiscard]] virtual Void::Result::Result<void> install() = 0; // owner thread, before any Runtime thread
|
||
virtual void uninstall() noexcept = 0; }; // same thread, after all Runtime threads joined
|
||
class HostContext { public: Async::Executor& executor(); IO::Driver* io(); const Void::Time::MonotonicClock& clock();
|
||
Void::Memory::BudgetResource& memory_budget(); std::stop_token business_stop() const; };
|
||
class Component { public: virtual ~Component() = default;
|
||
[[nodiscard]] virtual Void::Result::Result<void> start(HostContext&) = 0; // outside Host locks
|
||
[[nodiscard]] virtual Coro::Task<Void::Result::Result<void>> stop(Async::OperationOptions) = 0; };
|
||
struct StartOptions { SignalGate* signal_gate{nullptr};
|
||
std::function<Void::Result::Result<void>(StartStep)> before_step{};
|
||
std::function<void(ShutdownPhase)> on_phase{}; // used by S-RUNTIME-03
|
||
std::chrono::milliseconds readiness_timeout{5000}; };
|
||
}
|
||
// Host (EDIT): all lifecycle state in std::unique_ptr<detail::HostCore>; Host stays movable.
|
||
[[nodiscard]] Void::Result::Result<void> start(StartOptions = {}); // once: constructed->starting->running|failed_start
|
||
[[nodiscard]] bool is_ready() const noexcept; [[nodiscard]] Async::Executor* executor() noexcept;
|
||
[[nodiscard]] IO::Driver* io() noexcept; [[nodiscard]] std::optional<std::thread::id> owner_thread() const noexcept;
|
||
[[nodiscard]] std::expected<Async::JoinHandle, Async::AdmissionError> spawn(Coro::Task<void>&&, Async::OperationOptions = {});
|
||
~Host(); // non-default: reverse teardown on allowed thread
|
||
// HostBuilder (EDIT):
|
||
[[nodiscard]] Void::Result::Result<void> add_component(std::string id, ResourceKind, std::shared_ptr<Component>,
|
||
std::vector<std::string> deps = {}, bool critical = true);
|
||
```
|
||
|
||
**Root pre-commit:** `RuntimeErrorCode::self_join = 8` (→ `conflict`) and `shutdown_incomplete = 9` (→ `timeout`).
|
||
|
||
**Fixed start algorithm.** Each step pushes a cleanup action. On failure, the cleanups are popped in reverse on the starting thread, the state becomes `failed_start`, and the error is returned wrapped with context, preserving the root `Status`.
|
||
1. Validate `constructed`; record the owner thread.
|
||
2. `signal_gate->install()`.
|
||
3. Memory budget.
|
||
4. `ThreadExecutor{cpu_workers, max_admitted = limits.max_cpu_tasks}` → `start()`.
|
||
5. `IO::Driver::create`, with `io.limits.file_workers = Options::file_workers` (Runtime is authoritative).
|
||
6. `start_file_workers()`.
|
||
7. A Runtime-owned reactor thread looping `poll_once(5ms)`.
|
||
8. Components in `plan_.startup_order`.
|
||
9. Readiness: an executor `try_post` probe plus one reactor turn → `running`.
|
||
|
||
Embedded mode skips steps 4–7 (no threads). `started_worker_count()` reports the real CPU, reactor and file threads.
|
||
|
||
**Tests (NEW)**
|
||
- **`tests/standalone/Runtime/RuntimeStart.cpp`:**
|
||
- `runtime_start_spawns_workers_only_on_start_ready`
|
||
- `runtime_start_twice_invalid_state`
|
||
- `runtime_failed_start_each_step_reverse_cleanup_no_threads_no_fds` (loop over `StartStep`; `/proc/self/task` and `/proc/self/fd` deltas are 0; a fresh Host then starts)
|
||
- `runtime_component_start_failure_unwinds_reverse`
|
||
- `runtime_signal_gate_before_threads_uninstall_on_owner` (fake gate)
|
||
- `runtime_embedded_start_no_threads`
|
||
- `runtime_move_after_start_keeps_resources_valid`
|
||
- **`tests/standalone/Runtime/RuntimeSignals.cpp`.** It includes `Void/System/SignalWatcher.hpp`, so it runs only when System is enabled. It uses a test-local adapter around `Process::SignalWatcher` and SIGUSR2.
|
||
- `runtime_system_gate_mask_inherited_by_workers`
|
||
- `runtime_system_gate_mask_restored_on_owner_after_failed_start_and_teardown`
|
||
- `runtime_signal_during_start_stays_pending_and_is_drained`
|
||
|
||
**Commands**
|
||
```sh
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt2 -G Ninja -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt2 && /tmp/void-w11-rt2/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt2 --output-on-failure --timeout 60'
|
||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt2-nosys -G Ninja -DVOID_ENABLED_MODULES="Runtime;Testing" -DVOID_WARNINGS_AS_ERRORS=ON 2>&1 | grep "Skipping.*RuntimeSignals" && cmake --build /tmp/void-w11-rt2-nosys && ctest --test-dir /tmp/void-w11-rt2-nosys --output-on-failure --timeout 60'
|
||
# plus Debug TSan and ASan+UBSan dirs with "^(RuntimeStart|RuntimeSignals)\."
|
||
```
|
||
|
||
### S-RUNTIME-03: structured shutdown, repeated join, exporter-before-executor ordering, budget accounting (astra → opus)
|
||
|
||
**NEW**
|
||
```cpp
|
||
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
|
||
stopping_components, flushing_exporters, stopping_io, stopping_workers, releasing, stopped };
|
||
// ShutdownReport (EXISTING fields kept) + appended: phase, pending_business_tasks, pending_cpu_admitted,
|
||
// pending_io_operations, retained_buffer_bytes, drain_grace_expired, export_flush_expired, owner_release_pending
|
||
void Host::begin_shutdown() noexcept;
|
||
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::poll_shutdown(); // non-blocking step
|
||
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_blocking(Async::OperationOptions = {}); // repeatable
|
||
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions = {});
|
||
[[nodiscard]] std::optional<ShutdownReport> Host::last_shutdown_report() const;
|
||
```
|
||
|
||
**Fixed semantics**
|
||
- **Total deadline:** fixed at the first `begin_shutdown`, as `min(caller deadline, deadline_after(clock, total_timeout))`.
|
||
- **Phase deadlines:** drain = `min(total, phase start + drain_grace)`; flush = `min(total, phase start + export_flush_timeout)`.
|
||
- **Phase order:**
|
||
1. Close business scope admission.
|
||
2. Drain.
|
||
3. Request stop on the business scope.
|
||
4. Join it.
|
||
5. Stop non-exporter components (dependents first).
|
||
6. Stop exporters with the flush deadline. On expiry, request stop and set `export_flush_expired`, but keep IO, the reactor and the workers alive.
|
||
7. `driver->shutdown(remaining)`; if incomplete, retain it.
|
||
8. Stop and join the reactor, then `ThreadExecutor::join()`.
|
||
9. Drop component references, so exporters are destroyed before the executor is torn down.
|
||
10. Release budgets and fds. Signal-gate uninstall happens on the owner thread only; otherwise `owner_release_pending` is set and the next owner-thread call or `~Host` performs it.
|
||
- **Mandatory mechanics:**
|
||
- Component `stop` tasks are launched through `post_completion`, never through normal-lane admission, so a full queue cannot block them.
|
||
- Expiry of the total budget returns `complete = false` and state `shutdown_incomplete`, retaining all resources. The next call continues from there.
|
||
- Concurrent callers get the same final report, and there is exactly one teardown.
|
||
- Calling `shutdown_blocking` on a Runtime worker returns `RuntimeErrorCode::self_join`.
|
||
- Calling it from a non-owner thread completes every phase except the signal-gate release, as above.
|
||
|
||
**Tests: NEW `tests/standalone/Runtime/RuntimeShutdown.cpp`**
|
||
- `runtime_shutdown_concurrent_callers_single_teardown_tsan`
|
||
- `runtime_shutdown_full_normal_queue_still_delivers_completion`
|
||
- `runtime_shutdown_inflight_export_retains_io_workers_through_flush_expiry_then_completes` (exporter waits on a held mock read; total budget expires → incomplete, active ops 1, retained bytes > 0, threads alive; release → join again → complete; ordering log: `exporter_stopped < exporter_destroyed < executor_joined`)
|
||
- `runtime_shutdown_stalled_business_task_incomplete_retains`
|
||
- `runtime_shutdown_child_spawn_during_close_rejected`
|
||
- `runtime_shutdown_budget_min_caller_policy_manual_clock` (`poll_shutdown`)
|
||
- `runtime_shutdown_on_worker_self_join`
|
||
- `runtime_shutdown_non_owner_defers_gate_release`
|
||
- `runtime_shutdown_embedded_pumping`
|
||
- `runtime_destructor_joins_after_start`
|
||
|
||
**Commands:** as S-RUNTIME-02, with `"^(RuntimeShutdown|RuntimeStart|RuntimeSignals|RuntimeHost)\."`, in `-Werror`, TSan and ASan dirs, plus `ctest` (RuntimeOnly).
|
||
|
||
---
|
||
|
||
## 2. Dependency graph and INTERNAL_DEPS check
|
||
|
||
```
|
||
M-FUNCTIONAL-02✓ → M-FUNCTIONAL-03 ──(G1: RetryState)──→ M-TIME-03[Retry.hpp part]
|
||
M-TIME-02✓ → M-TIME-03[Timer.hpp part] ──(G2: TimerQueue)──→ M-ASYNC-04[AsyncChannel deadlines]
|
||
M-ASYNC-03✓ → M-ASYNC-04 → M-ASYNC-05
|
||
M-ASYNC-04 ──(G3, hidden: ThreadExecutor)──→ S-RUNTIME-02
|
||
S-IO-02✓ → S-IO-03 ──(G4, same files)──→ S-IO-04 (M-TIME-03 → S-IO-04 soft: PumpOptions::timers)
|
||
S-IO-03 ──(hidden: start_file_workers, safe shutdown)──→ S-RUNTIME-02
|
||
S-RUNTIME-01✓ → S-RUNTIME-02 → S-RUNTIME-03 ←(G5, hidden: Driver::shutdown(options))── S-IO-04
|
||
{M-ASYNC-05, S-IO-04, S-RUNTIME-03} → P-NETWORKED-02 / P-RELOADABLE-02 gates
|
||
```
|
||
|
||
**Critical path:** M-TIME-03 (Timer) → S-IO-03 → S-RUNTIME-02 → S-RUNTIME-03, with S-IO-04 needed before S-RUNTIME-03.
|
||
|
||
| Module | Change | Rule check against DEPENDENCIES.md |
|
||
| --- | --- | --- |
|
||
| Functional | none (stays empty) | Rule 1 and D-015: standard library only. `RetryState.hpp` includes no Void header. |
|
||
| Time | none | Rule 1. The helpers are `std::chrono` only. No Time→Functional edge (D-W11-02). |
|
||
| Async | none (Functional Time LogState) | Rule 2: no Log backend, no Runtime. New headers include only Async, Functional and Time. |
|
||
| IO | none internal; no Threads (D-W11-08) | Rule 2: IO depends on Async; no System, Runtime or Net. |
|
||
| Runtime | none (…Async IO) | Composes Async/IO/Time/Memory. No System edge; uses the `SignalGate` port. |
|
||
| SystemAsync, tests only | none | "System may use IO". System appears in `RuntimeSignals.cpp` as a test include only; the file is skipped without System. |
|
||
|
||
## 3. Ownership partition
|
||
|
||
**Root-owned, before dispatch (W11-0 contracts pre-commit; single writer):**
|
||
- `include/Void/Async/Detail/Types.hpp`: `AsyncErrorCode::closed = 9` plus its mapping case.
|
||
- `include/Void/IO/Types.hpp`: the enum part only, `IoErrorCode::sync_failed = 12` plus its case.
|
||
- `include/Void/Runtime/Options.hpp`: `RuntimeErrorCode::self_join = 8` and `shutdown_incomplete = 9` plus their cases.
|
||
|
||
**Root-owned throughout:**
|
||
- `docs/agent-workflow/**` (task specs, TASKS, STATE, DECISIONS, VERIFICATION)
|
||
- `CMakeLists.txt`, `cmake/*`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake` (no change planned)
|
||
- `include/Void/Functional/Error.hpp` (no change planned; no new domains)
|
||
- All integration, commits and merges
|
||
|
||
**Package A: sonnet-implementer (sol rows), run in order**
|
||
|
||
| Step | Task | Owned paths |
|
||
| --- | --- | --- |
|
||
| A1 | M-FUNCTIONAL-03 | `include/Void/Functional/RetryState.hpp` (NEW), `include/Void/Functional/Retry.hpp`, `tests/standalone/Functional/RetryState.cpp`, `tests/standalone/Functional/RetryBlocking.cpp` |
|
||
| A2 | M-ASYNC-04 | `include/Void/Async/ThreadExecutor.hpp`, `include/Void/Async/FuturePool.hpp`, `include/Void/Async/AsyncChannel.hpp` (all NEW), `include/Void/Async/ParallelFor.hpp`, `tests/standalone/Async/{ThreadExecutor,FuturePool,AsyncChannel,ParallelForBounded}.cpp`. Channel deadline waits wait for G2. |
|
||
| A3 | M-ASYNC-05 | `include/Void/Async/EventBus.hpp`, `include/Void/Async/Observable.hpp`, `tests/standalone/Async/{EventBusJoin,ObservableReentrancy}.cpp` |
|
||
| A4 | S-IO-04 (after G4: IO ownership passes from B to A) | `include/Void/IO/{Types,Driver,Pump(NEW)}.hpp`, `include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.{hpp,cpp}`, `tests/standalone/IO/{IoShutdown,IoPump}.cpp`, `tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`. Not owned: `src/SystemAsync/*` (stop and report). |
|
||
|
||
**Package B: opus-implementer (astra rows), run in order**
|
||
|
||
| Step | Task | Owned paths |
|
||
| --- | --- | --- |
|
||
| B1 | M-TIME-03 | `include/Void/Async/Timer.hpp` (NEW), `include/Void/Async/Retry.hpp` (NEW, after G1), `include/Void/Time/Clock.hpp`, `tests/standalone/Async/{TimerQueue,AsyncRetry,DeadlineDomains}.cpp`, `tests/standalone/Time/ClockSaturation.cpp` |
|
||
| B2 | S-IO-03 | `include/Void/IO/File.hpp` (NEW), `include/Void/IO/{Types,Driver}.hpp`, `include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.{hpp,cpp}` (NEW), `tests/standalone/IO/IoFile.cpp` |
|
||
| B3 | S-RUNTIME-02 (after G3 + B2) | `include/Void/Runtime/{Host,Lifecycle(NEW)}.hpp`, `include/Void/Runtime/Detail/HostCore.hpp` (NEW), `tests/standalone/Runtime/{RuntimeStart,RuntimeSignals}.cpp`, `tests/package/RuntimeOnly/main.cpp` (optional smoke) |
|
||
| B4 | S-RUNTIME-03 (after G5) | same Runtime files, plus `tests/standalone/Runtime/RuntimeShutdown.cpp` |
|
||
|
||
**Gate sequence (root integrates at each):**
|
||
- G1: A1 merged, then B1 writes `Retry.hpp`.
|
||
- G2: B1's `Timer.hpp` merged, then A2 adds channel deadlines.
|
||
- G3: A2 merged, then B3.
|
||
- G4: B2 merged, then A4.
|
||
- G5: A4 merged, then B4.
|
||
|
||
No path is owned by both packages at the same time. No worker touches `Executor.hpp`, `Operation.hpp`, `TaskScope.hpp`, `ThreadPool.hpp` or `Channel.hpp`.
|
||
|
||
## 4. System signal gate (S-RUNTIME-02)
|
||
|
||
It exists:
|
||
- `Void::Process::SignalWatcher` (`include/Void/System/SignalWatcher.hpp:16-43`). Its contract (`:13-15`): construct it before worker threads; destroy it on the creating thread.
|
||
- `create` blocks the mask with `pthread_sigmask` and opens a `signalfd` with `SFD_CLOEXEC|SFD_NONBLOCK` (`src/System/SignalWatcher.cpp:74-90`).
|
||
- `~Impl` closes the fd and restores the mask only when `pthread_equal(owner, self)` (`:27-37`). Off-thread destruction silently skips the restore.
|
||
- It has been unchanged since before baseline (`3851aeb`).
|
||
|
||
Runtime has no System edge. The S-RUNTIME-01 spec excludes it, and the Runtime area plan doesn't list it, although DEPENDENCIES.md does not forbid it.
|
||
|
||
Minimal in-wave work:
|
||
- The `SignalGate` port: installed as start step 1, uninstalled last on the owner thread, with deferred owner release if shutdown runs elsewhere.
|
||
- A test-local adapter over `SignalWatcher` inside `RuntimeSignals.cpp`.
|
||
- No System source changes.
|
||
- A production bridge module (for example a NEW `RuntimeSystem` with deps Runtime+System, following the SystemAsync pattern) is deferred to S-RUNTIME-04 (D-W11-04).
|
||
|
||
## 5. S-RPC-04 verdict: do not ride along; defer to the P3 wave
|
||
|
||
**What is in place:**
|
||
- S-RPC-03 is VERIFIED (`docs/agent-workflow/TASKS.md:129`).
|
||
- The Net WebSocket pieces are present: codec and client (`Net/WebSocket.hpp:127-185`), server sessions (`Net/Server.hpp:205-300`), `add_websocket_route` (`Net/HttpServer.hpp:93-99`), and subprotocol negotiation (`WebSocket.hpp:37-45,127-130`).
|
||
- It is file-disjoint from this wave (`include/Void/RPC`, `src/RPC`, `tests/standalone/RPC`).
|
||
|
||
**Why it should wait:**
|
||
1. `WebSocketLimits::max_output_messages` and `max_output_bytes` (`WebSocket.hpp:32-33`) are never read in `src/Net`. Server sends are a synchronous `send_all` under a per-connection mutex (`src/Net/HttpServer.cpp:930-946`). So "no memory growth under stalled consumers", and a reserved control lane for CANCEL/TERMINAL, can't be guaranteed at the transport layer without a Net change or an explicit acceptance of blocking-send semantics.
|
||
2. The client is synchronous (`WebSocket.hpp:166-170`). The planned `Task<Result<DuplexCall>>` API would naturally sit on M-ASYNC-04's `AsyncChannel`, which makes it dependent on this wave's output.
|
||
3. It is an astra row and would compete with the opus critical path.
|
||
4. It is P3, against D-027 ordering.
|
||
|
||
**Prerequisite for later:** a small Net task to enforce output budgets or a bounded non-blocking send queue, or a recorded decision to accept blocking sends.
|
||
|
||
## 6. Risks
|
||
|
||
- **D1 (high):** the existing epoll double reference release and the shutdown-versus-poller use-after-free / fd-reuse risk. It is fixed in S-IO-03 and needs TSan and ASan evidence.
|
||
- **SIGUSR2 is fatal if left pending.** A blocked SIGUSR2 that is still pending when the mask is restored takes its default action and kills the VoidTests process. The signal tests must drain the signal via `poll()` before uninstalling.
|
||
- **`/proc` counting:** thread and fd deltas can be disturbed by background threads from earlier tests. Measure deltas within a single test (tests run sequentially by default, `Runner.cpp:734-740`), with Host telemetry as the primary check.
|
||
- **ThreadExecutor join while coroutines are still suspended elsewhere** falls back to inline resume. Runtime must reach driver quiescence before executor join; the S-RUNTIME-03 phase order enforces this.
|
||
- **ManualClock with blocking waits:** `shutdown_blocking` and IO `shutdown` must re-evaluate the injected clock in short slices. Deterministic tests use `poll_shutdown` or expired deadlines rather than sleeps.
|
||
- **Internal TaskScopes in destructors:** a `TaskScope` destructor pumps or blocks (`TaskScope.hpp:562-575`). EventBus (Injected mode) and Host must join their internal scopes before destruction.
|
||
- **Behavior changes in 1.x:** Observable and Sync EventBus reentrancy used to be undefined behavior and now get defined semantics. Async-mode handler exceptions change from terminate to catch-and-count (needs D-W11-06 approval).
|
||
- **Scope size:** B3 and B4 are the largest items and carry the highest schedule risk.
|
||
- **Out of scope:** `Concurrency::Channel` with capacity 0 deadlocks (`Channel.hpp:17,27-28`), and Resilience `wait_with_stop` mixes real sleeps with the injected clock (`AsyncPolicy.hpp:553-575`).
|
||
|
||
## 7. Open decisions (recommendation for each)
|
||
|
||
| ID | Decision | Recommendation |
|
||
| --- | --- | --- |
|
||
| D-W11-01 | Where TimerQueue is owned | Async header `Async/Timer.hpp`, delivered by M-TIME-03 (astra) |
|
||
| D-W11-02 | Clock/sleeper adapter placement | Callables injected into Functional; no Time→Functional edge and no Time retry header (resolves the Functional.md wording) |
|
||
| D-W11-03 | Zero-attempt success in legacy `retry` | Keep unchanged (D-029), pin it with a test, and record it for the Wave C migration |
|
||
| D-W11-04 | How the signal gate is wired | `SignalGate` port, no Runtime→System edge; production bridge deferred to S-RUNTIME-04 |
|
||
| D-W11-05 | S-IO-03 (opus) then S-IO-04 (sonnet) in shared IO files | Accept serial hand-off at G4, with the risky shutdown and poll fixes placed in S-IO-03. No other role deviation. |
|
||
| D-W11-06 | EventBus semantics | Legacy `unsubscribe` keeps delivering queued copies in Async mode; NEW `close_and_join` gates and joins; Async-mode handler exceptions go to `error_sink` (no terminate) |
|
||
| D-W11-07 | Net adapter for IO | Defer. The System adapter is the existing SystemAsync, validated by the new shutdown test. |
|
||
| D-W11-08 | `Threads::Threads` for IO and Runtime | Don't add it. Adding it would require changing IOOnly/RuntimeOnly flags in `InstalledComponents.cmake`. |
|
||
| D-W11-09 | Runtime build shape | Stay header-only (`Detail/HostCore.hpp`), so packaging is unchanged |
|
||
| D-W11-10 | Legacy `parallel_for` on exceptions | Join all futures before rethrowing; this fixes a lifetime hazard without changing the API |
|
||
| D-W11-11 | When file workers start | Explicit `start_file_workers()`, so existing Driver users don't get hidden threads |
|
||
| D-W11-12 | S-RPC-04 | Defer to the P3 wave, after a Net output-bounds task |
|
||
| D-W11-13 | `async_wait_for_capacity` and the channel byte budget | Defer; neither is in the row acceptance |
|
||
| D-W11-14 | Host-managed TimerQueue | Defer to S-RUNTIME-04 |
|
||
| D-W11-15 | New enumerators | Root pre-commit before dispatch: `AsyncErrorCode::closed`, `IoErrorCode::sync_failed`, `RuntimeErrorCode::{self_join, shutdown_incomplete}` |
|
||
|
||
**Roadmap inconsistencies, all resolvable:**
|
||
- The S-RUNTIME-02 and S-RUNTIME-03 rows omit their M-ASYNC-04 and S-IO-03/04 prerequisites; add the edges.
|
||
- The area plan's awaited `Coro::Task` shutdown on the host's own executor would conflict with stopping that executor; the plan uses blocking and polling shutdown APIs instead.
|
||
- Runtime and IO each define a `file_workers` setting; Runtime is authoritative.
|
||
- The IO plan describes a "driver thread" but the code has none; S-IO-04 adds `run()`, and Runtime owns the reactor thread.
|
||
|
||
None of these contradicts D-001..D-036 or needs a forbidden edge.
|
||
|
||
## 8. Checks not run
|
||
|
||
- No builds or tests were run, and no probe was compiled. Every command above is proposed and unverified.
|
||
- Graph and Serena tools weren't used, so no `check_index_coverage` either. All claims come from direct file reads and `rg`.
|
||
- Not inspected in depth: the SystemAsync `ProcessManager` shutdown path, IPC and Storage test names (their commands run unfiltered), and `docs/roadmap/PERFORMANCE.md`.
|
||
- Two C++ points are assumed, not compile-checked: that the `move_only_function` used by `TimerQueue` is available, and that `std::uniform_int_distribution` is consistent across toolchains (the tests assert bounds, not exact values).
|
||
|
||
**Files most relevant to this plan:**
|
||
- `/home/faumaray/Projects/VoidLibrary/src/IO/EpollDriver.cpp`
|
||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Async/Executor.hpp`
|
||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Async/TaskScope.hpp`
|
||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Runtime/Host.hpp`
|
||
- `/home/faumaray/Projects/VoidLibrary/include/Void/Functional/Retry.hpp`
|
||
- `/home/faumaray/Projects/VoidLibrary/include/Void/System/SignalWatcher.hpp`
|
||
- `/home/faumaray/Projects/VoidLibrary/src/System/SignalWatcher.cpp`
|
||
- `/home/faumaray/Projects/VoidLibrary/tests/package/InstalledComponents.cmake`
|
||
- `/home/faumaray/Projects/VoidLibrary/src/Net/HttpServer.cpp`
|