From c6789e7dbfa5d62199e80d1a2cc419c9a6ea7d55 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 29 Nov 2026 19:45:03 +0300 Subject: [PATCH] docs(wave11): S-IO-03 and M-ASYNC-04 specs with review amendments (D-042) Co-Authored-By: Claude Opus 5.5 --- docs/agent-workflow/DECISIONS.md | 2 + docs/agent-workflow/TASKS.md | 26 +- docs/agent-workflow/tasks/M-ASYNC-04.md | 228 +++++++++++++ docs/agent-workflow/tasks/S-IO-03.md | 318 ++++++++++++++++++ .../tasks/W11-SPEC-REVIEW-1-OUTPUT.md | 186 ++++++++++ .../agent-workflow/tasks/W11-SPEC-REVIEW-1.md | 69 ++++ 6 files changed, 825 insertions(+), 4 deletions(-) create mode 100644 docs/agent-workflow/tasks/M-ASYNC-04.md create mode 100644 docs/agent-workflow/tasks/S-IO-03.md create mode 100644 docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md create mode 100644 docs/agent-workflow/tasks/W11-SPEC-REVIEW-1.md diff --git a/docs/agent-workflow/DECISIONS.md b/docs/agent-workflow/DECISIONS.md index 6f8418c..3565d66 100644 --- a/docs/agent-workflow/DECISIONS.md +++ b/docs/agent-workflow/DECISIONS.md @@ -90,3 +90,5 @@ execution without pausing between waves). They are not new user approvals. | N-001 | Note (not a decision of this session): the VoidForge session reports (2026-11-29, Forge D46) that the user granted permission to distribute VoidLibrary with VOID Forge, including Forge-motivated additions, with no relicensing. VoidLibrary still has no LICENSE file; any license file or wording remains a user decision to be confirmed directly in a VoidLibrary session. | Relayed by peer session; not user input in this session | | D-039 | User reconfirmed in this session (2026-11-29, "i allow pushing to remote") that pushing to `origin` is allowed; consistent with D-032 (push verified `main` and active feature branches). `main` is pushed only after a wave is verified and merged, keeping it green for VoidForge, which tracks remote `main`. | CONFIRMED by user | | D-040 | PREFLIGHT-2 (`tasks/W11-PREFLIGHT-2-OUTPUT.md`) returned CHANGES_REQUIRED with N1–N6 (P2) and P3 lines, no P0/P1. Root resolutions are the mandatory amendment `tasks/W11-CONTRACT-R2.md` (destruction blocks until complete; embedded ManualExecutor pumping; shutdown polling/loop rules; File fd state machine; channel timer callbacks use shared waiter state; EventBus destruction gating). A1/B1 continue with documentation-only corrections. The re-review of R2 happens on the B2/B3/B4/A2/A3 specs before each dispatch. | C-03–C-06; D-038 | +| D-041 | VoidForge wave order (after Wave 11, before the D-036 foundation wave): (1) `VL-STREAM-01`, `VL-PROC-01` (P0); (2) small P1 crypto/text items `VL-CRYPTO-01`, `VL-CRYPTO-02`, `VL-TEXT-01`, plus hygiene `VL-NET-W01`; (3) `VL-NET-02` (TLS client stream + SMTP); (4) `VL-WASM-01`, `VL-TOML-01`, `VL-MCP-01`; Sqlite items `VL-SQLITE-01..06` (G7 automatic-rollback detection first) after that. Root sequencing; peer requests are inputs, not user approvals. | D-037 | +| D-042 | W11-SPEC-REVIEW-1 (`tasks/W11-SPEC-REVIEW-1-OUTPUT.md`) findings S1–S9 (S-IO-03) and A1–A3 (M-ASYNC-04), all P2, adopted verbatim as mandatory amendments in the two specs. S9 resolution: S-IO-03 (B2) owns and tests the public inline wrappers `Driver::begin_shutdown/shutdown(options)/quiescent/shutdown_complete`; S-IO-04 (A4) keeps `run()`, `Pump.hpp`, SystemAsync conformance and tests. Amended text is checked by the fresh post-implementation review rather than a third pre-dispatch review, since it is the reviewer's own replacement text. Worktree dispatches start with `git merge --ff-only ` (X-WF-01). | C-03–C-06; D-038, D-040 | diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index fad187e..43a5cdd 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -151,11 +151,11 @@ Decisions: D-033..D-036. | ID | Deliverable | Spec | State | Verification summary | | --- | --- | --- | --- | --- | | W11-PLAN | Architecture/task plan + REV1 addendum | [W11-PLAN](tasks/W11-PLAN.md), [output](tasks/W11-PLAN-OUTPUT.md), [REV1](tasks/W11-PLAN-REV1-OUTPUT.md) | DONE | PREFLIGHT 1 CHANGES_REQUIRED ([findings](tasks/W11-PREFLIGHT-OUTPUT.md)); resolved in REV1/D-038; PREFLIGHT 2 running | -| M-FUNCTIONAL-03 | Pure retry decisions + named blocking adapter (A1) | [spec](tasks/M-FUNCTIONAL-03.md) | IN PROGRESS | sonnet-implementer, worktree | -| M-TIME-03 | Injected-deadline domains: TimerQueue + clock saturation (B1); `retry_async` (B1b, after G1) | [spec](tasks/M-TIME-03.md) | IN PROGRESS | B1 opus-implementer, worktree | -| M-ASYNC-04 | Bounded executors, cancellable channels, future pool adapter, ParallelFor | — | PLANNED | — | +| M-FUNCTIONAL-03 | Pure retry decisions + named blocking adapter (A1) | [spec](tasks/M-FUNCTIONAL-03.md) | VERIFIED (`26edf65`) | Review W11-REVIEW-A1 READY (P3 1/2/5 fixed by root); ResilienceAsync subset 475 (472 ✔, 3 ⊘), filtered 43/43, ctest 2/2, TSan 40/40 0 races, ASan+UBSan 40/40, `-Werror` syntax checks clean | +| M-TIME-03 | Injected-deadline domains: TimerQueue + clock saturation (B1); `retry_async` (B1b, after G1) | [spec](tasks/M-TIME-03.md) | IN REVIEW (B1) | B1 DONE (TimerQueue 15/15, DeadlineDomains 2/2, ClockSaturation 1/1, TSan 17/17 ×10); fresh review running; B1b pending | +| M-ASYNC-04 | ThreadExecutor, FuturePool, AsyncChannel, bounded ParallelFor (A2) | [spec](tasks/M-ASYNC-04.md) | READY (waits for B1 commit, G2) | — | | M-ASYNC-05 | EventBus/Observable snapshot dispatch, joined subscriptions | — | PLANNED | — | -| S-IO-03 | Bounded positional file workers, sync, active-cancel | — | PLANNED | — | +| S-IO-03 | Bounded positional file workers, sync, active-cancel, shutdown core, D1 fixes (B2) | [spec](tasks/S-IO-03.md) | IN PROGRESS | opus-implementer, worktree | | 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 | — | @@ -183,3 +183,21 @@ specs' observed baselines (D-035); not separately scheduled. | 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 | | VL-SQLITE-05 | P2 (non-blocking) | Write admission and `wal_checkpoint_recommended` use on-disk `-wal` size, which passive checkpoints never shrink, so `begin(Immediate)` stays `overloaded`; admit on un-checkpointed frames or truncate on admission failure (`Sqlite.cpp` ~:417-423, :1756-1762, :1918-1923) | PLANNED | | VL-SQLITE-06 | P2 (non-blocking) | `Statement::step`/`exec` do not detect SQLite automatic rollback (FULL/IOERR/NOMEM/BUSY/INTERRUPT) via `sqlite3_get_autocommit`, so `Transaction` stays `Active` and later statements run in autocommit (`Sqlite.cpp` ~:884-910) | PLANNED | + +## Quality findings surfaced during Wave 11 (backlog, root-owned) + +| ID | Finding | Source | State | +| --- | --- | --- | --- | +| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then fix in `tests/CMakeLists.txt`) | +| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then count failures independently of retention) | +| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | PLANNED (scanner hardening or lint) | +| X-WF-01 | Agent `isolation: worktree` checkouts start at `main` (`38436b1`), not the wave branch tip; dispatches must fast-forward the worktree to the stated HEAD first | Observed in A1 | RECORDED (dispatch rule) | + +## VoidForge upstream requests — M04 identity batch (received 2026-11-29; D-041) + +| ID | Priority | Request | State | +| --- | --- | --- | --- | +| VL-CRYPTO-01 | P1 | Generic `Crypto::hmac(HashAlgorithm, key, message)` incl. HMAC-SHA1 (TOTP RFC 6238/4226); RFC 2202 vectors | PLANNED | +| VL-CRYPTO-02 | P1 | `pbkdf2_hmac_sha256(password, salt, iterations, out_len)` (RFC 8018 §5.2) on the builtin HMAC path; RFC 7914 §11 vectors; bounded iterations/output | PLANNED | +| VL-NET-02 | P1 (blocks Forge production email) | Public TLS client stream (TCP+TLS, CA + hostname verification, STARTTLS upgrade) + minimal SMTP submission client (EHLO, STARTTLS-required or implicit TLS, AUTH PLAIN over TLS only, MAIL/RCPT/DATA with dot-stuffing, bounded size, deadlines) | PLANNED | +| VL-TEXT-01 | P2 | RFC 4648 base32 + Crockford base32 encode/decode | PLANNED | diff --git a/docs/agent-workflow/tasks/M-ASYNC-04.md b/docs/agent-workflow/tasks/M-ASYNC-04.md new file mode 100644 index 0000000..f8e4d41 --- /dev/null +++ b/docs/agent-workflow/tasks/M-ASYNC-04.md @@ -0,0 +1,228 @@ +# M-ASYNC-04 — Bounded ThreadExecutor, FuturePool, cancellable AsyncChannel, bounded ParallelFor + +Task ID: M-ASYNC-04 +Role: sonnet-implementer +Status: READY + +## 1. Context and baseline +- Wave 11 package step A2. Repo VoidLibrary, branch `feat/roadmap-p2-wave11`. You work in an isolated + git worktree of the HEAD given in your prompt (it includes M-FUNCTIONAL-03 and the M-TIME-03 + `Async/Timer.hpp`); cwd = worktree root. Never read the user's untracked files in the main checkout. +- Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed. +- Observed source (M-ASYNC-01 characterization folded in, D-035): + - `include/Void/Async/Executor.hpp:58-113`: `Executor` base (`post`, `try_post`, `post_completion`, + reservation API `supports_reservation/try_reserve_slot/commit_reserved/release_reserved`, + `has_background_workers`, `is_executor_thread` via `detail::ExecutorThreadGuard` ~:86-96). + `ManualExecutor` (:120-254) is the only executor; its bound excludes running work (:216-228) and + `post()` bypasses the bound (:128-135). No thread-backed executor exists. + - `include/Void/Async/ThreadPool.hpp` (`Void::Concurrency::ThreadPool`): `max_queue == 0` unbounded, + bound counts only the queue, `submit` throws after stop, `try_submit` returns `nullopt` for both + full and stopped; includes Log. + - `include/Void/Async/Channel.hpp` (`Concurrency::Channel`): blocking only; out of scope (capacity-0 + deadlock is a recorded residual). + - `include/Void/Async/ParallelFor.hpp` (`Void::Concurrency::parallel_for`): one future per index; + on the first throwing `fut.get()` returns without joining the rest (lifetime hazard). + - Root prep `7f95f89` added `AsyncErrorCode::closed = 9` (→ `ErrorKind::cancelled`). + - M-TIME-03 provides `include/Void/Async/Timer.hpp` (`TimerQueue`, `TimerHandle`, `TimerEvent`, + `schedule_at(when, callback(TimerEvent) noexcept)`; `cancel()==false` means fired-or-firing). +- Requirements: roadmap row M-ASYNC-04 ("Bounded executors, cancellable channels, future pool adapter, + ParallelFor | Bounds include running work; producer stop and close-drain deterministic; chunk + errors join"); C-03..C-05; decisions D-038, D-040, D-W11-10, D-W11-13. +- MANDATORY design sources: `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-ASYNC-04, + `W11-PLAN-REV1-OUTPUT.md` F7, F11, F12, P3 (ThreadExecutor), `W11-CONTRACT-R2.md` N5. + Precedence R2 > REV1 > PLAN. + +## 2. Objective and deliverables +NEW `include/Void/Async/ThreadExecutor.hpp`, `include/Void/Async/FuturePool.hpp`, +`include/Void/Async/AsyncChannel.hpp`; EDIT `include/Void/Async/ParallelFor.hpp` (NEW bounded overload ++ legacy overload joins all futures before rethrowing); NEW tests +`tests/standalone/Async/{ThreadExecutor,FuturePool,AsyncChannel,ParallelForBounded}.cpp`. + +## 3. Scope and non-goals +Out: `Executor.hpp`, `Operation.hpp`, `TaskScope.hpp`, `ThreadPool.hpp`, `Channel.hpp` changes; +`async_wait_for_capacity` and channel byte budget (D-W11-13); EventBus/Observable (M-ASYNC-05); +build files. + +## 4. Files to inspect +`include/Void/Async/{Executor,Operation,TaskScope,Task,ThreadPool,ParallelFor,Timer}.hpp`, +`include/Void/Async/Detail/Types.hpp`, `tests/standalone/Async/{OperationScope,Executor,ParallelFor,ThreadPool}.cpp`, +and the design sources in §1. + +## 5. Write ownership and coordination +Write scope: `include/Void/Async/ThreadExecutor.hpp` (NEW), `include/Void/Async/FuturePool.hpp` (NEW), +`include/Void/Async/AsyncChannel.hpp` (NEW), `include/Void/Async/ParallelFor.hpp`, +`tests/standalone/Async/ThreadExecutor.cpp`, `tests/standalone/Async/FuturePool.cpp`, +`tests/standalone/Async/AsyncChannel.cpp`, `tests/standalone/Async/ParallelForBounded.cpp` (all NEW tests). +Forbidden: every other path. An IO worker may run concurrently in another worktree. No git +commit/branch/stash/reset. + +## 6. Implementation or investigation approach +MANDATORY: +- ThreadExecutor: `create` starts no threads; `start()` once; a `before_worker_start(i)` hook error or + a caught `std::system_error` from `std::thread` joins started workers and returns an error (shared + path). Bound = queued + running normal-lane work (`max_admitted >= 1`); `try_post` → `overloaded` + at the bound; a slot is released only after the resumed handle returns. Every resume runs inside + `detail::ExecutorThreadGuard`. Legacy `post()` never rejects (counted; may exceed the bound); after + `close()` legacy `post()` goes to the completion lane (counted). `post_completion` uses a reserved, + prioritized lane that drains after `close()`. `join()` = close + drain both lanes until empty and + nothing running + join; on a worker returns `self_join`. After join, posts resume inline on the + caller (counted `inline_after_join`), never dropped. No drain cap (C-03); a self-reposting handle + that prevents join is a documented caller error. `~ThreadExecutor` without join = close()+join(); + on its own worker → stderr diagnostic + `std::terminate`. NEW `idle()` (both lanes empty, nothing + running). Reservation API implemented and compatible with `TaskScope`. +- FuturePool: reserve-then-transfer; on rejection the callable is NOT moved; exceptions go to the + future; bound includes running work. +- AsyncChannel (F7 + N5): one mutex for buffer and both waiter lists; waiter nodes with state + `{linked, claimed, cancelled, timed_out, closed}`; pairing sender/receiver happens in one critical + section (unlink+claim the waiter, then move the value) so a value is always in exactly one place + (sender node, buffer, or receiver slot). Stop callbacks and timer callbacks take the same lock: + if still `linked` → unlink + `cancelled`/`timed_out` (sender keeps/gets back its value); if + `claimed` → no-op. Timer callbacks capture shared waiter state (`shared_ptr` control block) or a + `weak_ptr` to the channel + waiter id looked up under the lock — NEVER a raw pointer into a + coroutine frame (N5). Every resume via `post_completion` after unlock. A wait with a deadline but + no `timers` → `invalid_argument`. `close()` gives waiting senders `closed` + their value; receivers + drain the buffer FIFO then get `closed`. `capacity == 0` → `invalid_argument` at create. +- Bounded parallel_for: shared `detail::PForState` (decay-copied `F`, chunk counter, error slots); + runners submitted with `try_submit`; if rejected the caller runs chunks inline; no new chunk after + stop or (with `stop_on_error`) an error; the caller waits for EVERY submitted runner future + (including never-started ones); reported error = lowest-indexed failed chunk; nested use on the + same pool from a pool worker is documented unsupported. Legacy overload waits for all futures + before rethrowing the first exception (D-W11-10). + + +### Amendments from W11-SPEC-REVIEW-1 (MANDATORY; override earlier text where they differ) +Source: `docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md` A1–A3 + P3 (decision D-042). +- A2 no-worker join: admission before `start()` queues normally. When no worker is running, + `join()` and the destructor drain both lanes inline on the caller under `ExecutorThreadGuard` + (counted as `inline_after_join`) and never wait. `start()` after `close()` or after a successful + `start()` → `invalid_argument`; after a failed `start()` it may be retried. +- A3 reservations: a reserved slot counts in `admitted()` and in the bound; `try_reserve_slot` after + `close()` → `stopped`; a reservation taken before `close()` stays binding (`commit_reserved` after + `close()` enqueues normally); `join()` also waits until no reservation is outstanding. +- P3: `make_async_error(ChannelError, ...)` is `inline`. AsyncChannel deadlines are judged by + `timers->clock()`; check stop, then deadline, then "deadline without timers" → `invalid_argument`, + before any state change (value returned in `SendFailure`); `TimerEvent::closed` → `cancelled`; + `schedule_at` failure `overloaded` → `ChannelError::overloaded`, `stopped` → `cancelled`; + `max_waiters` applies per direction, 0 → `invalid_argument`; frames hold `shared_from_this()`; + never construct or destroy a `std::stop_callback` while holding the channel mutex; destroying a + suspended Task is a caller error; the resume executor must outlive every pending resume; FIFO means + per-producer order. TimerQueue facts (from the M-TIME-03 implementation): `cancel() == true` + destroys the callback on the caller's thread before returning — so never call `TimerHandle::cancel()` + while holding the channel mutex if the callback's destructor could take it; `cancel() == false` + means fired-or-firing. parallel_for: at most `max_concurrency` chunks run at once (counting the + caller when it runs inline); `Kind::rejected` is not produced in this wave; precedence + `invalid_argument` > `failed` > `stopped`; `first >= last` → success; compute the range in the + unsigned type of `I`. ThreadExecutor: `idle()`/`stats()` are snapshots; the switch to inline mode + happens under the executor mutex; `admitted()` = queued + running + reserved. FuturePool: if + creating the frame throws, release the slot and rethrow. `ExecutorThreadGuard` is at + `Executor.hpp:32-51`. Stop and report if `Async/Timer.hpp` is missing or differs from M-TIME-03 §7. + +## 7. Interfaces and data contracts +```cpp +namespace Void::Async { +struct ThreadExecutorOptions { std::size_t workers{1}; std::size_t max_admitted{4096}; + std::function(std::size_t)> before_worker_start{}; }; +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 = {}); + [[nodiscard]] Void::Result::Result start(); + void post(std::coroutine_handle<>) override; + [[nodiscard]] std::expected try_post(std::coroutine_handle<>) override; + void post_completion(std::coroutine_handle<>) override; + [[nodiscard]] bool supports_reservation() const noexcept override; + [[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; + void close() noexcept; [[nodiscard]] Void::Result::Result join(); + [[nodiscard]] bool idle() const noexcept; [[nodiscard]] std::size_t admitted() const noexcept; + [[nodiscard]] ThreadExecutorStats stats() const noexcept; ~ThreadExecutor() override; }; +class FuturePool { public: explicit FuturePool(ThreadExecutor&) noexcept; + template [[nodiscard]] std::expected>, AdmissionError> + try_submit(F&& f); }; +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]] inline Void::Result::Error make_async_error(ChannelError, std::string message = {}); +} +namespace Void::Concurrency { // ParallelFor.hpp (NEW overload) +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); +} +``` +`ChannelError` maps into `kAsyncErrorDomain` via existing codes (`closed`→`AsyncErrorCode::closed`, +`cancelled`→`cancelled`, `timed_out`→`timeout`, `overloaded`/`full`→`overloaded`, `empty`/`invalid_argument`→ +`invalid_argument`); the overload must not collide with existing `make_async_error` overloads. +`max_concurrency == 0` = the pool's thread count; `grain == 0` → `invalid_argument`. Unchanged 1.x: +`ManualExecutor`, `ThreadPool`, `Channel`, legacy `parallel_for` signatures, `spawn`, `schedule_on`. + +## 8. Dependencies and integration +Upstream: M-ASYNC-03 (done), M-TIME-03 Timer (gate G2, present in your base). Downstream: +S-RUNTIME-02 uses `ThreadExecutor` (`create/start/close/join/idle/admitted/stats`), M-ASYNC-05 may use +`ThreadExecutor` in tests. Keep §7 exactly. Root integrates and commits. + +## 9. Edge cases security and performance +Stop vs send vs receive vs close vs timer races (TSan); move-only `T`; exceptions thrown by `T`'s move +constructor (document strong guarantee where possible); bounded waiters; no busy-waiting in join; +no user code under locks; hook throwing; zero workers rejected at create. + +## 10. Acceptance criteria +Tests (all pass; TSan 0 races; ASan+UBSan 0 errors): +- `ThreadExecutor.cpp`: `thread_executor_create_starts_no_threads`, `thread_executor_bound_includes_running_work`, + `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_system_error_path_shared_with_hook`, + `thread_executor_legacy_post_spawn_schedule_on_compat`, `thread_executor_inline_after_join_counted`, + `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_receiver_stop_after_claim_delivers_value_no_loss`, `channel_sender_stop_vs_receive_race_exactly_once_tsan` + (10,000 iterations; multiset sent == received ∪ returned), `channel_close_wakes_senders_with_value_and_drains_receivers`, + `channel_deadline_requires_timers`, `channel_deadline_times_out_once_manual_clock_poll`, + `channel_timer_close_settles_waiter_cancelled`, `channel_timer_fire_after_waiter_destroyed_safe`, + `channel_waiter_bound_overloaded`, `channel_move_only_values`, `channel_mpmc_fifo_tsan`, + `channel_deadline_check_order_returns_value`. +- Additional ThreadExecutor tests: `thread_executor_join_without_start_drains_inline`, + `thread_executor_start_twice_and_after_close_invalid`, `thread_executor_reservation_across_close_binding`. +- `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`, + `parallel_for_bounded_waits_all_submitted_runners`, `legacy_parallel_for_exception_joins_all`. +- Existing `ParallelFor`, `ThreadPool`, `ThreadPoolBackpressure`, `Channel`, `OperationScope`, `Executor`, + `Coro`, `TimerQueue` tests pass unchanged. `-Werror` clean. + +## 11. Verification commands and evidence +Cwd = worktree root; `dev` with the sandbox disabled. Confirm new suites appear in output. +```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 --parallel 8 && /tmp/void-w11-async4/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor|ThreadPool|ThreadPoolBackpressure|Channel|OperationScope|Executor|Coro|TimerQueue)\." && 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 --parallel 8 && /tmp/void-w11-async4-tsan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."' +dev cpp-gcc -c bash -lc 'for f in ThreadExecutor FuturePool AsyncChannel ParallelForBounded; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Async/$f.cpp || exit 1; done' +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 --parallel 8 && /tmp/void-w11-async4-asan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."' +``` + +## 12. Constraints and stop conditions +No edits outside write scope; no weakened assertions; no disabled warnings; no change to 1.x +semantics other than D-W11-10. Stop and report BLOCKED if the contract needs a forbidden-file edit, +the reservation API cannot be satisfied as specified, or two repair attempts at one check fail. + +## 13. Authorization and decisions +Root decisions D-034, D-038, D-040 under user decisions D-027/D-029/D-031. Listed files only; no +commits, pushes or other side effects. + +## 14. Return format +Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance +criterion; commands with cwd/results (counts, TSan/ASan); checks not run; residual risks; integration +notes (worktree path). Do not spawn children. diff --git a/docs/agent-workflow/tasks/S-IO-03.md b/docs/agent-workflow/tasks/S-IO-03.md new file mode 100644 index 0000000..ab82073 --- /dev/null +++ b/docs/agent-workflow/tasks/S-IO-03.md @@ -0,0 +1,318 @@ +# S-IO-03 — Bounded positional file workers, sync, active cancel, safe shutdown core, epoll D1 fixes + +Task ID: S-IO-03 +Role: opus-implementer +Status: READY + +## 1. Context and baseline +- Wave 11 package step B2 (critical path). Repo VoidLibrary, branch `feat/roadmap-p2-wave11`. + You work in an isolated git worktree of the HEAD given in your prompt; cwd = worktree root. + Never read the user's untracked files (`.env`, `WG.conf`, `keys`, `jev_token`) in the main checkout. +- Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed. +- Observed source (cite-checked by planner and two PREFLIGHT reviews): + - `include/Void/IO/Driver.hpp:59-105`: `Driver` (non-movable; `create(executor, BackendOptions, + clock, pmr resource)`, `poll_once(max_wait)`, `wake`, `request_stop`, `shutdown_and_join`), no + thread, no run loop, no file API. `~Driver` at `src/IO/EpollDriver.cpp:1737-1742` and + `~EpollBackend` at `:953-963` both call `shutdown_and_join()` and ignore the result. + - `include/Void/IO/Types.hpp`: `IoErrorCode` (incl. root-added `sync_failed = 12` → `ErrorKind::io`), + `IoLimits{max_descriptors 4096, max_operations 8192, ..., file_workers 4, max_file_queue 256}` + (:100-110), `validate_limits` ignores file fields (:112-124), `BackendOptions`, `DriverTelemetry`. + - `include/Void/IO/Detail/Backend.hpp`: `DriverBackend` virtual interface; streams hold `weak_ptr` + to the backend (:85-125); stop forwarders lock briefly (:279-285). + - Epoll defects D1 (all CONFIRMED): (a) `complete_op_and_collect_tickets` releases the backend ref + unconditionally (`EpollDriver.cpp:448`) though `retire_op_locked` is idempotent (:391-394); + (b) cancel path (:1332-1351) doesn't skip retired ops (mock does, :770-781) — stop after the + start-of-turn drain (:1053) while `drive_read/write` completes the op double-releases at the + end-of-turn drain (:1173); (c) `::read`/`::send`/`::write` at :1466/:1549/:1560 run outside `mu_` + without `in_execution` (mock-only, :653-671); (d) cross-thread `shutdown_and_join` (:1179-1238) + completes ops mid-syscall and closes fds (:1221→:363) while a poller holds the integer (:1151). + - `poll_once` early-returns once stopping (`:1056-1059`); mock `poll_once` ignores `max_wait` + (:739-741); `IoErrorCode::busy` already means "concurrent op not allowed" (:533-540). + - Consumers of `Driver`: IPC (`src/IPC/Session.cpp:1118-1129` bounded poll loop ignoring result), + SystemAsync, CryptoAsync, Storage, ConfigurationAsync, Runtime tests. +- Requirements: roadmap row S-IO-03 ("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"); `docs/roadmap/subsystems/IO.md` + (updated in `7f95f89`); contracts C-03..C-06; decisions D-038, D-040. +- MANDATORY design sources (read fully): `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §S-IO-03, + `W11-PLAN-REV1-OUTPUT.md` F1, F2, F9, F11, F13 and P3 (D1 seam), and `W11-CONTRACT-R2.md` N3, N4, + P3-5, P3-9. Precedence: R2 > REV1 > PLAN. This spec restates the mandatory points. + +## 2. Objective and deliverables +1. NEW `include/Void/IO/File.hpp`: `FileOpenOptions`, `SyncMode`, `FileSyscallResult`, + `FileSyscalls` (injectable shim with `native()`), move-only `File`, `read_exact_at`, `write_all_at`. +2. EDIT `include/Void/IO/Driver.hpp`: `open_file`, `adopt_file_fd`, `start_file_workers`, + `run_file_work`, NEW free `is_io_worker_thread()`; `~Driver` becomes the only blocking teardown; + public inline shutdown wrappers `begin_shutdown()`, `shutdown(Async::OperationOptions)`, + `quiescent()`, `shutdown_complete()` (moved from S-IO-04 by D-042 so B2 can test its primitive). +3. EDIT `include/Void/IO/Types.hpp`: append `BackendOptions::file_syscalls{nullptr}` (borrowed), + `BackendOptions::before_file_worker_start{}`, `DriverTelemetry::{queued_file_requests, + active_file_requests, file_workers_running, duplicate_completions_ignored}`, NEW + `DriverShutdownReport`; `validate_limits` rejects `max_file_queue == 0`. +4. EDIT `include/Void/IO/Detail/Backend.hpp`: file-submit virtuals + shutdown primitives + (`begin_shutdown`, `advance_shutdown`, `shutdown_complete`, `quiescent`, `teardown_blocking`). +5. EDIT `src/IO/EpollDriver.cpp`: D1 fixes, poll-owner exclusion, file completion lane, bounded + shutdown core, F2 wake/close rules; NEW private `src/IO/FileWorkers.{hpp,cpp}`. +6. NEW `tests/standalone/IO/IoFile.cpp`. + +## 3. Scope and non-goals +In: the above, for both mock and epoll backends (file pool shared via the base backend). +Out: `Driver::run` and `Pump.hpp`/`pump_until` (S-IO-04, step A4); Net +adapter; io_uring; Runtime; any build-file edit; `Threads::Threads` (D-W11-08: IO already uses +pthread calls without it; IOOnly consumer disables Threads lookup). + +## 4. Files to inspect +`include/Void/IO/{Types,Driver,Stream}.hpp`, `include/Void/IO/Detail/Backend.hpp`, +`src/IO/EpollDriver.cpp` (all), `include/Void/Async/{Operation,Executor,TaskScope}.hpp`, +`include/Void/Async/Detail/Types.hpp`, `tests/standalone/IO/IoDriver.cpp`, +`tests/package/InstalledComponents.cmake:74-80` (IOOnly flags), `src/IPC/Session.cpp:1118-1129`, +and the three design documents in §1. + +## 5. Write ownership and coordination +Write scope: `include/Void/IO/File.hpp` (NEW), `include/Void/IO/Driver.hpp`, `include/Void/IO/Types.hpp`, +`include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.hpp` (NEW), +`src/IO/FileWorkers.cpp` (NEW), `tests/standalone/IO/IoFile.cpp` (NEW). +Forbidden: all other paths, including `src/IO/module.cmake`, Async headers, Runtime, SystemAsync, +IPC, tests other than `IoFile.cpp`, build files, docs. Other workers may run concurrently in other +worktrees on Async files. No git commit/branch/stash/reset. + +## 6. Implementation or investigation approach +Order: (1) D1 fixes + regression test first; (2) poll-owner exclusion; (3) file pool + File API; +(4) bounded shutdown core + teardown; (5) remaining tests; (6) downstream builds. +MANDATORY invariants: +- D1: release the backend ref only if this call retired the op; cancel/expire paths skip retired + ops; epoll marks an op `in_execution` under `mu_` before its syscall and shutdown/cancel never + completes an op that is in execution (it records stop intent; the syscall's real result settles + it). NEW `duplicate_completions_ignored` counts suppressed double retirements. +- Poll owner: a dedicated `std::mutex poll_mu_`; `poll_once` first checks the thread-local + polling marker (reentrant call → `busy`), then `try_lock`; failure → `IoErrorCode::busy` + without touching any fd. Every turn drains cancels, control messages and file completions + BEFORE any stop-flag early return. While stopping (not yet shut down) a turn with no work waits + in `epoll_wait` up to `max_wait` (no spin). After shutdown completes `poll_once` returns 0 + without touching any fd. +- File workers (F1): a worker performs exactly one syscall (native or the injected shim — the + single documented exception allowed to run on workers; it must not call Driver/Executor/File + APIs), then pushes `{request, result}` onto the shared completion queue under the pool mutex and + wakes. Resume tickets are produced only by a poll turn via the existing + `complete_op_and_collect_tickets` path. `run_file_work(n)` runs syscalls on the caller and only + queues results. Workers hold `shared_ptr`, never the backend. + Thread-local `tl_io_worker_owner` set on workers; `is_io_worker_thread()` reads it. +- Admission: closed driver / stopped / expired → rejected before queueing; `max_file_queue` bounds + queued requests, `max_operations` bounds queued+active; either → `overloaded`; zero-length → + `{0,false}` without a syscall; offset+length overflow → `invalid_argument`. Files count against + `max_descriptors`. +- Ordering: writes and syncs on one file run in admission order, one active at a time; reads may + run concurrently. One syscall per request; EINTR retried; short transfer returns actual bytes; + 0-byte read of nonzero length = EOF. +- Queued stop/expiry: removed, completes `cancelled`/`timeout`; writes/syncs carry + `DomainOutcomeKind::not_committed`. Expiry checked by the driver clock in `poll_once` and again at + worker dequeue. +- Active stop/expiry: intent only; span/lease and telemetry retained; result = the syscall's actual + outcome. Sync success after stop = success; sync failure → `sync_failed` + native errno + + `DomainOutcomeKind::unknown`. +- `start_file_workers()` explicit, once; the `before_file_worker_start(index)` hook error or a + caught `std::system_error` joins already-started workers, returns `os_error` (system code when + present), and allows retry. +- File fd state (N4/F13): `detail::FileState` shared-owned, `enum {open, closing, closed}` under + the pool mutex; handle drop / in-flight / `close_pending` transitions under that mutex; exactly + one close enqueued (preallocated node inside `FileState`, reserved capacity bounded by + `max_descriptors`); close executes on a worker or in `run_file_work`. `~File` wakes only via a + weak→strong backend lock or the worker condvar, never a raw waker. Teardown closes remaining file + fds after joining workers and marks them `closed`; afterwards File ops return `closed` without a + syscall, `~File` does nothing, `close_and_join` returns success. `File::close_and_join(options)` + is always admitted; deadline/stop expiry → `incomplete_shutdown`, File stays valid with fd and + buffers retained; close syscall failure → `os_error`, fd treated as closed. +- Shutdown core (F9/N3): backend `begin_shutdown()` (idempotent: sets the stopping flag, closes + admission, cancels queued, stops active); `advance_shutdown(deadline, stop)` waits in ≤1 ms real + slices re-reading the injected clock, releases `poll_mu_` between slices, runs its own turns only + while holding poll ownership, wakes the current poller, returns the current + `DriverShutdownReport` with `complete=false` on deadline or stop (not an error), returns + `Async::make_async_error(AdmissionError::self_join)`-equivalent error if called on this backend's + worker or inside its poll turn; dispatches resume tickets only after releasing poll ownership + (P3-9). On completion: workers joined, op/descriptor fds closed, `wake_closed_` set (release). + 1.x `shutdown_and_join()` = `advance_shutdown(nullopt, {})` mapped to `Result`. +- F2: epoll fd and eventfd close only in `~EpollBackend`; `wake()` returns early if + `wake_closed_` (acquire). +- F1 teardown: `~EpollBackend`/`~MockBackend`/`~FileWorkers` never block; `~FileWorkers` finding + a joinable thread prints a one-line stderr diagnostic and `std::terminate`s. `Driver::~Driver` + calls `backend_->teardown_blocking()` (begin + advance to completion). `~Driver` on a file-worker + thread or inside a poll turn of that backend → stderr diagnostic + `std::terminate`. + + +### Amendments from W11-SPEC-REVIEW-1 (MANDATORY; override earlier text where they differ) +Source: `docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md` S1–S9 + P3 (decision D-042). +- S1 ownership handoff: before each slice `advance_shutdown` sets atomic `shutdown_waiting_` and + calls `wake()`. While it is set, `poll_once` on any other thread returns `busy` before `try_lock`, + touching no fd and not incrementing `turns`. It is cleared once `advance_shutdown` holds + `poll_mu_`. Between slices, after `advance_shutdown` releases `poll_mu_`, other pollers may run turns. +- S2 shutdown order (replaces the order implied above): (1) `begin_shutdown()` — `advance_shutdown` + calls it itself; (2) wait until no queued or active file request and no op `in_execution`; + (3) under `poll_mu_`, final drain of cancels, controls, file completions and close waiters; + (4) join workers; (5) still under `poll_mu_`, close remaining file fds (mark `closed`, complete + pending `close_and_join` waiters with success), then close op/descriptor fds; (6) set `shut_down_` + (release), then `wake_closed_`; (7) release `poll_mu_`, then dispatch tickets. `self_join` misuse + (`Async::make_async_error(Async::AdmissionError::self_join)`) is detected before any state change. + `begin_shutdown` only records intent and wakes the poller; it never completes or dispatches. + Document: the executor must outlive the Driver; an owned executor must not be joined before + Driver teardown (P3-9). +- S3 (replaces "Expiry checked ... again at worker dequeue"): expiry is checked with the driver + clock in `poll_once`; the epoll wait bound includes the earliest queued-file deadline. At dequeue a + worker checks, under the pool mutex and WITHOUT calling the clock, the request's stop flag and the + expired mark set by the last turn; such a request completes `cancelled`/`timeout` with no syscall. +- S4 observable contract: queued stop → `IoErrorCode::cancelled`, queued expiry → + `IoErrorCode::timeout` (kIoErrorDomain), zero shim calls, unchanged file bytes; sync failure → + `IoErrorCode::sync_failed` with `system_code() == std::error_code{errno, std::generic_category()}`. + Internally settle with `try_commit_error(err, not_committed|unknown)`; tests do not assert the + outcome kind. Retirement uses a retire-once path equivalent to `complete_op_and_collect_tickets`, + generalized for `OperationState` and the file outcome kinds. +- S5 slots: a File occupies a `DescriptorSlot`, counts in `active_descriptors_`, bounded by + `max_descriptors`; `File::id()` is that slot's `DescriptorId`. The slot has `fd = -1` and a + file-kind flag; socket paths (interest updates, `close_fd` controls, stale-event checks, shutdown + sweep) skip it. The file fd lives only in `FileState`. +- S6 lifetimes: `FileState` holds `shared_ptr` and `weak_ptr`, + never raw pool/backend pointers. The raw-context waker is called only by workers, which are joined + before the backend is destroyed. +- S7 stop flag: `request_stop()` == `begin_shutdown()`, with idempotence on a separate + `shutdown_begun_` flag. On mock, requests held by a token never block `advance_shutdown`; + `finish_*` still completes them, and `teardown_blocking` completes any still held with + `IoErrorCode::closed`. +- S8 D1 counter: increment `duplicate_completions_ignored` each time a cancel, expiry or shutdown + path meets an already-retired op and skips it. Retired ops are not purged from the cancel queue + early. A turn's first `clock_.now()` comes after the start-of-turn cancel/control/file drain; the + queued-file expiry scan reads the clock only when queued file requests have deadlines. +- S9 (D-042): B2 owns and tests the public wrappers `begin_shutdown`, `shutdown(options)`, + `quiescent`, `shutdown_complete` (inline in `Driver.hpp`). A4 adds only `run()`, `Pump.hpp`, + SystemAsync conformance and its tests. +- P3 clarifications: busy only if the polling marker equals THIS backend (save/restore it for nested + turns of other drivers); mock `poll_once` still ignores `max_wait`; the only worker-side Driver call + is detected (`shutdown_and_join`/`shutdown` → `self_join`); closed → `closed`, stop → `cancelled`, + expired → `timeout` (as `submit_io`); `offset > OFF_MAX` or `offset+len > OFF_MAX` → + `invalid_argument`; file requests count in the shared `active_operations_` until poll-turn + retirement; reads are unordered relative to writes; a second `start_file_workers` → + `invalid_argument`, `file_workers == 0` → success with no threads, after shutdown begins → + `closed`, `run_file_work` while workers run → `busy`; `close_and_join` waits for (does not cancel) + the file's queued/active requests, success invalidates the File, after an expired call the File is + `valid()` but closing (new ops → `closed`, a repeat call waits); document the difference from + `ByteStream::close_and_join`; `read_exact_at`/`write_all_at` mirror `Stream.hpp` composed transfers + with the offset advancing and one deadline, a 0-byte pwrite with bytes remaining is an error (no + loop); open flags: RDWR/WRONLY/RDONLY, neither read nor write → `invalid_argument`, `truncate` + requires write, `exclusive` requires create, always `O_CLOEXEC`, runs on the caller's thread; + `adopt_file_fd` takes ownership only on success; the injected shim must outlive Driver teardown. +- Test file includes: `IoFile.cpp` may include only Void/{IO, Async, Time, Memory, Functional, Core, + Testing} headers (otherwise it is silently skipped); write a local temp-dir helper. + +## 7. Interfaces and data contracts +```cpp +namespace Void::IO { // File.hpp (NEW) +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: File() noexcept; File(File&&) noexcept; File& operator=(File&&) noexcept; ~File(); + [[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 = {}); +} +// Driver.hpp additions +[[nodiscard]] Void::Result::Result Driver::open_file(const std::filesystem::path&, FileOpenOptions = {}); +[[nodiscard]] Void::Result::Result Driver::adopt_file_fd(int fd); +[[nodiscard]] Void::Result::Result Driver::start_file_workers(); +[[nodiscard]] Void::Result::Result Driver::run_file_work(std::size_t max_requests = 1); +[[nodiscard]] bool Void::IO::is_io_worker_thread() noexcept; +void Driver::begin_shutdown() noexcept; // -> backend_->begin_shutdown() +[[nodiscard]] Void::Result::Result Driver::shutdown(Async::OperationOptions); // -> advance_shutdown(o.deadline, o.stop) +[[nodiscard]] bool Driver::quiescent() const noexcept; +[[nodiscard]] bool Driver::shutdown_complete() const noexcept; +// Types.hpp additions +struct DriverShutdownReport { bool complete{false}; std::size_t pending_operations{0}, + active_file_requests{0}, open_descriptors{0}, retained_buffer_bytes{0}; }; +// BackendOptions (append): FileSyscalls* file_syscalls{nullptr}; +// std::function(std::size_t)> before_file_worker_start{}; +// DriverTelemetry (append): queued_file_requests, active_file_requests, file_workers_running, +// duplicate_completions_ignored (std::size_t / std::uint64_t as fits existing fields) +// detail::DriverBackend (append, pure virtual or with base impl): +virtual void begin_shutdown() noexcept; +[[nodiscard]] virtual Void::Result::Result advance_shutdown( + std::optional deadline, std::stop_token stop); +[[nodiscard]] virtual bool shutdown_complete() const noexcept; +[[nodiscard]] virtual bool quiescent() const noexcept; +virtual void teardown_blocking() noexcept; +``` +`ComposedTransferError`, `Transfer`, `DescriptorId`, `BufferLease` are existing IO types — reuse. +Use existing namespace aliases/spellings for `Coro::Task` and `Void::Result::Result` as in `Stream.hpp`. +Unchanged 1.x: every existing `Driver`/`ByteStream`/`BufferLease` signature and the IoDriver tests. + +## 8. Dependencies and integration +Upstream: S-IO-01/02 (done), root prep `7f95f89` (`sync_failed`). Downstream: S-IO-04 (A4) adds +public wrappers over your backend primitives (gate G4); S-RUNTIME-02 (B3) uses +`start_file_workers`, `is_io_worker_thread`. Keep §7 exactly. Root integrates and commits. + +## 9. Edge cases security and performance +fd reuse after close during concurrent poll; buffer retention on active timeout; `open_file` uses +`O_CLOEXEC` with ordinary `open(2)` path semantics (no new symlink policy); EINTR; ENOSPC/EIO surfaced as `os_error`; partial start; teardown with +stalled worker (shim gated by a latch); no busy loops; no allocation in `~File`; TSan-clean. + +## 10. Acceptance criteria +`IoFile.cpp` (isolated temp dir per test, no fixed paths): `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_file_workers_partial_start_failure_joins_started`, `io_file_drop_with_inflight_defers_close_until_drained`, +`io_file_close_and_join_expiry_incomplete_retains_then_completes`, `io_file_ops_after_teardown_closed_no_syscall`, +`io_driver_destroyed_from_coroutine_resumed_after_poll_dispatch_same_thread`, +`io_worker_thread_marker_only_on_file_workers`, `io_concurrent_poll_once_second_caller_busy_no_fd_touch_tsan`, +`io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan`, `io_stop_after_completion_releases_backend_ref_once`, +`io_epoll_stop_requested_at_deadline_scan_completes_once` (D1 seam: clock armed after submission, +asserts single delivery and `duplicate_completions_ignored >= 1`), `io_file_eintr_retried_via_shim`, +`io_file_zero_length_overflow_and_zero_queue_limit`, `io_file_counts_against_max_descriptors`, +`io_file_workers_second_start_invalid`, `io_poll_once_after_shutdown_returns_zero`, +`io_poll_once_reentrant_inline_resume_busy`, `io_shutdown_bounded_deadline_incomplete_then_complete`, +`io_shutdown_stop_token_returns_incomplete_report`, `io_request_stop_then_shutdown_cancels_queued_files`, +`io_mock_held_request_does_not_block_teardown`. All pass; existing `IoDriver` tests +pass unchanged; downstream suites pass unfiltered; `-Werror`, TSan 0 races, ASan+UBSan 0 errors. + +## 11. Verification commands and evidence +Cwd = worktree root; run `dev` with the sandbox disabled. Confirm new suites appear in output. +```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 --parallel 8 && /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 --parallel 8 && /tmp/void-w11-io3-tsan/tests/VoidTests --filter "^(IoFile|IoDriver)\."' +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-asan --parallel 8 && /tmp/void-w11-io3-asan/tests/VoidTests --filter "^(IoFile|IoDriver)\."' +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-users -G Ninja -DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;CryptoAsync;Runtime;ConfigurationAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-users --parallel 8 && /tmp/void-w11-io3-users/tests/VoidTests && ctest --test-dir /tmp/void-w11-io3-users --output-on-failure --timeout 180' +``` +Warnings check (VOID_WARNINGS_AS_ERRORS does not reach VoidTests TUs, X-QA-01): +```sh +dev cpp-gcc -c bash -lc 'g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/IO/IoFile.cpp && for h in File Driver Types; do echo "#include " | g++ -std=c++26 -freflection -x c++ -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers - || exit 1; done' +``` +CryptoAsync may need `-p openssl` on the `dev` line (`dev cpp-gcc -p openssl -c ...`); report the +exact command used. + +## 12. Constraints and stop conditions +No edits outside write scope; no weakened assertions; no disabled warnings; no Threads link. Stop +and report BLOCKED if: a forbidden file must change; a downstream suite fails for reasons rooted in +the new blocking `shutdown_and_join` semantics that need a consumer edit; any D1 fix cannot be made +without changing a public 1.x signature; or two repair attempts at the same failing check fail. + +## 13. Authorization and decisions +Root decisions D-034, D-038, D-040 under user decisions D-027/D-029/D-031. Listed files only; no +commits, pushes or other side effects. + +## 14. Return format +Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations (esp. any choice the +design docs left to you); evidence per acceptance criterion; commands with cwd/results (test counts, +TSan/ASan); checks not run; residual risks; integration notes (worktree path, primitives A4 should +wrap). Do not spawn children. diff --git a/docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md b/docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md new file mode 100644 index 0000000..6654695 --- /dev/null +++ b/docs/agent-workflow/tasks/W11-SPEC-REVIEW-1-OUTPUT.md @@ -0,0 +1,186 @@ +# W11-SPEC-REVIEW-1 output (opus-reviewer, 2026-11-29) + +Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`. + +**Task W11-SPEC-REVIEW-1. Verdict: S-IO-03 is CHANGES_REQUIRED and M-ASYNC-04 is CHANGES_REQUIRED.** + +There are no P0 or P1 findings. Every fix below is added spec text. None needs a re-plan, a change to ownership or reopening a D-W11 decision. Each finding says whether I saw it in the text and code ("observed") or worked out an interleaving ("inferred"). + +- **Blocks dispatch:** S-IO-03 S1–S8, plus a root decision on S9. M-ASYNC-04 A1–A3. +- **Editorial:** all P3 items. They are clarifications and can be folded into the same edit. + +Spec line numbers refer to `docs/agent-workflow/tasks/S-IO-03.md` and `docs/agent-workflow/tasks/M-ASYNC-04.md` as they are now. + +## S-IO-03 (B2): CHANGES_REQUIRED + +**S1 (P2, inferred): shutdown can be starved by a concurrent poller (§6 l.86-91, l.124-131).** +- **Text:** + - The spec requires a `std::mutex` acquired with `try_lock` (l.86-87). + - While stopping, a turn with no work holds ownership inside `epoll_wait` for up to `max_wait` (l.89-90). + - `advance_shutdown` takes ownership only between slices of at most 1 ms (l.125-127), and it must own the poll to close fds (l.131). +- **Effect:** a poller loop re-locks within nanoseconds after each `wake()`, so `try_lock` almost never wins. The mandatory test `io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan` (l.211) and a cross-thread 1.x `shutdown_and_join` can stall for seconds or hang. +- **Append to Shutdown core:** "Ownership handoff: before each slice `advance_shutdown` sets atomic `shutdown_waiting_` and calls `wake()`. While it is set, `poll_once` on any other thread returns `busy` before `try_lock`, touching no fd and not incrementing `turns`. It is cleared once `advance_shutdown` holds `poll_mu_`. Between slices, after `advance_shutdown` releases `poll_mu_`, other pollers may run turns (R2 N3)." + +**S2 (P2, observed omission): completion order, final drain and fd-close ownership are unstated (l.124-132).** +- REV1 F2 says shutdown closes operation and descriptor fds "only after it holds poll ownership" (W11-PLAN-REV1-OUTPUT.md:43). That sentence is missing from the spec. +- The step order is not given. Inferred consequence: a completion pushed after the last drain is stranded, because after shutdown `poll_once` no longer touches anything. +- **Replace l.131-132 with:** "Order: (1) `begin_shutdown()`. `advance_shutdown` calls it itself, because A4's `shutdown(options)` wraps only `advance_shutdown`. (2) Wait until no queued or active file request and no op `in_execution`. (3) Under `poll_mu_`, run a final drain of cancels, controls, file completions and close waiters. (4) Join workers. (5) Still under `poll_mu_`, close the remaining file fds (mark them `closed` and complete pending `close_and_join` waiters with success), then close op and descriptor fds. (6) Set `shut_down_` (release), then `wake_closed_`. (7) Release `poll_mu_`, then dispatch the tickets (P3-9). `self_join` misuse is detected before any state change. `begin_shutdown` only records intent and wakes the poller; it never completes or dispatches anything (F1(a))." + +**S3 (P2, observed contradiction): l.107-108 has workers re-check expiry with the driver clock at dequeue.** +- That conflicts with l.92-94, with D-038 ("file workers never call … user code except the injected syscall shim") and with IO.md:95-96. `MonotonicClock::now()` is injected user code. The D1 seam clock even requests stop from inside `now()`. +- **Replace l.107-108 with:** "Expiry is checked with the driver clock in `poll_once`. The epoll wait bound includes the earliest queued-file deadline. At dequeue, a worker checks under the pool mutex, without calling the clock, the request's stop flag and the expired mark set by the last turn. Such a request completes `cancelled`/`timeout` with no syscall." +- If the root prefers to keep the worker clock read, declare the clock a second documented exception that must be thread-safe. `ManualClock` is atomic (`Clock.hpp:129`). + +**S4 (P2, observed; the tests cannot assert what they are named for): `DomainOutcomeKind` is not observable.** +- `File` returns `Result<…>`, and `Error` carries only status and `system_code()` (`Functional/Error.hpp:136-235`). So `io_file_queued_cancel_not_committed_zero_effects` and `…sync_failed_unknown_errno` (l.202-205) cannot assert `not_committed` or `unknown`. +- Also, "via the existing `complete_op_and_collect_tickets` path" (l.95-96) cannot work as is. That function is typed for `Transfer` and hard-codes `cancelled`/`failed` (`EpollDriver.cpp:421-447`). +- **Add to §6:** "Observable contract: + - Queued stop gives `IoErrorCode::cancelled`; queued expiry gives `IoErrorCode::timeout` (both kIoErrorDomain), with zero shim calls and unchanged file bytes. + - Sync failure gives `IoErrorCode::sync_failed` with `system_code()==std::error_code{errno, std::generic_category()}`, matching `errno_code`. + - Internally, settle with `try_commit_error(err, not_committed|unknown)`. `Result` does not expose that kind and tests do not assert it. + - Retirement uses a retire-once path equivalent to `complete_op_and_collect_tickets`, generalized for `OperationState` and the file outcome kinds." + +**S5 (P2, observed omission plus inferred double close): it is unspecified whether files use the socket slot table (l.101-102, l.115-118).** +- The shutdown sweep calls `release_slot_locked(idx, true)` on every in-use slot (`EpollDriver.cpp:1209-1223`), and that closes `slot.fd` (`:362-363`). If an implementer stores the file fd in a slot, the fd gets closed twice. +- **Add:** "A File occupies a `DescriptorSlot`. It counts in `active_descriptors_`, is bounded by `max_descriptors`, and `File::id()` is that slot's `DescriptorId`. The slot has `fd = -1` and a file-kind flag, and socket paths (interest updates, `close_fd` controls, stale-event checks, the shutdown sweep) skip it. The file fd lives only in `FileState`." + +**S6 (P2, inferred use-after-free): `~File` after `~Driver` must lock the pool mutex (l.115-123).** +- **Add:** "`FileState` holds `shared_ptr` and `weak_ptr`, never raw pool or backend pointers. The raw-context waker is called only by workers, which are joined before the backend is destroyed." + +**S7 (P2, observed plus inferred hang): stop flag and mock held tokens.** +- **Shared stop flag:** `request_stop()` already sets `stopping_` (`EpollDriver.cpp:282-286`). If `begin_shutdown`'s idempotence is keyed on that flag (l.124-125), a prior `request_stop()` makes it a no-op. Queued file requests are then never cancelled, and with manual stepping `~Driver` hangs. +- **Mock held tokens:** 1.x mock shutdown skips held requests (`:847-851`). The `MockController` dies with the `Driver`, so if teardown waits for those requests it deadlocks. +- **Add:** "`request_stop()` == `begin_shutdown()`, with idempotence on a separate `shutdown_begun_` flag. On mock, requests held by a token never block `advance_shutdown`; `finish_*` still completes them, and `teardown_blocking` completes any still held with `IoErrorCode::closed`." + +**S8 (P2, observed ambiguity): the D1 seam test (l.212-213) can fail even with a correct fix.** +- An implementation that purges retired ops from `cancel_queue_`, or that reads the clock before the start-of-turn drain, leaves `duplicate_completions_ignored == 0`. +- **Add to the D1 bullet (l.82-85):** "Increment `duplicate_completions_ignored` each time a cancel, expiry or shutdown path meets an already-retired op and skips it. Retired ops are not purged from the cancel queue early. A turn's first `clock_.now()` comes after the start-of-turn cancel/control/file drain; the queued-file expiry scan reads the clock only when queued file requests have deadlines." + +**S9 (P2, observed verification gap; needs a root decision): B2 cannot test the bounded primitive it owns.** +- `advance_shutdown`'s deadline, stop, report and slice-release behaviour is reachable only as `advance_shutdown(nullopt, {})`, through `shutdown_and_join` and `~Driver` (`Driver.hpp:98-104`, `backend_` is private). +- A4 may not edit `EpollDriver.cpp` (REV1:340, G6). A defect found in A4 therefore bounces back to the root. +- **Choose one and write it into §10/§14:** + - (a) Add a NEW test-only accessor in the `MockController` style. + - (b) "B2 lists the unexercised primitive paths. A4's IoShutdown tests are the G4 acceptance gate before B2 is VERIFIED, and fixes found there are root-owned." + +**P3 (editorial):** +- **l.20-21:** fix the line citations. `StreamState`'s `weak_ptr` is at `Backend.hpp:80-116` (the file has 118 lines). The stop-forwarder lock is at `EpollDriver.cpp:589-596`. +- **l.86-88:** "`busy` only if the marker equals this backend; save and restore it for nested turns of other drivers." + - Give the busy test a deterministic hold point: the first poller is parked in a long `epoll_wait` after `turns` has incremented. + - Add a test `io_poll_once_reentrant_inline_resume_busy`, using an executor whose `post_completion` resumes inline. +- **l.89-90:** append "mock `poll_once` still ignores `max_wait` (REV1 P3)". +- **l.92-94:** carve-out: "a Driver API called from a worker is detected (`shutdown_and_join` → `self_join`). This is the only worker-side Driver call, used by `io_file_shutdown_from_worker_self_join`." +- **l.99-102:** + - Error codes: closed → `closed`, stop → `cancelled`, expired → `timeout` (as `submit_io`, `:495-506`). + - Overflow: `offset > OFF_MAX` or `offset+len > OFF_MAX` → `invalid_argument`. + - Counting: file requests count in the shared `active_operations_` until poll-turn retirement. +- **l.103-105:** "reads are unordered relative to writes". +- **l.112-114:** + - A second `start_file_workers` → `invalid_argument`. + - `file_workers==0` → success with no threads. + - After shutdown begins → `closed`. + - `run_file_work` while workers run → `busy`. +- **l.115-123:** + - `close_and_join` waits for (and does not cancel) the file's queued and active requests. Success invalidates the File. + - After an expired call, the File is `valid()` but closing. New ops return `closed`, and a repeat call waits. + - Document the difference from `ByteStream::close_and_join` (`Stream.hpp:102-120`) (F13). +- **l.128:** say exactly `Async::make_async_error(Async::AdmissionError::self_join)`. +- **l.131:** add the P3-9 documentation requirement: "the executor must outlive the Driver; an owned executor must not be joined before Driver teardown." +- **l.161-162:** `read_exact_at`/`write_all_at` mirror `Stream.hpp:126-180` with the offset advancing and one deadline. A 0-byte pwrite with bytes remaining returns an error; it must not loop. +- **l.165-166:** + - Flag map: RDWR/WRONLY/RDONLY; neither read nor write → `invalid_argument`; `truncate` requires write; `exclusive` requires create; always `O_CLOEXEC`; runs on the caller's thread. + - `adopt_file_fd` takes ownership only on success. +- **l.173:** the shim must outlive Driver teardown. +- **§10:** add tests for EINTR via the shim, zero-length/overflow/`max_file_queue==0`, files counting against `max_descriptors`, a second start, and `poll_once` after shutdown returning 0. +- **§5/§10:** `IoFile.cpp` may include only Void/{IO, Async, Time, Memory, Functional, Core, Testing} headers, or it is silently skipped (`tests/CMakeLists.txt:12-41`). `ScopedTempDir` is local to the CryptoAsync test file. + +## M-ASYNC-04 (A2): CHANGES_REQUIRED + +**A1 (P2, observed): "`-Werror` clean" is never actually checked (l.174, §11).** +- The warning flags are `PRIVATE` and apply only to modules that have `.cpp` sources (`cmake/Module.cmake:176-178`). `src/Async` holds only `module.cmake`. +- `VoidTests` gets no `-W` flags (`tests/CMakeLists.txt:113-123`; `cmake/VoidTesting.cmake` sets no compile options). +- Sanitizers do reach the tests: they are `PUBLIC` through `Void::Testing` (`Module.cmake:184-209`), so the TSan and ASan runs are valid. +- **Add to §11** (and to S-IO-03 for `IoFile.cpp`, optionally): + + ```sh + dev cpp-gcc -c bash -lc 'for f in ThreadExecutor FuturePool AsyncChannel ParallelForBounded; do g++ -std=c++26 -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Async/$f.cpp || exit 1; done' + ``` + + Add `-freflection` on GCC 16 or later, as `CMakeLists.txt:24-26` does. + +**A2 (P2, inferred hang): `join()` and the destructor when no worker is running (l.61-71).** +- If work is queued before `start()`, or after a failed `start()`, then `~ThreadExecutor` → `join()` waits for workers that do not exist. +- **Add:** "Admission before `start()` queues normally. When no worker is running, `join()` and the destructor drain both lanes inline on the caller under `ExecutorThreadGuard` (counted as `inline_after_join`) and never wait. `start()` after `close()` or after a successful `start()` → `invalid_argument`. After a failed `start()` it may be retried." + +**A3 (P2, inferred race): a reservation outstanding across `close()`/`join()`.** +- `TaskScope` reserves and commits in separate steps (`TaskScope.hpp:679-732`), and FuturePool will do the same. +- **Add:** "A reserved slot counts in `admitted()` and in the bound. `try_reserve_slot` after `close()` → `stopped`. A reservation taken before `close()` stays binding: `commit_reserved` after `close()` enqueues normally. `join()` also waits until no reservation is outstanding." + +**P3 (editorial):** +- **l.125:** must be `inline` (Async is header-only, so the ODR applies): `[[nodiscard]] inline Void::Result::Error make_async_error(ChannelError, std::string message = {});` +- **l.75-84 (AsyncChannel):** + - Deadlines and timers: + - Deadlines are judged by `timers->clock()`. + - Check stop, then deadline, then "deadline without timers" → `invalid_argument`, before any state change. The value is returned in `SendFailure`. + - `TimerEvent::closed` → `cancelled` (REV1 F12; today only a test name implies it). + - `schedule_at` failure: `overloaded` → `ChannelError::overloaded`, `stopped` → `cancelled`. + - Waiters and lifetime: + - `max_waiters` applies per direction; 0 → `invalid_argument`. + - Frames hold `shared_from_this()`. + - Never construct or destroy a `std::stop_callback` while holding the channel mutex. + - Destroying a suspended Task is a caller error. + - The resume executor must outlive every pending resume. + - FIFO means per-producer order. +- **l.85-90 (parallel_for):** + - At most `max_concurrency` chunks run at once, counting the caller when it runs chunks inline. + - `Kind::rejected` is not produced in this wave. + - Precedence: `invalid_argument` > `failed` > `stopped`. + - `first >= last` → success. + - Compute the range in the unsigned type of `I`. +- **ThreadExecutor:** `idle()`/`stats()` are snapshots. The switch to inline mode happens under the executor mutex. `admitted()` = queued + running + reserved. +- **FuturePool:** if creating the frame throws, release the slot and rethrow. +- **§12:** stop if `Async/Timer.hpp` is missing or differs from M-TIME-03 §7. +- **l.16:** `ExecutorThreadGuard` is at `Executor.hpp:32-51`. + +## R2 and carry-over coverage + +| Spec | Item | Status | +| --- | --- | --- | +| S-IO-03 | N3 | Partial. All B2 bullets are present; the owned-executor documentation and handoff liveness are missing (S1, P3). | +| S-IO-03 | N4 | Yes, l.115-123. S5 and S6 are needed to implement it without guessing. | +| S-IO-03 | P3-5 | Yes, l.212-213, but see S8. | +| S-IO-03 | P3-9 | Partial. Dispatch after release is there; the documentation is missing. | +| S-IO-03 | F1 | Yes, but contradicted by l.107-108 (S3). | +| S-IO-03 | F2 | Partial: fd close under poll ownership is missing (S2). | +| S-IO-03 | F9 | Yes, except that `advance_shutdown` must begin shutdown implicitly (S2). | +| S-IO-03 | F11 | Yes. | +| S-IO-03 | F13 | Yes, except "success invalidates the File" and the ByteStream note (P3). | +| M-ASYNC-04 | N5 | Yes, l.80-82. | +| M-ASYNC-04 | F7 | Yes. | +| M-ASYNC-04 | F11 | Yes. | +| M-ASYNC-04 | F12 | Yes, except `TimerEvent::closed`→`cancelled` is implicit (P3). | +| M-ASYNC-04 | REV1 P3 ThreadExecutor, `idle()` | Yes. | + +## Write scope + +The two specs' write sets are disjoint. Neither touches `Timer.hpp` (B1), Functional (A1) or Runtime (B3). + +- **Driver.hpp:** it passes from B2 to A4 in sequence at G4 (REV1:339-340), so there is no concurrent ownership. +- **No build edits needed:** `src/IO/FileWorkers.cpp` is picked up by the source glob (`Module.cmake:14`), so `module.cmake` needs no edit. `File.hpp` becomes a public header through the header glob. +- **Commands select the new tests:** the module closures cover the includes, and the filters match the file stems (`Runner.cpp:205-225`), including `TimerQueue` (M-TIME-03.md:34). + +## Checks executed and not run + +- **Executed:** read-only reads of: + - both specs, R2, REV1, the PLAN §§ for these tasks, PREFLIGHT-2, `IO.md`, `Async.md`; + - all of `EpollDriver.cpp`, the IO headers, `Executor.hpp`, `Operation.hpp`, `Detail/Types.hpp`; + - `TaskScope.hpp` (parts), `ThreadPool.hpp`, `ParallelFor.hpp`; + - the cmake files and `tests/CMakeLists.txt`, the IoDriver tests and consumer tests; + - M-TIME-03.md §§6-10 and DECISIONS D-034/038/040. +- **Not run:** no builds, tests or compile probes. + - `Timer.hpp` is not in the main checkout, so I checked it against M-TIME-03.md §7 only. + - S-IO-04 and S-RUNTIME-02 specs do not exist yet, so disjointness was checked against PLAN §3 and the REV1 ownership tables. + - No Serena or codebase-memory coverage checks; the hooks reported partial indexing, so I read the source directly. +- **Residual for the A4 spec:** R2 N3 loops must exit on `shutdown_complete()`, but F9's public wrapper list has no public `Driver::shutdown_complete()`. + +**Re-review scope:** only the amended text for S1–S9 and A1–A3. diff --git a/docs/agent-workflow/tasks/W11-SPEC-REVIEW-1.md b/docs/agent-workflow/tasks/W11-SPEC-REVIEW-1.md new file mode 100644 index 0000000..7cf6b0c --- /dev/null +++ b/docs/agent-workflow/tasks/W11-SPEC-REVIEW-1.md @@ -0,0 +1,69 @@ +# Wave 11 spec review: S-IO-03 (B2) and M-ASYNC-04 (A2) against contract R2 + +Task ID: W11-SPEC-REVIEW-1 +Role: opus-reviewer +Status: READY + +## 1. Context and baseline +- Repo `/home/faumaray/Projects/VoidLibrary`, branch `feat/roadmap-p2-wave11`, HEAD `99203ce` + (prep `7f95f89`, docs `a8a9249`, R2 `99203ce`) on `main` `38436b1`. Untracked user files are not inputs. +- PREFLIGHT-2 (`docs/agent-workflow/tasks/W11-PREFLIGHT-2-OUTPUT.md`) said the R2 amendment can be + re-reviewed on the task specs. Root wrote `docs/agent-workflow/tasks/W11-CONTRACT-R2.md` and draft + specs `docs/agent-workflow/tasks/S-IO-03.md` and `docs/agent-workflow/tasks/M-ASYNC-04.md`. +- Design chain: `W11-PLAN-OUTPUT.md` → `W11-PLAN-REV1-OUTPUT.md` → `W11-CONTRACT-R2.md` (R2 wins). + +## 2. Objective and deliverables +Verdict per spec (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE): is each spec complete, +internally consistent, faithful to PLAN+REV1+R2, implementable without guessing, with acceptance +tests covering the roadmap row and every mandatory invariant? Findings P0–P3 with exact spec line +and the replacement text you recommend. + +## 3. Scope and non-goals +In: the two specs, R2 items N3, N4, N5, P3-5, P3-9 as reflected in them, F1/F2/F7/F9/F11/F12/F13 +carry-over, verification commands (module lists, filters, sanitizer flags), write-scope +disjointness between the two specs and versus S-IO-04/S-RUNTIME-02 later steps. +Out: re-litigating accepted decisions D-W11-01..15; other specs. + +## 4. Files to inspect +The two specs, `W11-CONTRACT-R2.md`, `W11-PLAN-REV1-OUTPUT.md`, `W11-PLAN-OUTPUT.md`, +`docs/roadmap/subsystems/IO.md`, `docs/roadmap/modules/Async.md`, and source they cite +(`src/IO/EpollDriver.cpp`, `include/Void/IO/*`, `include/Void/Async/*`, `cmake/Module.cmake:14`, +`CMakeLists.txt:13-15`, `tests/CMakeLists.txt`). + +## 5. Write ownership and coordination +Write scope: none +Allowed: read-only `git`, `rg`, `sed -n`, Serena/codebase-memory reads. Two implementers (M-FUNCTIONAL-03, +M-TIME-03) run in separate worktrees; ignore them. + +## 6. Implementation or investigation approach +1. Diff each spec's mandatory list against PLAN/REV1/R2; list omissions or contradictions. +2. Check every signature is consistent with existing types it names (`ComposedTransferError`, + `Transfer`, `DescriptorId`, `BufferLease`, `Coro::Task`, `Void::Result::Result`, `ThreadPool`). +3. Check acceptance tests are deterministic and map to invariants; flag untestable ones. +4. Check commands will actually select the new tests (module closure; silent skip rule). + +## 7. Interfaces and data contracts +Not applicable for authorship: review signatures written in the specs. + +## 8. Dependencies and integration +Root will fix the specs from your findings, set Status READY, lint, and dispatch. + +## 9. Edge cases security and performance +As listed in the specs §9; flag any missing hazard from PREFLIGHT-1/2. + +## 10. Acceptance criteria +1. Verdict per spec. 2. Findings with spec line + replacement text. 3. Explicit statement whether +each R2 item relevant to the spec is fully reflected. + +## 11. Verification commands and evidence +Read-only, e.g. `rg -n "ComposedTransferError|struct Transfer|DescriptorId" include/Void/IO`. + +## 12. Constraints and stop conditions +No edits, commits, network or spawning. INSUFFICIENT_EVIDENCE rather than guess. + +## 13. Authorization and decisions +Root decisions D-034, D-038, D-040. Technical check only. + +## 14. Return format +Task ID; verdict per spec; findings P0→P3 with replacement text; R2 coverage statement; checks not +run. Compact.