diff --git a/docs/agent-workflow/DECISIONS.md b/docs/agent-workflow/DECISIONS.md index 9d2a714..e0021c3 100644 --- a/docs/agent-workflow/DECISIONS.md +++ b/docs/agent-workflow/DECISIONS.md @@ -73,3 +73,17 @@ plans requiring updates. Do not record a proposal as user approval. | D-030 | Create dedicated git branch (`feat/roadmap-p0-p1-foundations`) and make focused commits per completed milestone/task; leave local untracked files (`.env`, `.serena/`, `WG.conf`, `keys`) untouched | CONFIRMED by user | | D-031 | Proceed continuously across roadmap waves without pausing for confirmation between waves, and merge verified waves locally into `main` (without pushing to remote) | CONFIRMED by user | | D-032 | Push verified `main` (and active feature branches) to `origin` (`git@git.faumaray.com:Void/VoidLibrary.git`) after each verified wave merge, superseding the local-only constraint in `D-031` | CONFIRMED by user ("dont forget to push") | + +## Root decisions (2026-11-29) + +These are root-owned sequencing decisions made under D-027/D-031 (continuous roadmap-order +execution without pausing between waves). They are not new user approvals. + +| ID | Decision | Contract / rationale | +| --- | --- | --- | +| D-033 | Gap audit: `STATE.md`'s "all P2 modules complete" was inaccurate. Against the roadmap task tables, 2 P1 tasks (`M-FUNCTIONAL-03`, `M-TIME-03`) and 40 P2 tasks remain open; pre-roadmap headers (`Async/{Channel,EventBus,Observable,ParallelFor,ThreadPool}.hpp`, `Functional/{Retry,Memo}.hpp`, `Core/TypeMap.hpp`) are unchanged since `f1f9ba3`. | Roadmap order (D-027) and P2 outcome in `DELIVERY.md` | +| D-034 | Wave 11 is the execution-path backfill (`M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`, `S-RUNTIME-02`, `S-RUNTIME-03`) on `feat/roadmap-p2-wave11`. The platform half of the former "Wave 11" note (`P-NETWORKED-*`, `P-RELOADABLE-*`, `S-RPC-05`) is deferred because `P-*-02` require these Runtime/Async/IO lifecycle gates. `S-RPC-04` may ride along only if the planner finds it ready and file-disjoint. | G-EXEC, G-IO; C-03–C-06 | +| D-035 | P0 characterization tasks (`M-*-01`, `S-ALGORITHMS-01`, `S-MEMORY-01`) are not scheduled as separate waves; each follow-on spec records its observed baseline instead. Distributed `-01`/`-02` planning tasks stay with P4. | Avoids documentation-only waves; evidence lives in each task spec | +| D-036 | Remaining foundation P2 tasks (Core, Functional-04..06, Containers, Math, Text, Data, Binary, Time-04/05, Algorithms, Unicode, Memory-05, Testing-04/05) form a later parallel wave after Wave 11. | Independent of the execution-path gate | +| D-037 | VoidForge upstream requests (received 2026-11-29 from the VoidForge session on the user's behalf; source `VoidForge/docs/agent-workflow/VOIDLIBRARY_GAPS.md`) are scheduled as an out-of-band wave after Wave 11 and before the D-036 foundation wave, following the `VL-001`..`VL-013` precedent: first `VL-STREAM-01` + `VL-PROC-01` (P0), then `VL-WASM-01`, `VL-TOML-01`, `VL-MCP-01` (P1; MCP after STREAM), `VL-WIN-01` when the Windows runner needs it, and `VL-LUA-01`/`VL-STORE-01` (P2) later. Signatures are VoidLibrary-owned; peer proposals are inputs, not approvals. | Peer request is not user approval of scope beyond scheduling; licensing question escalated to the user | +| D-038 | Wave 11 contracts adopted from `tasks/W11-PLAN-OUTPUT.md` as amended by `tasks/W11-PLAN-REV1-OUTPUT.md` after PREFLIGHT `tasks/W11-PREFLIGHT-OUTPUT.md` (CHANGES_REQUIRED: F1 P1, F2–F13 P2, P3 list). Accepted D-W11-01..04, 06..15; D-W11-05 modified per F9 (S-IO-03/opus owns the bounded shutdown core and poll-owner exclusion; S-IO-04/sonnet adds thin wrappers, `pump_until`, conformance). Root resolutions for F1 (file workers never call executors/user code except the injected syscall shim; `~Driver` is the only blocking teardown; destruction on a worker/inside a poll turn terminates with a diagnostic), F2 (epoll/eventfd close in backend destructor; `wake()` after shutdown is a no-op), F3–F6 (phase renumbering, per-call shutdown budgets, teardown in `~HostCore`, embedded borrowed resources never shut down), F7–F13 as in the addendum. Area plans `Functional.md`, `Runtime.md`, `IO.md` and `MIGRATION.md` updated per C-13. A1/B1 (Functional/Timer) may start before the PREFLIGHT re-review because the P1 is confined to IO/Runtime; re-review findings on F8/F12 are applied as corrections. | C-03–C-06, C-13; D-029 | diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 1232a2b..c5f792e 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,9 @@ # Workflow state -Updated: 2026-11-27. -Repository: VoidLibrary; active branch `feat/roadmap-p3-wave10` (from `main` -at `65ad9b3`, merged Waves 1–9 + `VL-001`..`VL-013` and pushed to `origin/main`). +Updated: 2026-11-29. +Repository: VoidLibrary; active branch `feat/roadmap-p2-wave11` (from `main` at `38436b1`; +Waves 1–10 + `VL-001`..`VL-013` merged into `main` at `7d7d23e` and pushed to `origin/main`). +Current wave: **Wave 11 — execution-path backfill** (see D-033..D-036 and `TASKS.md`). ## Completed objective @@ -364,9 +365,10 @@ while leaving local untracked files untouched. ## Ownership and next step -Waves 1–10 (`P0`, `P1`, all `P2` modules, `VL-001`..`VL-013`, and P3 core -subsystems `Discovery`, `Scheduler`, `Messaging`) are complete, verified, and -ready for `--no-ff` merge to `main`. Next wave: **Wave 11 — P3 Completion** -(`S-RPC-04..05` WebSocket multiplexed streaming + `NetworkedApplications` & -`ReloadableApplications` platform integrations), followed by **P4** -(`Coordination`, `Replication`, `DistributedStorage`, `DistributedApplications`). +Waves 1–10 (`P0`, `P1` except `M-FUNCTIONAL-03`/`M-TIME-03`, the P2 operations/storage/ +lifecycle/network modules, `VL-001`..`VL-013`, and P3 core subsystems `Discovery`, +`Scheduler`, `Messaging`) are complete, verified, merged and pushed. A 2026-11-29 audit +(D-033) found 2 P1 and 40 P2 roadmap tasks still open. **Wave 11** backfills the +execution path (`M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04/05`, `S-IO-03/04`, +`S-RUNTIME-02/03`) that gates `P-NETWORKED-02`/`P-RELOADABLE-02`. Then: foundation P2 +leftovers (D-036), then P3 platforms + `S-RPC-04/05`, then P4. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 4666440..c037b89 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -141,3 +141,43 @@ persisted task specifications. Root owns all cross-cutting files and resolves co changes. No worker owns application code, build files, existing docs/short-url.md, or Git operations. Configured roles use XHigh; runtime model identity is not independently verified by the available spawn response. + +## Wave 11 — Execution-path backfill (`feat/roadmap-p2-wave11`) + +Baseline: `main` at `38436b1`; full RelWithDebInfo `-Werror` (`/tmp/void-w11-base`, 55 modules): +`VoidTests` 1,484 discovered (1,480 ✔, 4 ⊘, 0 ✘) in 26.99 s; `ctest` 2/2 (111.68 s). +Decisions: D-033..D-036. + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| W11-PLAN | Architecture/task plan for the eight tasks below | [W11-PLAN](tasks/W11-PLAN.md) | IN PROGRESS | opus-planner dispatched | +| M-FUNCTIONAL-03 | Pure retry decisions + named blocking adapter | — | PLANNED | — | +| M-TIME-03 | Injected-deadline domains with Async/blocking retry adapters | — | PLANNED | — | +| M-ASYNC-04 | Bounded executors, cancellable channels, future pool adapter, ParallelFor | — | PLANNED | — | +| M-ASYNC-05 | EventBus/Observable snapshot dispatch, joined subscriptions | — | PLANNED | — | +| S-IO-03 | Bounded positional file workers, sync, active-cancel | — | PLANNED | — | +| S-IO-04 | Embedded pumping, joined shutdown, optional adapters | — | PLANNED | — | +| S-RUNTIME-02 | Explicit start, readiness, reverse failed-start cleanup | — | PLANNED | — | +| S-RUNTIME-03 | Structured shutdown, repeated join, exporter-before-executor ordering | — | PLANNED | — | + +P0 characterization tasks (`M-*-01`, `S-ALGORITHMS-01`, `S-MEMORY-01`): folded into follow-on +specs' observed baselines (D-035); not separately scheduled. + +## VoidForge upstream requests (scheduled after Wave 11; D-037) + +| ID | Priority | Request (VoidLibrary owns final signatures) | State | +| --- | --- | --- | --- | +| VL-STREAM-01 | P0 | Duplex HTTP response streaming: `HttpServer` duplex route + scoped response writer (begin/write_some/finish), per-exchange cancel/deadline, chunked/fixed/bodyless framing, pre-header error vs post-header abort | PLANNED | +| VL-PROC-01 | P0 | Binary subprocess session (argv-only, env allowlist, independent stdout/stderr drain, bounded buffering, NUL-safe, distinguishable EOF/exit/timeout/cancel/truncation) | PLANNED | +| VL-WIN-01 | P0 (later) | Windows HANDLE backend for VL-PROC-01 and HttpClient file transfer; client-only Net selection | PLANNED (deferred until requested) | +| VL-WASM-01 | P1 | Bounded `Text/Diff.hpp` (`DiffLimits`, checked sizes, work/memory caps, cancellation, explicit incomplete result, reflection-free build) | PLANNED | +| VL-MCP-01 | P1 | Generic MCP foundations (envelope, bounded JSON-RPC framing, Streamable HTTP + stdio bindings, auth callback); depends on VL-STREAM-01; RPC untouched | PLANNED | +| VL-TOML-01 | P1 | Qualify `Data/Toml` limits for dotted keys/table paths/inline tables; API change only with reproducer | PLANNED | +| VL-LUA-01 | P2 | Sandboxed Lua runtime (allocation/step budgets, no ambient IO) | PLANNED (backend decision needed) | +| VL-STORE-01 | P2 | Native Storage conformance support for Forge | PLANNED | +| VL-SQLITE-01 | P2 (non-blocking) | Structural SQLite primary/extended result codes (distinguish UNIQUE/CONSTRAINT vs BUSY/LOCKED) instead of message-only (`Sqlite/Types.hpp`, `Sqlite.cpp`) | PLANNED | +| VL-SQLITE-02 | P2 (non-blocking) | Documented `Unknown` commit outcome for failed COMMIT under WAL I/O error (like `Storage` `Outcome::Unknown`) | PLANNED | +| VL-SEC-01 | P2 (non-blocking) | Public CSPRNG bytes API (e.g. `Security::random_bytes(std::span)`) | PLANNED | +| VL-SQLITE-03 | P3 (non-blocking) | Per-connection, phase-targetable `ScopedFaultGuard` (incl. "COMMIT succeeded but reported failure") | PLANNED | +| VL-SQLITE-04 | P3 (non-blocking) | Per-call busy-timeout override | PLANNED | +| VL-NET-W01 | P2 (hygiene) | `src/Net/HttpServer.cpp:1797,1871` ignore `read()`/`write()` results (`-Wunused-result` under consumer flags, likely `_FORTIFY_SOURCE`); VoidLibrary's own `-Werror` build at `38436b1` passes | PLANNED | diff --git a/docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md b/docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md new file mode 100644 index 0000000..dac1e40 --- /dev/null +++ b/docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md @@ -0,0 +1,906 @@ +# 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 ``, 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 jitter{}; }; +struct RetrySpec { std::uint32_t max_attempts{3}; // total incl. first + std::variant 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 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 +class RetryState { +public: + [[nodiscard]] static std::expected + create(const RetrySpec&, SteadyTimePoint start, URBG urbg = URBG{}, + std::optional 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 deadline() const noexcept; +}; +template struct RetryError { RetryStopReason reason{}; std::uint32_t attempts{0}; + std::optional last_error{}; // empty iff no attempt ran + std::optional config{}; }; +struct RetryEveryError { template 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 +struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{}; URBG urbg{}; + std::stop_token stop{}; std::optional deadline{}; }; +template // F() -> std::expected +[[nodiscard]] auto retry_blocking(const RetrySpec&, F&& fn, BlockingRetryOptions = {}) + -> std::expected>; +``` + +- 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 |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; +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> + create(Executor& completion_executor, const Void::Time::MonotonicClock& clock, TimerQueueOptions = {}); + [[nodiscard]] Coro::Task> sleep_until(time_point when, OperationOptions = {}); + [[nodiscard]] Coro::Task> sleep_for(std::chrono::nanoseconds, OperationOptions = {}); + [[nodiscard]] std::expected 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 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 +[[nodiscard]] auto retry_async(Void::Retry::RetrySpec, F fn /* ()->expected | Task> */, + TimerQueue& timers, OperationOptions = {}, Classify = {}, URBG = URBG{}) + -> Coro::Task>>; +``` +- "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(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> create(ThreadExecutorOptions = {}); // no threads + [[nodiscard]] Void::Result::Result start(); // once; partial failure joins started workers + void post(std::coroutine_handle<>) override; // never rejects; counted; may exceed bound (legacy) + [[nodiscard]] std::expected 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 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 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 [[nodiscard]] std::expected>, 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 struct SendFailure { ChannelError error; T value; }; +template class AsyncChannel : public std::enable_shared_from_this> { public: + [[nodiscard]] static Void::Result::Result> create(Executor& resume, ChannelOptions = {}); + [[nodiscard]] std::expected> try_send(T); + [[nodiscard]] Coro::Task>> send(T, OperationOptions = {}); + [[nodiscard]] std::expected try_receive(); + [[nodiscard]] Coro::Task> 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 first_failed_chunk{}; std::exception_ptr first_exception{}; }; +template F> +[[nodiscard]] std::expected 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 error_sink{}; }; // outside locks +class EventBus { // EXISTING API unchanged, plus: + explicit EventBus(Void::Async::Executor& executor, BusOptions = {}); // no private thread; internal TaskScope + template [[nodiscard]] Void::Result::Result try_subscribe(std::function); + template [[nodiscard]] Void::Result::Result try_publish(const Event&); // overloaded / closed + [[nodiscard]] Void::Result::Result close_and_join(); + [[nodiscard]] Void::Result::Result close_and_join_pumping(Void::Async::ManualExecutor&); + [[nodiscard]] std::uint64_t callback_failures() const noexcept; + class Subscription { /* EXISTING */ public: [[nodiscard]] Void::Result::Result 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` 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::uint64_t) noexcept; + [[nodiscard]] virtual FileSyscallResult pwrite(int, std::span, 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> read_at(std::uint64_t, std::span, Async::OperationOptions = {}); + [[nodiscard]] Coro::Task> write_at(std::uint64_t, std::span, Async::OperationOptions = {}); + [[nodiscard]] Coro::Task> read_at_owned(std::uint64_t, BufferLease&, Async::OperationOptions = {}); + [[nodiscard]] Coro::Task> write_at_owned(std::uint64_t, const BufferLease&, Async::OperationOptions = {}); + [[nodiscard]] Coro::Task> sync(SyncMode = SyncMode::full, Async::OperationOptions = {}); + [[nodiscard]] Coro::Task> close_and_join(Async::OperationOptions = {}); }; +[[nodiscard]] Coro::Task> read_exact_at(File&, std::uint64_t, std::span, Async::OperationOptions = {}); +[[nodiscard]] Coro::Task> write_all_at(File&, std::uint64_t, std::span, Async::OperationOptions = {}); +} +``` + +**EDITs** +- `Driver.hpp` gains: + - `Result open_file(const std::filesystem::path&, FileOpenOptions = {})` + - `Result adopt_file_fd(int)` + - `Result start_file_workers()` (explicit, once; D-W11-11) + - `Result 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 Driver::shutdown(Async::OperationOptions); // bounded; repeatable +[[nodiscard]] Void::Result::Result 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 requires std::predicate +[[nodiscard]] Void::Result::Result 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 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 start(HostContext&) = 0; // outside Host locks + [[nodiscard]] virtual Coro::Task> stop(Async::OperationOptions) = 0; }; +struct StartOptions { SignalGate* signal_gate{nullptr}; + std::function(StartStep)> before_step{}; + std::function on_phase{}; // used by S-RUNTIME-03 + std::chrono::milliseconds readiness_timeout{5000}; }; +} +// Host (EDIT): all lifecycle state in std::unique_ptr; Host stays movable. +[[nodiscard]] Void::Result::Result 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 owner_thread() const noexcept; +[[nodiscard]] std::expected spawn(Coro::Task&&, Async::OperationOptions = {}); +~Host(); // non-default: reverse teardown on allowed thread +// HostBuilder (EDIT): +[[nodiscard]] Void::Result::Result add_component(std::string id, ResourceKind, std::shared_ptr, + std::vector 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 Host::poll_shutdown(); // non-blocking step +[[nodiscard]] Void::Result::Result Host::shutdown_blocking(Async::OperationOptions = {}); // repeatable +[[nodiscard]] Void::Result::Result Host::shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions = {}); +[[nodiscard]] std::optional 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>` 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` diff --git a/docs/agent-workflow/tasks/W11-PLAN-REV1-OUTPUT.md b/docs/agent-workflow/tasks/W11-PLAN-REV1-OUTPUT.md new file mode 100644 index 0000000..d14ba94 --- /dev/null +++ b/docs/agent-workflow/tasks/W11-PLAN-REV1-OUTPUT.md @@ -0,0 +1,349 @@ +# W11-PLAN-REV1 contract addendum (opus-planner, 2026-11-29) + +Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`. + +# W11-PLAN-REV1: contract addendum (deltas only) + +**Status: DONE.** I accepted every root resolution, with three clarifications recorded at the end: +- F5: the off-owner signal adapter should close its fd. That matches 1.x and avoids a descriptor leak. +- F1(a): the injected `FileSyscalls` shim is the one exception to "workers never run user code". +- Observable: queuing nested updates for copyable types is a 1.x ordering change that MIGRATION must record. + +Nothing was written to the repository. The reviewer's findings aren't persisted separately: `W11-PREFLIGHT.md` is the review brief. I worked from your F1–F13 and P3 summary. Gates G1–G5 stay; G6 is new; the B2 and A4 file sets change (table at the end). + +--- + +## F1 (P1) S-IO-03 teardown thread rule (owner B2) + +**Invariants** +- **(a)** A file worker performs one syscall (native or `FileSyscalls` shim) and nothing else. It then pushes `{request, result}` onto `FileWorkerShared::completions` under the shared mutex and calls the waker. + - Resume tickets are produced only by a poll turn, which drains `completions` through the existing `complete_op_and_collect_tickets` / `dispatch_tickets` path. + - `run_file_work()` executes one syscall on the caller's thread and only queues its result. +- **(b)** Workers hold only `std::shared_ptr` (queues, mutex/condvar, completion queue, and a waker given as function pointer plus context). They never hold `shared_ptr`. + - The waker's raw backend pointer stays valid because workers are joined before the backend can be destroyed: `Driver::~Driver` and `shutdown_and_join` both join first. +- **(c)** `~EpollBackend`, `~MockBackend` and `~FileWorkers` never block. `~FileWorkers` finding a joinable thread prints a diagnostic to stderr and calls `std::terminate`. + - Today `~EpollBackend` blocks (`EpollDriver.cpp:953-955` calls `shutdown_and_join`); that call is removed. + - `Driver::~Driver` (`:1737-1742`) becomes the blocking teardown: `backend_->teardown_blocking()`. +- **(d)** Two thread-local markers detect misuse: + - `tl_io_worker_owner` (a non-null pool pointer on worker threads) + - `tl_polling_backend` (set while a thread runs that backend's `poll_once` turn) + `~Driver` with either marker matching prints a one-line stderr diagnostic and calls `std::terminate`. +- NEW, declared in `Driver.hpp` and defined in `FileWorkers.cpp`: + ```cpp + [[nodiscard]] bool Void::IO::is_io_worker_thread() noexcept; // true on any Driver's file-worker thread + ``` + +**(e) Tests (`IoFile.cpp`)** +- `io_driver_destroyed_from_coroutine_resumed_after_poll_dispatch_same_thread`: with `ManualExecutor`, `poll_once` dispatches a ticket and `exec.drain()` on the same thread resumes a coroutine that resets the `unique_ptr`. Teardown must complete with no terminate. +- `io_worker_thread_marker_only_on_file_workers`: a gated shim records `is_io_worker_thread()` as true inside `pread`; it is false on the main thread, inside the poll turn and inside executor drain. The terminate path is documented only; no death test, because the Runner has no fork-based death support (`src/Testing/Subprocess.cpp:142` only execs helpers). + +## F2 epoll/eventfd lifetime (B2) + +- The epoll fd and eventfd still close in `~EpollBackend`, as in 1.x (`:956-963`). +- Shutdown closes only operation and descriptor fds, and only after it holds poll ownership. +- `wake()` loads `std::atomic wake_closed_` (acquire) and returns if set. It is set (release) when shutdown completes. +- Lock vs atomic: atomic is enough, and TSan-clean. `wake_fd_` is written only in the constructor (`:1255-1265`) and in `~EpollBackend`. + - All `wake()` callers hold a shared owner: `Driver::backend_`, the `CancelForwarder` weak→lock at `:589-596`, and `StreamState::lock_backend` at `Backend.hpp:89-96`. + - Workers are joined first. + - So the destructor's write happens after every `wake()` call, through the `shared_ptr` control block's acq_rel ordering. +- `poll_once` checks `shut_down_` (acquire) on entry and returns `0` before touching any fd. That keeps the 1.x return value (`:1057-1059` returns `work_done`). + +## F3 / F4 Runtime shutdown phases and budgets (B4) + +```cpp +enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business, + stopping_components, flushing_exporters, releasing_components, stopping_io, stopping_workers, releasing, stopped }; +``` + +**Phase order** + +| # | Phase | What happens | +| --- | --- | --- | +| 1 | `closing_admission` | business scope closes admission | +| 2 | `draining` | wait for the business scope to drain (deadline fixed at first entry) | +| 3 | `cancelling` | request stop on the business scope | +| 4 | `joining_business` | wait for the business scope to finish | +| 5 | `stopping_components` | non-exporter components stop | +| 6 | `flushing_exporters` | exporters stop (flush deadline fixed at first entry) | +| 7 | `releasing_components` | drop every component `shared_ptr`, so exporters are destroyed here | +| 8 | `stopping_io` | owned driver shuts down | +| 9 | `stopping_workers` | wait for the owned executor to go idle within budget, then join the reactor and executor | +| 10 | `releasing` | budgets and fds; signal gate on the owner thread | +| 11 | `stopped` | | + +- The ordering assertion `exporter_stopped < exporter_destroyed < executor_joined` stays. +- **Per-call budget:** every `shutdown_blocking`, `poll_shutdown` and `shutdown_pumping` call uses `call_deadline = min(options.deadline, deadline_after(clock, total_timeout))` for the work that remains. +- **Phase deadlines:** the drain and flush deadlines are fixed when their phase is first entered and stay expired afterwards. + - Drain expiry moves on to phase 3 and sets `drain_grace_expired`. + - Flush expiry requests stop on the exporter operations, sets `export_flush_expired`, and keeps waiting. +- **Incomplete:** if `call_deadline` expires in a waiting phase (4, 5, 6, 8 or 9), the sequence stops and returns `complete=false`, with the phase and state recorded as `shutdown_incomplete`. The next call resumes at that phase. +- NEW `[[nodiscard]] bool Async::ThreadExecutor::idle() const noexcept;` (both queues empty and nothing running), used by phase 9 so the executor join is never unbounded. + +## F5 Host ownership (B3, with the B4 parts) + +- All lifecycle state and teardown live in `detail::HostCore`, owned by `std::unique_ptr`. `~HostCore`: + - if the host is started and not stopped, calls `shutdown_blocking({})` (unbounded); + - then `gate->uninstall(this_thread == owner)`. + Default move-assign is therefore safe. +- **Moved-from Host** (`HostState` has no moved-from value, `Host.hpp:19-29`): + - NEW `[[nodiscard]] bool valid() const noexcept;` + - `state()` returns `stopped`; `is_running()` and `is_ready()` return false; `started_worker_count()` returns 0. + - `executor()` and `io()` return `nullptr`; `owner_thread()` and `last_shutdown_report()` return `nullopt`. + - `start`, `shutdown_*` and `poll_shutdown` return `RuntimeErrorCode::invalid_state`; `spawn` returns `AdmissionError::stopped`. + - `clock()` stays safe through its System-clock fallback (`:147-151`). + - `memory_budget()` has the precondition `valid()`. This is a pre-existing hazard: the 1.x code dereferences a null `owned_budget_` after a move (`:153-156`). +- `~HostCore` running on a Runtime worker, the reactor or an IO worker prints a stderr diagnostic and calls `std::terminate`. Detection uses: + - `executor->is_executor_thread()` (`Executor.hpp:86-96`) + - a Runtime `tl_reactor` marker + - `IO::is_io_worker_thread()` +- **SignalGate shape:** + ```cpp + class SignalGate { public: virtual ~SignalGate() = default; + [[nodiscard]] virtual Void::Result::Result install() = 0; + virtual void uninstall(bool on_owner_thread) noexcept = 0; }; // replaces uninstall() + ``` + - `shutdown_*` called off the owner thread leaves the gate installed (`owner_release_pending=true`). A later owner-thread call, or `~HostCore`, calls `uninstall(this_thread == owner)`. + - The System test adapter destroys its `SignalWatcher` in both cases. 1.x closes the fd on any thread (`SignalWatcher.cpp:29-31`) but restores the mask only on the owner (`:32-36`). Off-owner teardown therefore cannot restore the owner's mask; document this. +- Test: `runtime_offowner_destroy_closes_gate_fd_mask_not_restored`, which checks the `/proc/self/fd` delta is 0 and that the owner's mask is still blocked. + +## F6 Teardown follows ResourceOwnership (B4) + +- An embedded or borrowed executor, driver, clock or memory resource is never shut down, closed or joined by the Host. Phases 8 and 9 are skipped for borrowed resources. +- Signature: + ```cpp + [[nodiscard]] Void::Result::Result Host::shutdown_pumping( + Async::ManualExecutor&, Async::OperationOptions = {}, Async::TimerQueue* timers = nullptr); + ``` + It drives progress with `IO::pump_until(*io, manual, done, PumpOptions{.operation = call_budget, .timers = timers})`, so gate G5 stays. +- Test: `runtime_embedded_shutdown_never_shuts_borrowed_driver_or_executor`. After shutdown the borrowed driver still accepts `create_mock_stream` and the executor still accepts `try_post`. + +## F7 AsyncChannel arbitration (A2) + +- One `std::mutex` covers the buffer and both waiter lists. +- Waiter nodes live in the awaiter, inside the coroutine frame. Each holds `enum class WaiterState { linked, claimed, cancelled, timed_out, closed }`. A send waiter holds `std::optional value`; a receive waiter holds `std::optional slot`. +- Pairing a sender with a receiver happens under the lock, in one critical section: unlink and claim the waiter, then move the value. A value is therefore always in exactly one place: the sender node, the buffer or the receiver slot. It is never in limbo. +- Stop callbacks and timer callbacks take the same lock. + - If the waiter is still `linked`, it is unlinked and set to `cancelled` or `timed_out`. A sender keeps its value and gets it back. + - If it is already `claimed`, the callback does nothing. A sender gets success; a receiver gets the value that is already in its slot. +- Every resume is dispatched through `post_completion` after unlock. Each sender gets success or its value back exactly once. +- Tests: + - `channel_receiver_stop_after_claim_delivers_value_no_loss` + - `channel_sender_stop_vs_receive_race_exactly_once_tsan`: 10,000 iterations; the multiset of values sent equals values received plus values returned. + - `channel_timer_close_settles_waiter_cancelled` (see F12) + +## F8 Default URBG (A1, B1) + +House convention: `Retry.hpp:89` seeds with `std::random_device`. + +```cpp +namespace Void::Retry::detail { template G seeded_engine() + { if constexpr (std::is_constructible_v) return G{std::random_device{}()}; else return G{}; } } +// RetryState::create(spec, start, URBG urbg = detail::seeded_engine(), std::optional = {}) +// BlockingRetryOptions::urbg default member init = detail::seeded_engine(); retry_async param default likewise +``` + +- Tests pass seeded `std::mt19937_64{42}` everywhere except `retry_state_default_engine_jitter_in_bounds`, which checks bounds only. + +## F9 Revised D-W11-05: B2 owns the shutdown core, A4 owns thin wrappers + +**B2 internal primitive in `detail::DriverBackend` (`Backend.hpp`):** +```cpp +virtual void begin_shutdown() noexcept = 0; // idempotent: close admission, cancel queued, stop active +[[nodiscard]] virtual Void::Result::Result advance_shutdown( + std::optional deadline, std::stop_token stop) = 0; +[[nodiscard]] virtual bool shutdown_complete() const noexcept = 0; +[[nodiscard]] virtual bool quiescent() const noexcept = 0; // no owned ops/requests/in-flight syscalls +virtual void teardown_blocking() noexcept = 0; // Driver::~Driver only +``` +- B2 also owns `DriverShutdownReport` in `Types.hpp`, using the plan's fields. +- 1.x `shutdown_and_join()` becomes `advance_shutdown(nullopt, {})` mapped to `Result`. +- `advance_shutdown` details: + - Waits for the injected-clock deadline in ≤1 ms real slices, re-reading the clock each time. + - Calls `wake()` to interrupt the current poller. + - Runs its own poll turns only while it holds poll ownership. + - Returns `self_join` if called on this backend's worker or inside its poll turn. +- **Poll-owner exclusion** uses a dedicated `std::mutex poll_mu_`. `poll_once` tries the lock and returns `std::unexpected(make_io_error(IoErrorCode::busy, ...))` if it can't get it, without touching any fd. + - I chose `busy` over `0` for three reasons: `busy` already means "concurrent op not allowed" (`EpollDriver.cpp:533-540`); the only library caller in a loop ignores the result (`IPC/Session.cpp:1128`); and a silent `0` would let a second `run()` loop spin. + - Test: `io_concurrent_poll_once_second_caller_busy_no_fd_touch_tsan`. + +**A4 public wrappers** (inline in `Driver.hpp`; A4 touches no `.cpp`): +```cpp +void begin_shutdown() noexcept; // -> backend_->begin_shutdown() +[[nodiscard]] Void::Result::Result shutdown(Async::OperationOptions); // -> advance_shutdown(o.deadline, o.stop) +[[nodiscard]] Void::Result::Result run(std::stop_token, std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5}); +[[nodiscard]] bool quiescent() const noexcept; +``` +A4 also delivers `Pump.hpp`/`pump_until`, the SystemAsync conformance test, and tests. + +## F10 Roadmap and doc edits (root, before dispatch) + +**`docs/roadmap/modules/Functional.md`** +- **:95-96**: "NEW `RetryState` exposes `begin(now)`, `next(now, outcome)` and `resume(now)`: `next` returns `stop` or `wait_until(absolute time)`; `begin`/`resume` return `attempt` or `stop`. Callers map their error to `AttemptOutcome` with a supplied classifier." +- **:99**: append "; the default engine is seeded from `std::random_device`." +- **:104-106**: "Retain 1.x `retry`/`retry_while` unchanged, including the zero-attempt default-result defect (recorded for Wave C). NEW `retry_blocking` takes injected `now`/`sleep` callables, so Functional stays standard-library-only and no Time-dependent retry header exists. Async supplies `Async::retry_async` over `TimerQueue`." + +**`docs/roadmap/subsystems/Runtime.md`** +- **:48-51**: "`Result start(StartOptions); Async::Executor* executor(); IO::Driver* io(); Result shutdown_blocking(Async::OperationOptions); Result poll_shutdown(); Result shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions);` An awaited shutdown Task on the host's own executor is not offered, because it would self-join." +- **:73**: "install the injected `SignalGate` (Runtime has no System dependency; System-backed adapter optional) on the owner thread" +- **:77**: append "; off-owner teardown calls `uninstall(false)`, which cannot restore the owner's mask." +- **:114-117**: "6. After cleanup/export callbacks and backend references retire, drop component/exporter references, then stop owned IO, the reactor and CPU/file workers, and release budgets, descriptors and the signal gate in reverse creation order. Borrowed executor, driver, clock and memory are never shut down or joined by the Host." +- **:119**: "Each shutdown call observes min(caller deadline, now + total_timeout (30 s)) for remaining work. Drain-grace and flush deadlines are fixed at first entry to their phase. An incomplete phase stops the sequence and the next call resumes there." +- **:124-126**: "Destruction blocks to join only off Runtime threads. Destruction on a Runtime worker, reactor or IO file-worker thread is a programmer error that terminates after a diagnostic." +- **:159**: deps become "P2 / S-RUNTIME-01, M-ASYNC-04, S-IO-03; signal gate (injected port)". +- **:160**: deps become "P2 / S-RUNTIME-02, S-IO-04". + +**`docs/roadmap/subsystems/IO.md`** +- **:77-79**: "The Driver owns no thread. One thread at a time runs a `poll_once` turn (the poll owner) and owns interest updates and generations; a concurrent caller gets `busy` without touching descriptors. Producers wake the owner through eventfd. Runtime or the embedder supplies the thread (`Driver::run`, `pump_until`)." +- **:92**: "Files use a bounded blocking worker pool started explicitly by `start_file_workers()` or stepped by `run_file_work()`. Workers run only the syscall or injected shim and queue its result; completions are delivered only by a poll turn." +- **:118-120**: "Driver shutdown closes admission, cancels queued requests, stops active ones, waits for the poll owner and in-flight syscalls, drains completions, joins workers, then closes operation descriptors. Epoll and wake descriptors close in the backend destructor. Blocking teardown runs in `Driver::~Driver`; destruction on a file worker or inside a poll turn is a programmer error." +- **:121-122**: "`File::close_and_join` returns `incomplete_shutdown` on expiry and retains the fd and buffers. A dropped File closes its fd after its last in-flight request drains." +- **:154**: "optional System/Net adapters" becomes "SystemAsync conformance; Net adapter deferred (Net has no IO use)". + +**`docs/roadmap/MIGRATION.md:61` (Async/IO row, append to the evidence cell)** +"Recorded W11 changes: +- `Driver::shutdown_and_join` blocks for in-flight syscalls and joins file workers. +- `validate_limits` rejects `max_file_queue == 0`. +- Sync EventBus and Observable/Signal dispatch over snapshots; subscription changes take effect next pass. +- Nested Observable/Signal updates for copyable types are queued FIFO. +- Legacy `parallel_for` waits for all tasks before rethrowing. +- Async-mode EventBus handler exceptions are counted instead of terminating. +- Legacy `retry` zero-attempt result is kept until Wave C." + +**DECISIONS:** amend D-W11-05 per F9, and add F1, F2 and F5 as root decisions. + +## F11 Within-step failure coverage + +- **IO (B2):** `BackendOptions::before_file_worker_start` (NEW, appended): + ```cpp + std::function(std::size_t)> before_file_worker_start{}; + ``` + - `start_file_workers` treats a hook error exactly like a caught `std::system_error`: it joins the workers already started, returns `os_error` (with the system code when one exists), and allows a retry. + - Test: `io_file_workers_partial_start_failure_joins_started`. +- **ThreadExecutor (A2):** `start()` catches `std::system_error` from `std::thread` through the same path as `before_worker_start`. +- **Runtime (B3):** + ```cpp + struct StartOptions { /*...*/ + std::function(StartStep, std::size_t thread_index)> before_thread_start{}; + std::chrono::milliseconds cleanup_timeout{5000}; }; + ``` + - `before_thread_start` is forwarded to the executor and IO hooks and to the reactor's `std::thread` creation, which also catches `std::system_error`. + - Failed-start component cleanup waits at most `cleanup_timeout` (injected clock). If it runs out, the state is `failed_start`, resources are retained, and the next `shutdown_blocking` or `~HostCore` continues the cleanup. +- Tests: + - `runtime_failed_start_thread_fault_each_threaded_step_reverse_cleanup` (cpu_executor, file_workers and reactor, at index 0 and at the last index) + - `runtime_failed_start_component_cleanup_timeout_retains_then_completes` + - `thread_executor_system_error_path_shared_with_hook` + +## F12 Shared-core lifetimes + +- **EventBus (A3):** + - Injected-mode dispatch frames capture `std::shared_ptr`. + - `~EventBus` closes admission. On an executor thread it does not wait: frames finish against the shared core. Off the executor it calls `close_and_join` (blocking, or pumping on `ManualExecutor`). + - NEW `[[nodiscard]] Void::Result::Result flush_blocking();` returns `self_join` on an executor thread or inside a bus callback, and `invalid_argument` on a `ManualExecutor` (`Executor.hpp:195`). + - NEW `flush_pumping(ManualExecutor&)`. + - Legacy `flush()` in Injected mode calls `flush_blocking()` and discards the error, because the 1.x signature returns `void` (`EventBus.hpp:193-201`). It never deadlocks. +- **TimerQueue (B1):** + ```cpp + enum class TimerEvent : std::uint8_t { expired, closed }; + using TimerCallback = std::move_only_function; + ``` + - `TimerHandle` holds `shared_ptr`, whose state is an atomic pending→{fired, cancelled} transition. `cancel()` is valid after the queue is destroyed. + - The callback runs exactly once (`expired` or `closed`), or never if `cancel()` returned true. Queue close or destruction invokes pending callbacks with `closed`; AsyncChannel maps that to `cancelled`. + - Test: `timer_handle_cancel_after_queue_destroyed_safe`. +- **`parallel_for` (A2):** + - Shared `detail::PForState` holds the decay-copied `F`, the chunk counter and the error slots. + - The caller waits for every submitted runner future, including runners that were never started. + - Nested use on the same pool from a pool worker is documented as unsupported. + - Test: `parallel_for_bounded_waits_all_submitted_runners`. + +## F13 File descriptor lifetime (B2) + +- `detail::FileState` is shared-owned and holds the fd, the shim, the in-flight count, a `close_pending` flag and the per-file ordering lane. Every request holds a reference to it. +- When the last handle drops: + - with no requests in flight, an internal close request is enqueued, using reserved capacity outside `max_file_queue`; + - otherwise `close_pending` is set, and the poll-turn retirement of the last request enqueues the close. +- Close always executes on a worker, or in `run_file_work`. Teardown closes any remaining file fds after the workers are joined. +- `File::close_and_join(options)` is always admitted. + - Deadline or stop expiry returns `IoErrorCode::incomplete_shutdown`; the File stays valid with its fd and buffers retained, so the call can be repeated. + - Success invalidates the File. + - A close syscall failure returns `os_error`, and the fd is treated as closed. + - This differs from `ByteStream::close_and_join`, which consumes the stream (`Stream.hpp:105`); document the difference. +- Tests: + - `io_file_drop_with_inflight_defers_close_until_drained` + - `io_file_close_and_join_expiry_incomplete_retains_then_completes` + +## P3 resolutions + +- **`retry_blocking` template defaults (A1):** use defaulted function-template parameters, because deduction cannot read a default function argument: + ```cpp + template + auto retry_blocking(const RetrySpec&, F&&, BlockingRetryOptions = {}); + ``` + Tests spell the option types explicitly; aggregate CTAD is a convenience only. +- **Observable/Signal (A3):** + - `Observable` with `std::copy_constructible`: a nested `set` updates the value immediately and queues `(old, new)` copies, delivered FIFO after the current pass and bounded at 1,024. On overflow, `set` keeps the new value and counts a dropped notification. `try_set` (only when copyable) returns `overloaded` without changing the value. + - Move-only `T`: the 1.x behavior stays — immediate recursive notification — but iteration runs over a listener snapshot. There is no queue and no `try_set`. + - `Signal` follows the same rule when `(std::copy_constructible> && ...)`; the queue is a `mutable` member, since `emit` is `const`. + - On a throw, the value stays the new value (as in 1.x, `Observable.hpp:40-42`), dispatch depth is restored, and that pass's queued notifications are dropped and counted. +- **S-IO-03 downstream build:** + ```sh + -DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;CryptoAsync;Runtime;ConfigurationAsync;Testing" + ``` + run unfiltered, plus `ctest`. +- **Error-kind alignment:** `RuntimeErrorCode::shutdown_incomplete = 9` maps to `ErrorKind::conflict`, matching `IoErrorCode::incomplete_shutdown` (`IO/Types.hpp:51-53`). IO is unchanged. Root pre-commit. +- **D1 regression seam (B2):** + - Test `io_epoll_stop_requested_at_deadline_scan_completes_once` uses a clock whose `now()` requests stop. That `now()` call happens in the wait computation, only when the op has a deadline (`EpollDriver.cpp:1083,1098`). + - The sequence: + 1. The socket already has data. + 2. The stop puts the cancel in the queue. + 3. `drive_read` sees the stop and completes the op (`:1452`). + 4. The end-of-turn cancel pass hits the same op (`:1173`). + - NEW appended telemetry field `DriverTelemetry::duplicate_completions_ignored`. The test asserts a single delivery and a counter ≥ 1. +- **Mock reactor spin (B3):** `MockBackend::poll_once` ignores `max_wait` (`EpollDriver.cpp:739-741`) and its `wake` only counts (`:637-640`). + - The Runtime reactor (and A4's `Driver::run`) waits on a stop-aware condition variable for `max_wait` when the backend is mock and a turn did no work. + - IO is unchanged, so the `IoDriver` test timing is untouched. +- **Business scope:** `TaskScopeOptions{.max_tasks = limits.max_cpu_tasks, .stop_on_first_error = false}`, because the default is `true` (`TaskScope.hpp:32`). +- **ThreadExecutor (A2):** + - After `close()`, a legacy `post()` goes onto the completion lane and is counted. + - `join()` drains until both lanes are empty and nothing is running. After join, posts resume inline and are counted. + - No drain cap: abandoning a handle would strand a frame, which C-03 forbids (`ARCHITECTURE.md:63-64`, "owner until exactly one terminal result"). A handle that re-posts itself forever prevents join; that is documented as a caller error. + - `~ThreadExecutor` without a prior join calls `close()` then `join()`. On its own worker it prints a diagnostic and terminates. +- **Runtime worker detection** uses `IO::is_io_worker_thread()` (F1). +- **Layering check (A4):** + ```sh + rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO # expect no output + git diff --stat -- src/IO/module.cmake # expect empty + ``` +- **Budget accounting (B4):** test `runtime_shutdown_budget_bytes_retained_while_incomplete_zero_after_complete`. + - The Host passes `memory_budget()` as the Driver's pmr resource (`Driver.hpp:69-74`). + - An exporter holds a `BufferLease` across a stalled read. + - While incomplete: `memory_budget().stats().requested_live > 0` (`BudgetResource.hpp:106`, `Memory/Resource.hpp:22-30`), and `executor()->admitted()` and `DriverTelemetry::owned_buffer_bytes` stay as they were. + - After release and a second join: all three are 0. +- **M-ASYNC-05 captured-state tests (A3):** + - `bus_sync_unsubscribe_releases_captured_state` + - `bus_legacy_async_unsubscribe_then_flush_releases_captured_state` + - `bus_legacy_async_close_and_join_releases_capture_with_queued_copies` + All three assert the sentinel's `use_count() == 1`. + +## Revised gates and ownership (changes only) + +**Gates** +- G1–G5 as before. +- G4 now hands A4 only `Driver.hpp` (inline wrappers), the NEW `Pump.hpp` and tests. +- **G6 (new):** after A4 merges, all IO files are root-owned. B4 must stop and report if it needs an IO edit. + +| Step | Owned-file delta | +| --- | --- | +| Root pre-commit | `RuntimeErrorCode::shutdown_incomplete` maps to `conflict` (changed from `timeout`) | +| B1 | adds `TimerEvent` and the shared-state `TimerHandle` to `Async/Timer.hpp` | +| B2 | adds to `IO/Driver.hpp`: `is_io_worker_thread`, `~Driver` teardown. Adds to `IO/Types.hpp`: `DriverShutdownReport`, `BackendOptions::before_file_worker_start`, `DriverTelemetry::duplicate_completions_ignored`. Adds to `IO/Detail/Backend.hpp`: the shutdown primitives. Also `src/IO/{EpollDriver.cpp, FileWorkers.{hpp,cpp}}` and `tests/standalone/IO/IoFile.cpp` | +| A4 | `include/Void/IO/Driver.hpp` (inline wrappers only), `include/Void/IO/Pump.hpp` (NEW), `tests/standalone/IO/{IoShutdown,IoPump}.cpp`, `tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`. Not owned: `EpollDriver.cpp`, `Backend.hpp`, `Types.hpp`, `FileWorkers.*` (stop and report) | +| B3 / B4 | `Runtime/Lifecycle.hpp` gains `SignalGate::uninstall(bool)`, `StartOptions::{before_thread_start, cleanup_timeout}` and the renumbered `ShutdownPhase`. `Host.hpp` gains `valid()` and the 3-argument `shutdown_pumping`. A2 additionally owns `ThreadExecutor::idle()` | + +## Root resolutions I'd adjust (not silently changed) + +1. **F5 adapter wording.** "Releases its fd ... only on the owner thread" doesn't match 1.x: `SignalWatcher` closes the fd on any thread (`SignalWatcher.cpp:29-31`). Keeping the fd open off-owner would leak it, because no later owner-thread call is guaranteed. I recommend closing the fd and skipping only the mask restore, exactly as 1.x does; the F5 section above specifies that. +2. **F1(a) "workers never call user code".** The injected `FileSyscalls` shim runs on workers by design. It should be stated as the only exception: a syscall substitute that must not call Driver, Executor or File APIs. +3. **Observable copyable queuing.** It changes 1.x nested-set ordering from recursive to FIFO for copyable types. That's acceptable, since the roadmap mandates the queue, but it must appear in the MIGRATION record; F10 includes it. + +**Checks not run:** no builds or tests. All citations come from direct reads during this session. diff --git a/docs/agent-workflow/tasks/W11-PLAN.md b/docs/agent-workflow/tasks/W11-PLAN.md new file mode 100644 index 0000000..8396272 --- /dev/null +++ b/docs/agent-workflow/tasks/W11-PLAN.md @@ -0,0 +1,125 @@ +# Wave 11 execution-path backfill — architecture and task plan + +Task ID: W11-PLAN +Role: opus-planner +Status: READY + +## 1. Context and baseline +- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11` + created from `main` at `38436b1` (Waves 1–10 merged at `7d7d23e`, pushed to `origin/main`). +- Tracked tree clean. Untracked user files (`.env`, `WG.conf`, `keys`, `jev_token`, `.serena/`, + `.vbs/`, dotfiles, `compile_commands.json`) are NOT task inputs; never read, copy or quote them. +- Root gap analysis (2026-11-29): roadmap task tables list 300 tasks; `docs/agent-workflow/TASKS.md` + marks Waves 1–10 done, but these execution-path tasks remain open and their pre-roadmap + headers are untouched since baseline `f1f9ba3` (`git log f1f9ba3..HEAD` on + `Async/{Channel,EventBus,Observable,ParallelFor,ThreadPool}.hpp`, `Functional/Retry.hpp` + shows no commits; `IO`/`Runtime` only received `S-IO-01/02` `673bb7e` and `S-RUNTIME-01` `1b3331e`): + - P1 leftovers: `M-FUNCTIONAL-03`, `M-TIME-03`. + - P2: `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`, `S-RUNTIME-02`, `S-RUNTIME-03`. +- These gate `P-NETWORKED-02` / `P-RELOADABLE-02` ("Runtime/Async/IO lifecycle gates"). +- Requirement/contract references: `docs/roadmap/REQUIREMENTS.md` R-001..R-016, + `docs/roadmap/ARCHITECTURE.md` C-01..C-14, gates G-ERROR/G-EXEC/G-IO in `DEPENDENCIES.md`. +- Baseline full build/test of `main` is running separately under root; not your concern. + +## 2. Objective and deliverables +Produce an implementation-ready plan (returned as text, not written to files) for the eight +tasks above, plus a readiness verdict for `S-RPC-04` (WebSocket streaming) as an optional +ride-along. Deliverables in the reply: +1. Per task: observed baseline (exact existing symbols/behavior with `path:line`), the gap + against its roadmap row and area plan, and the minimal complete scope to satisfy the + row's acceptance text. +2. Per task: NEW public interfaces (C++ signatures, enums, error codes in existing domains, + limits/defaults) marked NEW, and which existing 1.x APIs stay unchanged (D-029). +3. Dependency graph between the eight tasks, and the module `INTERNAL_DEPS` changes, if any, + with a check that every edge respects `DEPENDENCIES.md` target package rules. +4. A partition into 2–3 worker packages with exclusive file ownership (exact paths), role + (`astra_*` rows → opus-implementer, `sol_*` rows → sonnet-implementer), and order. + Identify root-owned shared edits (e.g. `include/Void/Functional/Error.hpp`, + `tests/package/InstalledComponents.cmake`, top-level `CMakeLists.txt`, `cmake/*`). +5. Per task: concrete test list (test file paths, scenario names) mapping to acceptance text, + and exact verification commands (module subset, filters) in the repository's form. +6. Whether the "System signal gate" named by `S-RUNTIME-02` exists in current source + (cite symbols), or what minimal in-wave work it implies without adding Runtime→System + unless `DEPENDENCIES.md` permits it. +7. Risks, open questions that need a root decision, and anything in the roadmap rows that + is infeasible or contradictory, with a recommended resolution. + +## 3. Scope and non-goals +In scope: planning only for the eight tasks and the S-RPC-04 readiness note. +Non-goals: editing files, writing specs, implementing code, running long builds, planning +foundation P2 leftovers (Core/Math/Text/Data/Binary/…) or P3/P4 platforms. + +## 4. Files to inspect +- Roadmap: `docs/roadmap/modules/{Functional,Time,Async}.md`, `docs/roadmap/subsystems/{IO,Runtime,RPC}.md`, + `docs/roadmap/{ARCHITECTURE,DEPENDENCIES,MIGRATION,VALIDATION,PERFORMANCE}.md`, + `docs/roadmap/platforms/{NetworkedApplications,ReloadableApplications}.md` (gate wording only). +- Prior specs for style/precedent: `docs/agent-workflow/tasks/{M-ASYNC-02-03,S-IO-01-02,S-RUNTIME-01,M-TIME-02,M-FUNCTIONAL-02,M-SYSTEM-01-05}.md`. +- Source: `include/Void/Functional/{Retry,Error,Result}.hpp`, `src/Functional/module.cmake`; + `include/Void/Time/{Clock,Stopwatch}.hpp`; `include/Void/Async/*.hpp`, `src/Async/module.cmake`; + `include/Void/IO/{Types,Driver,Stream}.hpp`, `include/Void/IO/Detail/*`, `src/IO/{EpollDriver.cpp,module.cmake}`; + `include/Void/Runtime/{Options,ResourceGraph,Host}.hpp`, `src/Runtime/module.cmake`; + `include/Void/System/*` (signal handling), `include/Void/Net/*` (only for S-IO-04/S-RPC-04 adapters); + existing tests under `tests/standalone/{Functional,Time,Async,IO,Runtime}/`; + `cmake/Module.cmake`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake`. + +## 5. Write ownership and coordination +Write scope: none +Allowed commands: read-only `git`, `rg`, `ls`, `wc`, Serena/codebase-memory read tools. You may +compile a tiny probe only under `/tmp/void-w11-plan-probe` if essential; do not touch the +repository tree. `dev cpp-gcc ...` must run unsandboxed (nix fetcher lock); avoid it unless needed. + +## 6. Implementation or investigation approach +1. Read each roadmap row and area-plan section; extract mandatory behavior and limits. +2. Inspect the current headers/tests via Serena symbol tools; record what exists. +3. Derive minimal complete NEW interfaces that layer beside 1.x APIs (Wave A+B, D-029). +4. Check layering: Functional has zero `INTERNAL_DEPS` (D-015) — retry decisions must take + injected time values or a template clock, not depend on `Time`; Async must not depend on + Log backends or Runtime; IO must not depend on Runtime/Net/System; Runtime composes. +5. Build the task DAG and the ownership partition minimizing cross-package header edits. +6. Draft test scenarios that prove each acceptance sentence deterministically (manual clocks, + mock IO backend) and TSan-relevant concurrency cases. + +## 7. Interfaces and data contracts +Use existing contracts: `Void::Functional::{Result,Error,Status,ErrorCode}`, domains +`kTimeErrorDomain=4`, `kAsyncErrorDomain=7`, `kIoErrorDomain=8`, `kRuntimeErrorDomain=11`; +`Void::Time::{MonotonicClock,ManualClock}`; Async `OperationOptions`/`TaskScope`/`Executor`; +IO `Driver`/`BufferLease`; Runtime `Host`/`HostBuilder`/`ResourceGraph`. Any new error code +must extend an existing domain enum; propose exact enumerator names. + +## 8. Dependencies and integration +Upstream: Waves 1–10 on `main`. Root owns integration, shared build files, and all commits. +Implementers will be dispatched only after a fresh opus-reviewer PREFLIGHT of your plan. + +## 9. Edge cases security and performance +Call out: exactly-one-terminal-result races, stop/expiry/completion permutations, buffer +retention on active cancel, bounded queues including running work, reentrancy and +unsubscribe-during-dispatch, failed-start reverse cleanup with no leaked threads/fds, +signal-mask ownership, exporter-before-executor shutdown ordering, no user callbacks +under locks, overflow-safe deadline arithmetic. + +## 10. Acceptance criteria +1. Each of the eight tasks has baseline, gap, NEW interface, tests and commands. +2. DAG and INTERNAL_DEPS changes respect DEPENDENCIES.md rules (stated per edge). +3. Ownership partition has no overlapping paths and lists root-owned shared files. +4. S-RUNTIME-02 signal-gate question answered with cited symbols. +5. S-RPC-04 readiness verdict with prerequisites cited. +6. Open decisions listed with a recommendation each. + +## 11. Verification commands and evidence +Not applicable for builds: planning-only. Cite `path:line` for every baseline claim. Command +templates you propose must follow the observed form, e.g. +`dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11- -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11- && /tmp/void-w11-/tests/VoidTests --filter "*" && ctest --test-dir /tmp/void-w11- --output-on-failure --timeout 60'`. + +## 12. Constraints and stop conditions +No repository edits, no commits, no network calls beyond local tools, no secrets. Stop and +report if a roadmap requirement contradicts a recorded decision (D-001..D-032) or would need +a new dependency edge forbidden by DEPENDENCIES.md. + +## 13. Authorization and decisions +Root decision under D-027/D-031 (continuous roadmap-order execution): Wave 11 is the +execution-path backfill. Planning-only authorization; you do not approve your own plan. + +## 14. Return format +Return task ID; DONE/BLOCKED/PARTIAL; summary; per-task sections (baseline, gap, NEW +interfaces, tests, commands); DAG; ownership partition; signal-gate answer; S-RPC-04 verdict; +risks; open decisions with recommendations; checks not run. Do not spawn children. diff --git a/docs/agent-workflow/tasks/W11-PREFLIGHT-2.md b/docs/agent-workflow/tasks/W11-PREFLIGHT-2.md new file mode 100644 index 0000000..bdf083a --- /dev/null +++ b/docs/agent-workflow/tasks/W11-PREFLIGHT-2.md @@ -0,0 +1,80 @@ +# Wave 11 PREFLIGHT re-review of the contract addendum + +Task ID: W11-PREFLIGHT-2 +Role: opus-reviewer +Status: READY + +## 1. Context and baseline +- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11` from `main` + `38436b1`. Uncommitted root prep: workflow docs, roadmap area-plan edits + (`docs/roadmap/{modules/Functional.md,subsystems/IO.md,subsystems/Runtime.md,MIGRATION.md}`), and new + enumerators `AsyncErrorCode::closed=9` (→cancelled), `IoErrorCode::sync_failed=12` (→io), + `RuntimeErrorCode::{self_join=8, shutdown_incomplete=9}` (→conflict). Untracked user files + (`.env`, `WG.conf`, `keys`, `jev_token`, `.serena/`, `.vbs/`, dotfiles) are not inputs. +- Baseline `38436b1`: `VoidTests` 1,484 discovered, 1,480 passed, 4 skipped, 0 failed. +- First PREFLIGHT verdict CHANGES_REQUIRED: `docs/agent-workflow/tasks/W11-PREFLIGHT-OUTPUT.md`. + Original plan: `W11-PLAN-OUTPUT.md`. Planner addendum answering it: `W11-PLAN-REV1-OUTPUT.md`. + Root disposition: `docs/agent-workflow/DECISIONS.md` D-038. + +## 2. Objective and deliverables +Fresh, independent verdict (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE) on whether the +addendum plus root doc edits resolve findings F1–F13 and the P3 list without introducing new +defects, so implementation specs can be written. Severity-ranked findings for anything still +open or newly introduced. + +## 3. Scope and non-goals +In scope (from the first review's re-review scope): revised S-IO-03, S-IO-04, S-RUNTIME-03 +contracts (F1–F6, F9, F13); AsyncChannel, Retry, EventBus, TimerQueue invariants (F7, F8, +F12); area-plan/MIGRATION edits (F10); the three planner adjustments (signal adapter closes +fd off-owner; syscall shim exception; Observable FIFO ordering change). Also check the +`poll_once` concurrent-caller choice (`busy`), the `wake_closed_` atomic argument, the +`FileState` close-request reserved capacity, and `ThreadExecutor::idle()` use in phase 9. +Non-goals: re-reviewing parts confirmed sound in the first review, style, other waves. + +## 4. Files to inspect +`docs/agent-workflow/tasks/{W11-PLAN-OUTPUT,W11-PREFLIGHT-OUTPUT,W11-PLAN-REV1-OUTPUT}.md`, +`docs/agent-workflow/DECISIONS.md` (D-038), `git diff` of the root prep, and source cited by +the addendum: `src/IO/EpollDriver.cpp`, `include/Void/IO/{Types,Driver,Stream}.hpp`, +`include/Void/IO/Detail/Backend.hpp`, `include/Void/Async/{Executor,Operation,TaskScope,EventBus,Observable}.hpp`, +`include/Void/Runtime/{Host,Options}.hpp`, `src/System/SignalWatcher.cpp`, `src/IPC/Session.cpp` +(poll_once result use), `include/Void/Memory/BudgetResource.hpp`. + +## 5. Write ownership and coordination +Write scope: none +Allowed commands: read-only `git`, `rg`, `ls`, `sed -n`, Serena/codebase-memory read tools; optional +probes only under `/tmp/void-w11-preflight2-probe`. A root subset build runs in +`/tmp/void-w11-prep`; do not touch it. + +## 6. Implementation or investigation approach +1. For each F1–F13 and P3 item: state RESOLVED / PARTIAL / UNRESOLVED with evidence. +2. Look for new hazards the resolutions introduce (e.g. raw waker pointer lifetime, `busy` from + `poll_once` breaking existing callers that loop on it, reserved close capacity unbounded, + phase-9 idle wait vs inline-resume after join, `~HostCore` unbounded shutdown on destruction). +3. Check the area-plan edits are consistent with the addendum and with D-001..D-038. + +## 7. Interfaces and data contracts +Not applicable for new authorship: review the addendum's signatures as written. + +## 8. Dependencies and integration +A1 (M-FUNCTIONAL-03) and B1 (M-TIME-03 Timer) may be dispatched in parallel with this review +(D-038); report any finding affecting F8/F12 explicitly so root can correct them. + +## 9. Edge cases security and performance +Same list as the first PREFLIGHT: fd reuse, signal masks, partial start, TaskScope destructor, +ManualClock + blocking waits, inline resume after join, retained buffers, tombstones. + +## 10. Acceptance criteria +1. Verdict with justification. 2. Each F1–F13/P3 item marked RESOLVED/PARTIAL/UNRESOLVED. +3. New findings have severity, location, trigger, impact, evidence, recommendation. + +## 11. Verification commands and evidence +Read-only inspection, e.g. `git diff -- docs/roadmap include/Void`, `rg -n "poll_once\(" src include`. + +## 12. Constraints and stop conditions +No edits, commits or network; no spawning. Mark INSUFFICIENT_EVIDENCE rather than guess. + +## 13. Authorization and decisions +Root decisions D-034, D-038 under user decisions D-027/D-031. Technical check only. + +## 14. Return format +Task ID; verdict; per-item status table; new findings P0→P3; checks not run. Compact. diff --git a/docs/agent-workflow/tasks/W11-PREFLIGHT-OUTPUT.md b/docs/agent-workflow/tasks/W11-PREFLIGHT-OUTPUT.md new file mode 100644 index 0000000..727926a --- /dev/null +++ b/docs/agent-workflow/tasks/W11-PREFLIGHT-OUTPUT.md @@ -0,0 +1,163 @@ +# W11-PREFLIGHT output (opus-reviewer, 2026-11-29) + +Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`. + +**Task:** W11-PREFLIGHT. **Verdict: CHANGES_REQUIRED.** + +The plan's direction is sound. The layering holds, no `INTERNAL_DEPS` change is needed, no two packages own a path at the same time, the gates G1–G5 contain no cycle, and almost every baseline claim matches the source. It is not yet complete enough to write specs from. There is one P1: the plan has no rule for what happens to driver teardown on a worker or poll thread. Eleven P2s need a fix or an explicit risk acceptance before dispatch. + +Paths below are relative to `/home/faumaray/Projects/VoidLibrary`. "Plan" means `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`. + +## P1 + +**F1. S-IO-03: no destructor or teardown-thread rule once the driver owns threads.** (Inferred defect if the spec is written as the plan reads.) +- **Location:** plan :542-548. `Driver::~Driver` at `src/IO/EpollDriver.cpp:1737-1742` and `~EpollBackend` at :953-963 both call `shutdown_and_join()` and ignore the result. +- **Evidence:** + - `Driver::poll_once` (:1843-1847) does not hold its own reference to the backend during a turn. + - Streams hold only a `weak_ptr` to the backend (`include/Void/IO/Detail/Backend.hpp:85-125`). Stop forwarders lock it briefly (:279-285). So the last owning reference can drop on any thread. +- **Trigger:** the plan makes `shutdown_and_join` return `self_join` on a worker or during poll dispatch, and makes it block until the poll turn and the workers finish. Then either: + - `~Driver` or `~EpollBackend` runs on a file worker or the poll thread. The self_join result is ignored, and a joinable `std::thread` is destroyed or joins itself, which calls `std::terminate`. Or the poll turn waits on itself and deadlocks. + - The last backend reference drops on a worker or poller. + - Also, after `ThreadExecutor::join` the plan resumes coroutines inline, so a coroutine can run on a file worker and destroy the `Driver` or a `File` there. +- **Impact:** abort or deadlock on the main teardown path every 1.x IO user takes (IPC, SystemAsync, CryptoAsync, Storage, Runtime). +- **Fix:** add mandatory invariants to the S-IO-03 spec: + - Only `~Driver` does a blocking teardown. It defines what happens on a worker or poll thread: a documented programmer error such as `terminate`, or deferring the join to a safe owner. + - `~EpollBackend` and `~FileWorkers` never block and never destroy a joinable thread. + - Workers and pollers never hold the last owning reference to the backend, or the pool's state is owned separately. + - Tests: Driver destroyed inside a coroutine resumed by poll dispatch, and inside a worker completion. + +## P2 + +**F2. S-IO-03 shutdown step 5 opens a new fd-reuse hazard.** +- **Location:** plan :547, "close the fds, epoll and eventfd". +- **Evidence:** in 1.x, `epoll_fd_` and `wake_fd_` are closed only in `~EpollBackend` (:953-963). `wake()` reads a plain `int` and writes to it (:1033-1042). `enqueue_cancel` (:153-166) and `request_stop` call `wake()`. +- **Trigger:** S-RUNTIME-03 phase 7 shuts the driver down, then phase 8 stops the reactor, which typically calls `wake()`. Late stop forwarders do the same. The write lands on a closed, possibly reused, integer fd. That is also a data race that TSan will report. +- **Fix:** keep epoll/eventfd closure in the backend destructor (1.x placement), or guard `wake()` with a lock and a closed flag. After shutdown, `poll_once` must return before touching any fd. 1.x already returns early once `stopping_` is set (:1056-1058). + +**F3. S-RUNTIME-03 contradicts itself on exporter vs executor order.** +- Plan :729-730 joins the executor (phase 8) before dropping component references (phase 9). +- The test at :742 asserts `exporter_destroyed < executor_joined`. +- **Fix:** drop exporter/component references after their stop finishes and before reactor/executor join (this matches the row name), or change the assertion. Decide in the spec. + +**F4. S-RUNTIME-03: a repeated join after expiry has no budget.** +- Plan :719 fixes the total deadline at the first `begin_shutdown`. Plan :734 says the next call continues. +- After the first expiry, every later `shutdown_blocking` has zero wait budget. Thread joins and executor progress need real waiting, so "release → join again → complete" (:742) becomes a busy loop or a flaky test. +- **Fix:** after a total-budget expiry, later calls use the caller's new deadline. Expired phase deadlines (drain, flush) stay expired. Also say explicitly that an incomplete phase stops the sequence; plan :728 "if incomplete, retain it" is ambiguous. + +**F5. Host lifecycle holes.** +- **Move-assignment:** `Host& operator=(Host&&) = default` (`include/Void/Runtime/Host.hpp:91`) destroys the overwritten state through the `unique_ptr` without running `~Host`. If teardown lives in `~Host` (plan :661), move-assigning over a started Host leaks joinable threads, and `std::thread`'s destructor terminates. Put teardown in `~HostCore` or write a custom move-assignment. +- **Moved-from Host:** accessors like `options()` and `state()` need defined behaviour when the core is null. +- **`~Host` on a Runtime worker:** behaviour is unspecified. The roadmap calls it a detected programmer error. +- **`~Host` off the owner thread:** a non-owner destructor cannot restore the mask, and `SignalWatcher` silently skips the restore off-thread (`src/System/SignalWatcher.cpp:27-37`). The plan (:731) must say whether the gate is leaked or uninstalled without a mask restore. + +**F6. Embedded mode would shut down borrowed resources.** +- Phase 7 calls `driver->shutdown()` and phase 8 joins the executor unconditionally (plan :728-729). In embedded mode both are borrowed (`include/Void/Runtime/Host.hpp:31-56`). The roadmap says borrowed resources must outlive final cleanup. +- **Fix:** tear down by `ResourceOwnership`. Embedded `shutdown_pumping` drains only the business scope and components, and must drive IO and timers through `pump_until`; `TaskScope::join_pumping` never polls IO (`include/Void/Async/TaskScope.hpp:639-647`). + +**F7. AsyncChannel: hand-off vs stop/close arbitration is unspecified (value-loss risk).** +- Plan :327-344 states only the outcomes. +- **Fix:** mandate that a waiter is claimed under the channel lock before a value moves; the stop callback must take the same lock to remove a waiter; a value is never in limbo; a sender gets either success or its value back, exactly once. +- Add a receiver-stop test (no value lost). + +**F8. Retry: the default URBG is deterministic.** +- Plan :102, :137 and :228 default-construct `std::mt19937_64`, which always starts from the same fixed seed. Every process then draws the same jitter, which defeats jitter's purpose. +- House convention seeds from `random_device` unless a deterministic seed is given (`include/Void/Functional/Retry.hpp:87`; `include/Void/Resilience/AsyncPolicy.hpp:487,525-529`). +- **Fix:** seed from `random_device` by default; tests pass a seeded engine. + +**F9. D-W11-05 routing: sonnet takes the riskiest code.** +- A4 (sonnet) rewrites the bounded, repeatable shutdown, poll-owner exclusion, manual-clock-sliced waits and `run()` concurrency in the same `src/IO/EpollDriver.cpp` B2 just changed. That is astra-level work. +- **Fix:** B2 delivers an internal deadline-aware shutdown/poll-owner primitive; A4 only adds the public wrappers, `pump_until` and tests. Or route that part to opus. + +**F10. C-13: area plans must be updated before parallel work.** +- The plan changes contracts in area plans: + - Functional.md: the clock/sleeper adapter moves out of the separate Time header (D-W11-02). + - Runtime.md: awaited shutdown becomes blocking/polling APIs; `file_workers` authority. + - IO.md: the "driver thread" model. + - Several row prerequisites change. +- `docs/roadmap/ARCHITECTURE.md` C-13 (:246-252) requires the decision ledger and area plans to be updated before parallel implementation. `docs/roadmap/**` is missing from the root-owned list (plan :786-790). Add a root step before dispatch. + +**F11. Within-step start failures are not covered (S-RUNTIME-02 acceptance).** +- The `before_step` hook (plan :652, :686) only injects failure between steps. +- Not specified or tested: + - partial failure inside `start_file_workers()` + - the reactor thread constructor throwing `std::system_error` + - `std::thread` throwing inside `ThreadExecutor::start` + - the stop budget for components during failed-start cleanup. +- **Fix:** add an IO fault hook and `io_file_workers_partial_start_failure_joins_started`, catch thread-creation exceptions, and bound the cleanup. + +**F12. Async lifetimes of borrowed objects.** +- **EventBus (Injected mode):** `~TaskScope` skips joining when it runs on an executor thread (`include/Void/Async/TaskScope.hpp:562-575`). If `~EventBus` runs on a worker, dispatch frames can still touch the destroyed bus. Dispatch must reference only a shared core, or this must be a documented error. `flush()` semantics in Injected mode are also unspecified. +- **TimerHandle:** move-only and may outlive its `TimerQueue` (plan :198-199). It needs shared control state. +- **Bounded `parallel_for`:** "All started runners are always joined" (plan :358). Runners that were queued but not yet started would later touch the caller's stack. Either wait for all submitted runners (and document that nested use on the same pool is unsupported) or put runner state, including the copied `F`, in shared ownership. + +**F13. File lifetime is unspecified.** +- `~File` with requests still in flight must defer the fd close until they drain; otherwise the fd can be reused while a worker still uses it. +- `File::close_and_join` on expiry should return `incomplete_shutdown` (exists at `include/Void/IO/Types.hpp:32`) and keep the fd and buffers. +- The roadmap says workers keep the descriptor until the syscall returns. + +## P3 +- **`retry_blocking` signature:** the template parameters have no defaults (plan :139-141), so `retry_blocking(spec, fn)` cannot deduce `NowFn` and the rest from the defaulted argument. Add the defaults. +- **Observable/Signal:** queuing nested `(old, new)` notifications and arguments requires copyable `T`/`Args`, which breaks 1.x compile for move-only types (D-029). Also state "state restored" precisely: the value stays new, as in 1.x. +- **S-IO-03 downstream build** (plan :576): omits CryptoAsync, Runtime and ConfigurationAsync, which also depend on IO. +- **Error kinds:** Runtime `shutdown_incomplete` maps to `timeout`, but IO `incomplete_shutdown` maps to `conflict` (`include/Void/IO/Types.hpp:50-52`). Align them. +- **D1 regression test needs a seam:** the double release isn't visible through the public API. Suggested deterministic trigger: an injected clock whose `now()` requests stop. That call happens between the step-1 drain and the event dispatch (:1083). +- **Mock reactor spin:** the mock `poll_once` ignores `max_wait` (:739-740), so a Runtime reactor on a mock driver busy-spins under TSan. +- **Host business scope:** the default `stop_on_first_error=true` (`include/Void/Async/TaskScope.hpp:32`) means one failing business task stops all of them, against the roadmap's per-component failure policy. +- **MIGRATION records needed** ("observable behavior" row): `shutdown_and_join` now blocks and joins; `validate_limits` rejects `max_file_queue==0`; Sync EventBus becomes snapshot dispatch; legacy `parallel_for` waits for all tasks. +- **Unspecified:** behaviour of concurrent `poll_once` callers; who owns IO files after G5; a stop-and-report rule if B3 or B4 needs an IO edit; how Runtime detects that it is running on a file worker. +- **ThreadExecutor:** `join()` can drain forever if `post()` keeps re-posting after close. `~ThreadExecutor` without `join` is unspecified. + +## D1 claims (all confirmed) +- **(a) Unconditional release — CONFIRMED.** `complete_op_and_collect_tickets` releases at :448, even though `retire_op_locked` is idempotent (:391-394). `release_backend_ref` cannot be called twice safely (`include/Void/Async/Operation.hpp:185-193`); the count underflows. +- **(b) Cancel path doesn't skip finished operations — CONFIRMED** (:1332-1351). The mock path does skip them (:770-781). + - Precise trigger: a stop arrives after the start-of-turn drain (:1053) while `drive_read`/`drive_write` completes the operation (including their own stop check, :1453-1458 and :1527-1535). The end-of-turn drain (:1173) then releases a second time. + - Impact the plan omits: if the waiting coroutine has not suspended yet, `try_arm_suspend` sees a non-zero count and the coroutine hangs forever. Otherwise the counter is silently corrupted. +- **(c) Syscalls outside `mu_` without `in_execution` — CONFIRMED.** `::read` at :1466; `::send` and `::write` at :1549 and :1560. `in_execution` is used only by the mock (:653-671, 758, 774, 791, 847-850). +- **(d) Cross-thread shutdown — CONFIRMED** (:1179-1238). + - It finishes operations regardless of whether a syscall is in progress (:1186-1206). The caller can then free its buffer while `::read` is still writing into it. + - It closes the fd (:1221 → :363) while the poller still holds the integer it read at :1151, so the number can be reused. + - Additional facet: when `~Driver` is the shutdown path, the backend object itself can be destroyed mid-turn (F1). +- **"No test covers it" — CONFIRMED.** `tests/standalone/IO/IoDriver.cpp:458-508` cancels a read that never becomes readable and joins the poller before teardown. + +## Other source claims +- **ManualExecutor bound — CONFIRMED.** `post` counts without a check (`include/Void/Async/Executor.hpp:128-135`); `run_one` decrements before resuming (:216-228). +- **SignalWatcher — CONFIRMED** (`include/Void/System/SignalWatcher.hpp:13-15`; `src/System/SignalWatcher.cpp:27-37,74-90`). +- **Host movable, default destructor, worker count always 0 — CONFIRMED** (`include/Void/Runtime/Host.hpp:88-92,173`). +- **Threads flags — CONFIRMED** (`tests/package/InstalledComponents.cmake:73-79,104-112`; `cmake/VoidConfig.cmake.in:97`). +- **Minor:** `tests/standalone/Async/OperationScope.cpp:135` is not a thread-backed executor; it wraps a ManualExecutor. + +## D-W11-01..15 + +| ID | Recommendation | +| --- | --- | +| D-W11-01 | Accept | +| D-W11-02 | Accept, and update Functional.md (F10) | +| D-W11-03 | Accept; label the pinned test as defect characterization and record it for Wave C | +| D-W11-04 | Accept. System requires Threads, so a Runtime→System edge would also break RuntimeOnly. Add the off-owner rules from F5 | +| D-W11-05 | Modify (F9) | +| D-W11-06 | Accept, provided a throwing `error_sink` is caught and counted and Sync propagation is unchanged; record the change | +| D-W11-07 | Accept | +| D-W11-08 | Accept, provided IOOnly/RuntimeOnly start a real worker thread with Threads disabled; record the libc-with-integrated-pthreads assumption (IO already relies on it at `src/IO/EpollDriver.cpp:47`) | +| D-W11-09 | Accept | +| D-W11-10 | Accept; it fixes a real use-after-free when caller-stack captures outlive a throw. Record the timing change | +| D-W11-11 | Accept, plus partial-start semantics (F11) | +| D-W11-12 | Accept (`max_output_*` unused in `src/Net`, confirmed) | +| D-W11-13 | Accept; record that the C-05 defaults are deferred | +| D-W11-14 | Accept; document that nothing polls a TimerQueue under managed Runtime, so channel deadlines and `retry_async` need caller-driven polling or `pump_until` | +| D-W11-15 | Accept; align error kinds (P3) | + +## Acceptance sentences not covered +- **S-IO-04:** "no IO→Runtime/Net dependency" has no check. Add `rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO` (expect no output) plus a diff of `src/IO/module.cmake`. +- **S-RUNTIME-02:** "failure at every creation/start step" only covers failures between steps (F11). +- **S-RUNTIME-03:** "exporter-before-executor ordering" contradicts the phase order (F3). "Budget accounting" is ambiguous: only the shutdown budget is tested, not memory or admission permits. +- **M-ASYNC-04:** no test for receiver-side cancellation. +- **M-ASYNC-05:** "no captured state in use after join" is tested only for Injected mode, not the legacy Async or Sync modes. +- M-FUNCTIONAL-03, M-TIME-03 and S-IO-03 are fully mapped. + +## Checks not run +- No builds or compile probes; every plan command is unverified. +- No Serena or codebase-memory coverage checks; all evidence comes from direct `sed`/`rg` reads. +- The advisor call timed out. +- Not inspected: the SystemAsync `ProcessManager` shutdown path, IPC/Storage/CryptoAsync internals, `docs/roadmap/VALIDATION.md`, `docs/roadmap/PERFORMANCE.md`. + +**Re-review scope:** the revised S-IO-03, S-IO-04 and S-RUNTIME-03 contracts (F1–F6, F9, F13), the AsyncChannel, Retry, EventBus and TimerQueue invariants (F7, F8, F12), and the area-plan updates (F10). diff --git a/docs/agent-workflow/tasks/W11-PREFLIGHT.md b/docs/agent-workflow/tasks/W11-PREFLIGHT.md new file mode 100644 index 0000000..f4f44fe --- /dev/null +++ b/docs/agent-workflow/tasks/W11-PREFLIGHT.md @@ -0,0 +1,107 @@ +# Wave 11 PREFLIGHT review of the execution-path plan + +Task ID: W11-PREFLIGHT +Role: opus-reviewer +Status: READY + +## 1. Context and baseline +- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11` from + `main` `38436b1`. Only workflow docs changed so far (uncommitted): `docs/agent-workflow/{STATE,TASKS,DECISIONS}.md`, + `docs/agent-workflow/tasks/W11-*.md`. Untracked user files (`.env`, `WG.conf`, `keys`, `jev_token`, + `.serena/`, `.vbs/`, dotfiles) are not inputs; never read or quote them. +- Observed baseline: full RelWithDebInfo `-Werror` build of `38436b1` in `/tmp/void-w11-base`: + `VoidTests` 1,484 discovered, 1,480 passed, 4 skipped, 0 failed; `ctest` 2/2 passed. +- Subject: `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` (opus-planner output for + `M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`, + `S-RUNTIME-02`, `S-RUNTIME-03`). Assignment it answered: `W11-PLAN.md`. Root decisions D-033..D-037 in + `docs/agent-workflow/DECISIONS.md`. Contracts C-01..C-14 in `docs/roadmap/ARCHITECTURE.md`. + +## 2. Objective and deliverables +Independent PREFLIGHT verdict (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE) on whether the +plan's contracts, ordering gates, ownership partition and failure semantics are correct and +complete enough to write implementation specs. Deliver severity-ranked findings (P0–P3) with +location, trigger, impact, evidence and recommended correction, plus a disposition +recommendation for each open decision D-W11-01..D-W11-15. + +## 3. Scope and non-goals +In scope: contract soundness, missing or contradictory invariants, cross-file obligations, +hidden dependencies, layering violations, 1.x compatibility (D-029), testability of every +acceptance sentence, and the plan's factual claims about current source (especially the +claimed epoll defects "D1" in `src/IO/EpollDriver.cpp`, the `ManualExecutor` bound, +`SignalWatcher` behavior, `Host` movability, and installed-consumer Threads flags). +Non-goals: writing code or specs, reviewing unrelated modules, style nits, re-planning +other waves. Do not agree with the planner by default; verify claims in source. + +## 4. Files to inspect +- `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` (subject) and `W11-PLAN.md` (its brief). +- Roadmap rows/plans: `docs/roadmap/modules/{Functional,Time,Async}.md`, + `docs/roadmap/subsystems/{IO,Runtime}.md`, `docs/roadmap/{DEPENDENCIES,ARCHITECTURE,MIGRATION}.md`. +- Source cited by the plan: `include/Void/Functional/Retry.hpp`, `include/Void/Time/Clock.hpp`, + `include/Void/Async/{Executor,Operation,TaskScope,ThreadPool,Channel,ParallelFor,EventBus,Observable}.hpp`, + `include/Void/Async/Detail/Types.hpp`, `include/Void/IO/{Types,Driver,Stream}.hpp`, + `include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `include/Void/Runtime/*.hpp`, + `include/Void/System/SignalWatcher.hpp`, `src/System/SignalWatcher.cpp`, + `include/Void/Resilience/AsyncPolicy.hpp`, `src/SystemAsync/AsyncProcess.cpp`, + `tests/package/InstalledComponents.cmake`, `tests/CMakeLists.txt`, `CMakeLists.txt`, `cmake/Module.cmake`, + `src/Testing/Runner.cpp` (filter semantics), existing tests in `tests/standalone/{Functional,Async,IO,Runtime}/`. + +## 5. Write ownership and coordination +Write scope: none +Allowed commands: read-only `git`, `rg`, `ls`, `wc`, `sed -n`, Serena/codebase-memory read tools. +Optional tiny compile probes only under `/tmp/void-w11-preflight-probe` (never in the repo); +`dev cpp-gcc ...` works only unsandboxed. No repository writes, no commits. + +## 6. Implementation or investigation approach +1. Verify every baseline claim the plan relies on against source (cite `path:line`). +2. For each NEW interface, check: invariants stated, ownership/lifetime of borrowed objects, + exactly-one-terminal-result, stop/expiry/completion races, callbacks outside locks, + overflow-safe time arithmetic, bounded resources, error mapping into existing domains. +3. Check gate order G1..G5 and the A/B partition for overlapping writes, impossible orders, + or hidden edges the plan missed (e.g. Runtime needing Timer, Host move with live threads, + IO `Types.hpp` edited by both root pre-commit and B2/A4). +4. Check layering against `DEPENDENCIES.md` rules 1–2 and D-015 (Functional std-only), + and installed consumers IOOnly/RuntimeOnly (`-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE`). +5. Check 1.x compatibility: `JitterMode` relocation, `ExponentialBackoff` users in Resilience, + EventBus/Observable behavior changes, legacy `parallel_for` change (D-W11-10). +6. Check that each acceptance sentence of the eight roadmap rows maps to at least one + deterministic test in the plan. + +## 7. Interfaces and data contracts +Not applicable for new authorship: you review the plan's proposed interfaces as written in +`W11-PLAN-OUTPUT.md`. Existing contracts: `Void::Functional` error domains (`Error.hpp`), +`Async::OperationOptions`/`AdmissionError`/`TaskScope`, `IO::Driver`/`BufferLease`, `Runtime::Host`. + +## 8. Dependencies and integration +Root will convert your verdict into persisted per-package task specs. Blocking findings +(P0/P1) must be resolved before dispatch; P2 need fix or explicit risk acceptance. + +## 9. Edge cases security and performance +Pay particular attention to: fd reuse after close during concurrent poll, signal-mask +inheritance and pending-signal default action, thread/fd leak on partial start failure, +`TaskScope` destructor pumping/blocking, `ManualClock` + blocking waits, coroutine resume +on a joined executor, retained buffers after shutdown timeout, unbounded tombstones. + +## 10. Acceptance criteria +1. Verdict stated with justification. +2. Every finding has severity, location, trigger, impact, evidence, recommendation. +3. Each D1 defect claim is CONFIRMED or REFUTED with cited lines. +4. Each of D-W11-01..15 has an accept/modify/reject recommendation. +5. Uncovered acceptance sentences (if any) are listed per task. + +## 11. Verification commands and evidence +Read-only inspection. Example: `rg -n "release_backend_ref|in_execution" src/IO/EpollDriver.cpp`, +`sed -n 430,460p src/IO/EpollDriver.cpp`, `git log --oneline f1f9ba3..HEAD -- include/Void/Async`. +Report any probe compile command and its exit status if you run one. + +## 12. Constraints and stop conditions +No edits, commits or network. Stop and report INSUFFICIENT_EVIDENCE for any claim you cannot +verify rather than guessing. Do not spawn agents. + +## 13. Authorization and decisions +Root decision D-034 (Wave 11 scope) under user decisions D-027/D-031. PREFLIGHT is a technical +check; it neither approves scope nor authorizes commits. + +## 14. Return format +Return task ID; verdict; findings ranked P0→P3 (severity, location, trigger, impact, +evidence, recommendation); D1 confirm/refute; D-W11-01..15 dispositions; uncovered +acceptance sentences; checks not run. Compact bullets. Do not spawn children. diff --git a/docs/roadmap/MIGRATION.md b/docs/roadmap/MIGRATION.md index 6479c7b..03f2eab 100644 --- a/docs/roadmap/MIGRATION.md +++ b/docs/roadmap/MIGRATION.md @@ -58,7 +58,7 @@ the explicit path when a backward-compatible downgrade is impossible. | Core/Functional | Error categories, formatting adapters, foundation dependency cleanup | Existing representations and error chains; minimal consumer with optional packages absent | | Containers/Memory | Allocator-aware variants and changed invalidation/ownership | Move-only values, allocator lifetime, stable-handle/invalidation examples, old default behavior | | Data/Binary/Text | Exact integers, checked conversions, Unicode/limit policies | Large identifiers round-trip; overflow errors; old strict signed documents remain accepted/rejected identically | -| Async/IO | Borrowed queued handles and detached work toward structured ownership | Cancellation/parked destruction and explicit join; blocking bridge cannot deadlock its own executor | +| Async/IO | Borrowed queued handles and detached work toward structured ownership | Cancellation/parked destruction and explicit join; blocking bridge cannot deadlock its own executor. Recorded W11 changes: `Driver::shutdown_and_join` blocks for in-flight syscalls and joins file workers; `validate_limits` rejects `max_file_queue == 0`; Sync EventBus and Observable/Signal dispatch over snapshots (subscription changes take effect next pass); nested Observable/Signal updates for copyable types are queued FIFO; legacy `parallel_for` waits for all tasks before rethrowing; Async-mode EventBus handler exceptions are counted instead of terminating; legacy `retry` zero-attempt result kept until Wave C | | Net | Secure TLS defaults, total deadlines, redirect and streaming/session APIs | Private-CA correct-host tests; wrong-host failure; explicit legacy override if offered; no fallback to insecure mode | | Service/Plugin | Reference convenience versus owning handles; new C ABI | Acquired old generation survives replacement; C/C++ paths have separate ABI tests and destruction ownership | | Fsm/Scheduler | Terminal-state consistency and supervised children | Faulted termination, race loser cleanup, state checkpoint restore; no coroutine-frame serialization | diff --git a/docs/roadmap/modules/Functional.md b/docs/roadmap/modules/Functional.md index da6a5e9..8cb4bf1 100644 --- a/docs/roadmap/modules/Functional.md +++ b/docs/roadmap/modules/Functional.md @@ -92,18 +92,22 @@ immutable and bounded; destructor traversal must not recurse through unbounded c ## Pure retry and callable ownership -NEW `RetryState::next(now, last_error)` returns either `stop`, `attempt`, or an absolute -next-attempt time. Defaults: three total attempts and a 30-second total budget; explicit +NEW `RetryState` exposes `begin(now)`, `next(now, outcome)` and `resume(now)`: `next` +returns `stop` or `wait_until(absolute time)`; `begin`/`resume` return `attempt` or `stop`. +Callers map their error to `AttemptOutcome` with a supplied classifier. Defaults: three total attempts and a 30-second total budget; explicit `no_deadline` is required for unlimited time. Zero attempts is invalid. Backoff arithmetic saturates at a configured cap before overflow, rejects negative durations/nonfinite -multipliers, and accepts an injected URBG for reproducible jitter. A stop request or +multipliers, and accepts an injected URBG for reproducible jitter; the default engine is seeded from +`std::random_device`. A stop request or expired admission deadline prevents the next attempt; the policy cannot interrupt an already-running callback or reverse its side effects. Retryability is a supplied predicate and retrying writes still requires the caller's idempotency contract. -Retain the synchronous `retry` adapter temporarily, explicitly named as blocking. A -Time-clock/sleeper adapter belongs in a separate Time-dependent header; Async supplies -its own awaiting adapter. This prevents foundational retry code from importing execution. +Retain 1.x `retry`/`retry_while` unchanged, including the zero-attempt default-result +defect (recorded for Wave C). NEW `retry_blocking` takes injected `now`/`sleep` callables, +so Functional stays standard-library-only and no Time-dependent retry header exists. +Async supplies `Async::retry_async` over `TimerQueue`. This prevents foundational retry +code from importing execution (W11 decision D-038). Memoization becomes per-instance with an explicit key/result signature, default 1,024 entries and FIFO eviction. Recursive calls mark an entry as computing; a repeated key diff --git a/docs/roadmap/subsystems/IO.md b/docs/roadmap/subsystems/IO.md index b599e72..68401f6 100644 --- a/docs/roadmap/subsystems/IO.md +++ b/docs/roadmap/subsystems/IO.md @@ -74,9 +74,11 @@ semantics avoid requiring every dispatch to drain a descriptor completely; the f budget can yield while data remains ready. This follows the [Linux epoll interface](https://man7.org/linux/man-pages/man7/epoll.7.html). -One driver thread owns interest updates and descriptor generations. Producers submit -bounded control messages and wake it through eventfd; an embedder may drive bounded -`poll_once` turns instead. Dispatch up to 64 ready descriptors and 64 KiB/direction per +The Driver owns no thread. One thread at a time runs a `poll_once` turn (the poll owner) +and owns interest updates and generations; a concurrent caller gets `busy` without +touching descriptors. Producers submit bounded control messages and wake the owner +through eventfd. Runtime or the embedder supplies the thread (`Driver::run`, +`pump_until`). Dispatch up to 64 ready descriptors and 64 KiB/direction per descriptor per turn before yielding. Enable writable interest only with pending writes to avoid idle busy loops. HUP/ERR still trigger final read/error inspection. Async completion tickets transfer continuations to the supplied executor outside driver locks. @@ -89,7 +91,10 @@ integer directly. Socket connect completion checks the socket error state; accep obey the same fairness/admission budget. Platform-specific endpoint conversion remains an IO/Net adapter detail until the Net endpoint contract is integrated. -Files initially use a bounded native blocking worker pool. Positional pread/pwrite +Files initially use a bounded native blocking worker pool, started explicitly by +`start_file_workers()` or stepped by `run_file_work()`. Workers run only the syscall (or +an injected syscall shim, the single documented exception) and queue its result; +completions are delivered only by a poll turn. Positional pread/pwrite avoids shared offset races; default writes/syncs for one file are serialized in admission order, and reads expose explicit offsets. Worker ownership retains descriptor and buffer until the syscall returns. Cancelled queued work is removed before execution; an active @@ -116,8 +121,12 @@ Only terminal delivery is arbitrated once; no callback is delivered merely becau arrived while backend access or outcome classification was still pending. Driver shutdown closes admission, cancels queued requests, asks active requests to -stop, drains readiness/control/completion lanes, joins file workers, then releases -descriptors/wake resources. It must keep the executor alive until all completion tickets +stop, waits for the poll owner and in-flight syscalls, drains readiness/control/completion +lanes, joins file workers, then closes operation descriptors. Epoll and wake descriptors +close in the backend destructor. Blocking teardown runs in `Driver::~Driver`; destruction +on a file worker or inside a poll turn is a programmer error. `File::close_and_join` +returns `incomplete_shutdown` on expiry and retains the fd and buffers; a dropped File +closes its fd after its last in-flight request drains. It must keep the executor alive until all completion tickets drain. `close_and_join` cannot free buffers when its own deadline expires; return an incomplete-shutdown report through the owning driver and retain work. Blocking joins are off-driver/off-worker operations; embedded drivers pump until their scopes join. @@ -151,7 +160,7 @@ are not owned by this document. | S-IO-01 | P1 / Async operation ownership and Time clock gates | Portable transfer/error/driver API, buffer leases, descriptor and quota ownership | Mock backend completes/stops in every ordering with exactly one result and no borrowed-buffer escape / astra_implementer | | S-IO-02 | P1 / S-IO-01 | Level-triggered epoll driver, wake/control path, generation-safe close and stream operations | Fragmentation/EAGAIN/EINTR/HUP/fd reuse and full queues do not lose completion or busy-spin / astra_implementer | | S-IO-03 | P2 / S-IO-01 | Bounded positional file workers, serialization, sync and active-cancel handling | Short writes preserve progress; active timeout retains buffers; sync success/failure after stop remains authoritative in the sole result / astra_implementer | -| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, optional System/Net adapters | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer | +| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, SystemAsync conformance (Net adapter deferred: Net has no IO use) | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer | | S-IO-05 | P3 / S-IO-04; performance harness | Optional io_uring capability/backend gate and portability conformance specification | Same tests pass; denied/unsupported capability falls back only before submission; profile evidence justifies enablement / astra_implementer | ## Validation, measurements and migration diff --git a/docs/roadmap/subsystems/Runtime.md b/docs/roadmap/subsystems/Runtime.md index 3c462be..1a96b77 100644 --- a/docs/roadmap/subsystems/Runtime.md +++ b/docs/roadmap/subsystems/Runtime.md @@ -45,10 +45,13 @@ struct Options { class Host { // owns managed resources public: static Result create(Options); // validates, starts no workers - Result start(); // explicit startup transaction - Async::Executor& executor(); - IO::Driver& io(); - Coro::Task> shutdown(Async::OperationOptions); + Result start(StartOptions); // explicit startup transaction + Async::Executor* executor(); + IO::Driver* io(); + Result shutdown_blocking(Async::OperationOptions); + Result poll_shutdown(); // non-blocking step + Result shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions); + // No awaited shutdown Task on the host's own executor: it would self-join (D-038). }; // NEW EmbeddedResources borrows executor, IO driver, Time clock and Memory budget. } @@ -70,11 +73,13 @@ constructors remain inert; start is explicit and errors return before publicatio Use a lifecycle graph of explicit resources, with required/optional dependencies and deterministic topological ordering. Default core order: validate limits/capabilities → -establish signal handling on the designated owner thread → allocate budgets and queues → +install the injected `SignalGate` on the designated owner thread (Runtime has no System +dependency; a System-backed adapter is optional) → allocate budgets and queues → start CPU executor → start IO driver/file workers → start optional service/admission adapters → report ready. SignalWatcher is created before worker threads as required by [its contract](../../../include/Void/System/SignalWatcher.hpp), and is destroyed on -the same creating thread after workers join. +the same creating thread after workers join; off-owner teardown calls `uninstall(false)`, +which closes the gate's descriptor but cannot restore the owner's mask. Each start step returns a retained cleanup action. A failed step aborts its partial resources and unwinds previously successful starts in reverse dependency order. @@ -111,19 +116,23 @@ idempotent; callers join one retained result rather than issue competing stop pa data and requests cooperative cancellation, but all admitted backend activity must still quiesce. Expiry of the total shutdown budget returns shutdown_incomplete with exporter owners and their execution resources retained; a later join continues them. -6. Only after cleanup/export callbacks and backend references retire, stop reactor and - CPU/file workers and release budgets/descriptors/signal masks in reverse creation - order. Observation failure cannot suppress cleanup or convert a failed operation +6. After cleanup/export callbacks and backend references retire, drop component/exporter + references, then stop owned IO, the reactor and CPU/file workers, and release budgets, + descriptors and the signal gate in reverse creation order. Borrowed executor, driver, + clock and memory are never shut down or joined by the Host. Observation failure cannot suppress cleanup or convert a failed operation into success. A timed-out flush is not evidence that its resources are releasable. Default total shutdown observation budget is 30 seconds, shortened by caller options. +Each shutdown call observes min(caller deadline, now + total_timeout) for remaining work; +drain-grace and flush deadlines are fixed at first entry to their phase. An incomplete +phase stops the sequence and the next call resumes there. Expiry produces `shutdown_incomplete` containing pending owner IDs/counts and phase; the Host remains in joining with resources retained. It can be waited again or the application can choose explicit process termination. There is no forced thread kill, buffer release or dlclose. Borrowed resources must outlive final cleanup, not merely -the first timed-out shutdown call. Destruction blocks to join only on an allowed -off-worker owner thread; on a runtime worker, callers must await shutdown before -destroying Host. Self-join misuse is detected as a programmer error. Process-level +the first timed-out shutdown call. Destruction blocks to join only off Runtime threads; +destruction on a Runtime worker, reactor or IO file-worker thread is a programmer error +that terminates after a diagnostic. Process-level hard-stop policy belongs to the application, not a hidden destructor timeout. Uncaught task exceptions reach explicit scope/error sinks. Default failure policy @@ -156,8 +165,8 @@ Every row is PLANNED. | ID | Phase / depends on | Intended scope | Acceptance / recommended role | | --- | --- | --- | --- | | S-RUNTIME-01 | P1 / Async ownership, IO driver, Time/Memory ports | Inert Host options, borrowed/owned resource graph, dependency validation | No constructor starts workers; invalid bounds/cycles fail before external admission / sol_implementer | -| S-RUNTIME-02 | P2 / S-RUNTIME-01; System signal gate | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer | -| S-RUNTIME-03 | P2 / S-RUNTIME-02 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer | +| S-RUNTIME-02 | P2 / S-RUNTIME-01, M-ASYNC-04, S-IO-03; signal gate (injected port) | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer | +| S-RUNTIME-03 | P2 / S-RUNTIME-02, S-IO-04 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer | | S-RUNTIME-04 | P3 / S-RUNTIME-03; Service/Configuration transaction gates | Optional managed adapters, transactional resize/reload and embedded examples | Same workload runs embedded/managed; failed resource prepare keeps active generation / sol_implementer | | S-RUNTIME-05 | P3 / S-RUNTIME-04; profile harness | Latency/throughput/footprint presets, inspection and tuning gates | Limits remain invariant per preset; measured p99/RSS/build cost reported with environment / astra_implementer | diff --git a/include/Void/Async/Detail/Types.hpp b/include/Void/Async/Detail/Types.hpp index d5512a3..d16a975 100644 --- a/include/Void/Async/Detail/Types.hpp +++ b/include/Void/Async/Detail/Types.hpp @@ -29,7 +29,8 @@ enum class AsyncErrorCode : std::int32_t { invalid_argument = 5, self_join = 6, backend_error = 7, - limit_exceeded = 8 + limit_exceeded = 8, + closed = 9 }; enum class DomainOutcomeKind { @@ -68,6 +69,7 @@ struct OperationOptions { break; case AsyncErrorCode::cancelled: case AsyncErrorCode::stopped: + case AsyncErrorCode::closed: kind = ErrorKind::cancelled; break; case AsyncErrorCode::timeout: diff --git a/include/Void/IO/Types.hpp b/include/Void/IO/Types.hpp index ddd82cf..bd2c93f 100644 --- a/include/Void/IO/Types.hpp +++ b/include/Void/IO/Types.hpp @@ -30,7 +30,8 @@ enum class IoErrorCode : std::int32_t { invalid_argument = 8, os_error = 9, incomplete_shutdown = 10, - exhausted = 11 + exhausted = 11, + sync_failed = 12 }; [[nodiscard]] inline Void::Result::Error make_io_error( @@ -66,6 +67,7 @@ enum class IoErrorCode : std::int32_t { break; case IoErrorCode::eof: case IoErrorCode::os_error: + case IoErrorCode::sync_failed: kind = ErrorKind::io; break; case IoErrorCode::invalid_argument: diff --git a/include/Void/Runtime/Options.hpp b/include/Void/Runtime/Options.hpp index 3b178b1..92661ae 100644 --- a/include/Void/Runtime/Options.hpp +++ b/include/Void/Runtime/Options.hpp @@ -25,7 +25,9 @@ enum class RuntimeErrorCode : std::int32_t { cycle_detected = 4, invalid_state = 5, unsupported = 6, - internal = 7 + internal = 7, + self_join = 8, + shutdown_incomplete = 9 }; [[nodiscard]] inline Void::Result::Error make_runtime_error( @@ -49,6 +51,8 @@ enum class RuntimeErrorCode : std::int32_t { case RuntimeErrorCode::conflict: case RuntimeErrorCode::cycle_detected: case RuntimeErrorCode::invalid_state: + case RuntimeErrorCode::self_join: + case RuntimeErrorCode::shutdown_incomplete: kind = ErrorKind::conflict; break; case RuntimeErrorCode::unsupported: