Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ea63844f0 | ||
|
|
99a1100bb1 | ||
|
|
95785ed47a | ||
|
|
c6789e7dbf | ||
|
|
26edf653e3 | ||
|
|
99203ce1f3 |
No files matched your search
@@ -89,3 +89,6 @@ execution without pausing between waves). They are not new user approvals.
|
||||
| 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 |
|
||||
| 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 <stated HEAD>` (X-WF-01). | C-03–C-06; D-038, D-040 |
|
||||
@@ -363,6 +363,24 @@ while leaving local untracked files untouched.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w10-asan`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB.
|
||||
- Debug TSan (`/tmp/void-w10-tsan`, `Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`, 23 modules, `-Werror`): `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings.
|
||||
|
||||
### Wave 11 — Execution-path backfill (`feat/roadmap-p2-wave11`, in progress)
|
||||
|
||||
Checkpoint 2026-11-29 (branch pushed to `origin/feat/roadmap-p2-wave11`; `main` untouched at `38436b1`):
|
||||
- Baseline `38436b1` full RelWithDebInfo `-Werror` (`/tmp/void-w11-base`, 55 modules): 1,484 tests
|
||||
(1,480 ✔, 4 ⊘), `ctest` 2/2.
|
||||
- Planning: `tasks/W11-PLAN-OUTPUT.md` → PREFLIGHT 1 (CHANGES_REQUIRED, F1 P1 + F2–F13) →
|
||||
`tasks/W11-PLAN-REV1-OUTPUT.md` → PREFLIGHT 2 (CHANGES_REQUIRED, N1–N6) → `tasks/W11-CONTRACT-R2.md`
|
||||
→ spec review (S1–S9, A1–A3) adopted into specs (D-038, D-040, D-042).
|
||||
- Commits: `7f95f89` prep (error codes, area plans), `a8a9249`/`99203ce`/`c6789e7` docs/specs,
|
||||
`26edf65` M-FUNCTIONAL-03 (VERIFIED).
|
||||
- In flight: M-TIME-03 B1 TimerQueue diff applied UNCOMMITTED in the main checkout (root-verified:
|
||||
681 tests 678 ✔ 3 ⊘, TSan 28/28 ×3, ASan 468 ✔; fresh review pending); S-IO-03 (B2) implementer
|
||||
in an agent worktree. Specs ready: M-ASYNC-04 (A2, after B1 commit), M-TIME-03-B1b (`retry_async`,
|
||||
after B1 commit), M-ASYNC-05 (A3, after A2). Still to specify: S-IO-04 (A4), S-RUNTIME-02 (B3),
|
||||
S-RUNTIME-03 (B4).
|
||||
- Dispatch rule (X-WF-01): agent worktrees start at `main`; each prompt fast-forwards to the stated HEAD.
|
||||
- Note: a 5-hour usage limit interrupted two agents once; they were resumed with SendMessage.
|
||||
|
||||
## Ownership and next step
|
||||
|
||||
Waves 1–10 (`P0`, `P1` except `M-FUNCTIONAL-03`/`M-TIME-03`, the P2 operations/storage/
|
||||
|
||||
@@ -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) | [spec](tasks/M-TIME-03.md), [B1b](tasks/M-TIME-03-B1b.md) | B1 VERIFIED; B1b IN PROGRESS | B1: review W11-REVIEW-B1 F1–F3 fixed by root; Runtime;SystemAsync;ResilienceAsync 681 (678 ✔, 3 ⊘), TSan 28/28 ×3, ASan 468 ✔, post-fix 18/18 + TSan 15/15 |
|
||||
| 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 |
|
||||
@@ -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<Void::Result::Result<void>(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<std::unique_ptr<ThreadExecutor>> create(ThreadExecutorOptions = {});
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
void post(std::coroutine_handle<>) override;
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_post(std::coroutine_handle<>) override;
|
||||
void post_completion(std::coroutine_handle<>) override;
|
||||
[[nodiscard]] bool supports_reservation() const noexcept override;
|
||||
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override;
|
||||
void commit_reserved(std::coroutine_handle<>) override; void release_reserved() noexcept override;
|
||||
[[nodiscard]] bool has_background_workers() const noexcept override;
|
||||
void close() noexcept; [[nodiscard]] Void::Result::Result<void> 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 <std::invocable F> [[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, 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 <class T> struct SendFailure { ChannelError error; T value; };
|
||||
template <class T> class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>> { public:
|
||||
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>> create(Executor& resume, ChannelOptions = {});
|
||||
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T);
|
||||
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>> send(T, OperationOptions = {});
|
||||
[[nodiscard]] std::expected<T, ChannelError> try_receive();
|
||||
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>> receive(OperationOptions = {});
|
||||
void close() noexcept; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool is_closed() const; };
|
||||
[[nodiscard]] 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<std::size_t> first_failed_chunk{}; std::exception_ptr first_exception{}; };
|
||||
template <std::integral I, std::invocable<I> F>
|
||||
[[nodiscard]] std::expected<void, ParallelForError> parallel_for(I first, I last, F&& f, ThreadPool&, ParallelForOptions);
|
||||
}
|
||||
```
|
||||
`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.
|
||||
@@ -0,0 +1,151 @@
|
||||
# M-ASYNC-05 — EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling
|
||||
|
||||
Task ID: M-ASYNC-05
|
||||
Role: sonnet-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step A3 (after A2 M-ASYNC-04 is committed). Repo VoidLibrary, branch
|
||||
`feat/roadmap-p2-wave11`. Isolated worktree; first fast-forward it to the HEAD stated in your prompt.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests (1,480 ✔, 4 ⊘).
|
||||
- Observed source (M-ASYNC-01 characterization folded in):
|
||||
- `include/Void/Async/EventBus.hpp` (`Void::EventBus`): sync `publish` iterates the live vector without
|
||||
the lock (~:156-164) so subscribe/unsubscribe during dispatch is UB; Async mode starts a private
|
||||
thread in the constructor (~:43-48); the async snapshot copies `std::function`s so `unsubscribe`
|
||||
cannot retract queued copies (~:167-169); a handler exception escapes the worker loop and terminates
|
||||
(~:248-269); task queue and handler list unbounded (~:272-278); `Subscription::reset` does not join
|
||||
(~:115-121); `Subscription` holds a raw `EventBus*` (~:137-146); `flush()` returns void (~:193-201).
|
||||
- `include/Void/Async/Observable.hpp`: `Observable`/`Signal` iterate live vectors (~:74-77, :116-119);
|
||||
reentrant use is UB; no threading policy; on throw the value stays new (~:40-42).
|
||||
- Existing tests: `tests/standalone/Async/{EventBus,EventBusAsync,Observable}.cpp` (12/4/14).
|
||||
- Available from A2: `Async::ThreadExecutor` (bounded, `join`, `is_executor_thread`), `ManualExecutor`.
|
||||
- Requirements: roadmap row M-ASYNC-05 ("EventBus/Observable snapshot dispatch, joined subscriptions,
|
||||
injected scheduling | Reentrancy, callback throw and unsubscribe races leave no captured state in use
|
||||
after join"); C-03/C-05; decisions D-W11-06 (accepted with conditions), D-038, D-040 (N6, P3-8).
|
||||
- MANDATORY design sources: `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-ASYNC-05,
|
||||
`W11-PLAN-REV1-OUTPUT.md` F12 + P3 (Observable/Signal, captured-state tests), `W11-CONTRACT-R2.md` N6.
|
||||
Precedence R2 > REV1 > PLAN.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
EDIT `include/Void/Async/EventBus.hpp` and `include/Void/Async/Observable.hpp`; NEW tests
|
||||
`tests/standalone/Async/EventBusJoin.cpp`, `tests/standalone/Async/ObservableReentrancy.cpp`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Out: Executor/Operation/TaskScope/ThreadExecutor changes, build files, other modules.
|
||||
|
||||
## 4. Files to inspect
|
||||
`include/Void/Async/{EventBus,Observable,Executor,TaskScope,ThreadExecutor}.hpp`, the three existing
|
||||
tests, and the design sources in §1.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Async/EventBus.hpp`, `include/Void/Async/Observable.hpp`,
|
||||
`tests/standalone/Async/EventBusJoin.cpp` (NEW), `tests/standalone/Async/ObservableReentrancy.cpp` (NEW).
|
||||
Forbidden: every other path, including the existing EventBus/Observable test files. Other implementers
|
||||
work concurrently in other worktrees (IO; Runtime). No git operations except the authorized fast-forward.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
MANDATORY:
|
||||
- Subscription state in shared ownership; every dispatch (all modes) iterates a snapshot of entries and
|
||||
checks a per-entry live flag before invoking; callbacks run outside locks.
|
||||
- NEW `Mode::Injected` + `EventBus(Async::Executor&, BusOptions)`: no private thread; dispatch frames
|
||||
capture `shared_ptr<detail::BusCore>`; bounded subscriptions/admitted dispatches → `overloaded`;
|
||||
Injected and Async modes catch handler exceptions and route them to `error_sink` (outside locks),
|
||||
counting `callback_failures`; a throwing `error_sink` is caught and counted (D-W11-06 condition).
|
||||
Sync `publish` keeps 1.x exception propagation.
|
||||
- `Subscription::close_and_join()`: suppresses admitted-but-not-started deliveries, waits for in-flight
|
||||
callbacks on other threads, resets the handler (releasing captured state) before returning; on its own
|
||||
callback thread → `self_join` (self-unsubscribe via legacy `unsubscribe`/`reset` still works).
|
||||
- 1.x `unsubscribe` in `Mode::Async` still delivers already-queued copies (pinned test).
|
||||
- `EventBus::close_and_join()` / `close_and_join_pumping(ManualExecutor&)`; `flush_blocking()`
|
||||
(`self_join` on an executor thread or inside a bus callback; `invalid_argument` on a ManualExecutor);
|
||||
`flush_pumping(ManualExecutor&)`; legacy `flush()` in Injected mode calls `flush_blocking()` and
|
||||
discards the error (never deadlocks).
|
||||
- `~EventBus` (N6): gates every admitted-but-not-started delivery on every thread before returning
|
||||
(core `closed` flag checked under the core lock before each delivery starts); waits for callbacks
|
||||
running on OTHER threads, excluding the current thread's own in-progress callback (thread-local
|
||||
dispatch depth); documented residual: destroying a bus from inside a callback that another thread's
|
||||
callback waits on can deadlock (caller error). On a ManualExecutor it pumps (TaskScope pattern).
|
||||
- Observable/Signal (REV1 P3): documented single-threaded, not thread-safe, reentrancy-safe. For
|
||||
copyable `T` (`std::copy_constructible`): nested `set` updates the value immediately and queues
|
||||
`(old, new)` copies delivered FIFO after the current pass, bounded at
|
||||
`kMaxPendingNotifications = 1024`; overflow keeps the new value and counts a dropped notification;
|
||||
`try_set(T)` (copyable only) → `overloaded` without changing the value; `dropped_notifications()`.
|
||||
Move-only `T`: 1.x immediate recursive notification over a listener snapshot, no queue, no `try_set`.
|
||||
Unsubscribe during a pass skips that listener for the rest of the pass; subscribe during a pass is not
|
||||
in the current pass. On a throw: the value stays new, dispatch depth restored, that pass's queued
|
||||
notifications dropped and counted, exception propagates from the outermost `set`/`emit`.
|
||||
`Signal<Args...>` follows the same rule when all decayed `Args` are copyable (queue is `mutable`).
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::EventBus {
|
||||
enum class Mode { Sync, Async, Injected }; // NEW enumerator appended
|
||||
struct BusOptions { std::size_t max_subscriptions{1024}; std::size_t max_admitted_dispatches{1024};
|
||||
std::function<void(std::exception_ptr)> error_sink{}; };
|
||||
// EventBus additions (existing API unchanged):
|
||||
explicit EventBus(Void::Async::Executor& executor, BusOptions = {});
|
||||
template <class Event> [[nodiscard]] Void::Result::Result<Subscription> try_subscribe(std::function<void(const Event&)>);
|
||||
template <class Event> [[nodiscard]] Void::Result::Result<void> try_publish(const Event&); // overloaded / closed
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join_pumping(Void::Async::ManualExecutor&);
|
||||
[[nodiscard]] Void::Result::Result<void> flush_blocking();
|
||||
[[nodiscard]] Void::Result::Result<void> flush_pumping(Void::Async::ManualExecutor&);
|
||||
[[nodiscard]] std::uint64_t callback_failures() const noexcept;
|
||||
// Subscription addition: [[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
}
|
||||
// Observable.hpp: inline constexpr std::size_t kMaxPendingNotifications = 1024;
|
||||
// Observable<T>: Void::Result::Result<void> try_set(T) requires std::copy_constructible<T>;
|
||||
// std::size_t dropped_notifications() const noexcept;
|
||||
```
|
||||
Errors use `Void::Async::make_async_error` codes (`overloaded`, `closed`, `self_join`, `invalid_argument`).
|
||||
If EventBus.hpp currently includes no Async headers, adding `Void/Async/Executor.hpp` is allowed (same
|
||||
module). Unchanged 1.x: every existing EventBus/Observable/Signal signature and their existing tests.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: A2 (ThreadExecutor) in your base. Downstream: none in this wave. Root integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Reentrant subscribe/unsubscribe/publish inside callbacks (ASan); unsubscribe vs dispatch races (TSan);
|
||||
callback throw in every mode; destruction on executor thread; captured-state release verified by a
|
||||
sentinel `shared_ptr` `use_count() == 1` after join; bounded queues; no user code under locks.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
- `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`,
|
||||
`bus_unsubscribe_during_dispatch_prevents_later_admission`, `bus_self_unsubscribe_ok_self_join_rejected`,
|
||||
`bus_callback_throw_to_error_sink_others_run`, `bus_error_sink_throw_caught_and_counted`,
|
||||
`bus_legacy_async_unsubscribe_keeps_queued_copy`, `bus_sync_reentrant_subscribe_unsubscribe_asan`,
|
||||
`bus_publish_after_close_closed`, `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`,
|
||||
`bus_destructor_gates_admitted_deliveries`, `bus_flush_blocking_self_join_and_manual_invalid`.
|
||||
- `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`,
|
||||
`observable_move_only_immediate_notification_compat`, `signal_reentrant_connect_disconnect_during_emit`.
|
||||
- Existing `EventBus`, `EventBusAsync`, `Observable` tests pass unchanged; TSan 0 races; ASan+UBSan 0
|
||||
errors; `-Werror` syntax checks clean.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm the new suites appear in the output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async5 --parallel 8 && /tmp/void-w11-async5/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\." && ctest --test-dir /tmp/void-w11-async5 --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-async5-tsan --parallel 8 && /tmp/void-w11-async5-tsan/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async5-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-async5-asan --parallel 8 && /tmp/void-w11-async5-asan/tests/VoidTests --filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."'
|
||||
dev cpp-gcc -c bash -lc 'for f in EventBusJoin ObservableReentrancy; 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'
|
||||
```
|
||||
Also run the full `Async;Testing` VoidTests binary unfiltered once to catch regressions in other Async
|
||||
users (Fsm is not selected; root runs the full suite at integration).
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions; 1.x behavior changes limited to those recorded in
|
||||
MIGRATION (snapshot dispatch, nested FIFO for copyable, Async-mode exceptions counted). Stop and report
|
||||
BLOCKED if an existing EventBus/Observable test must change, or two repair attempts at one check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040, D-042 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; checks not run; residual risks; worktree path. Do not spawn children.
|
||||
@@ -0,0 +1,116 @@
|
||||
# M-TIME-03 (step B1b) — Async::retry_async over TimerQueue and deadline-domain conformance
|
||||
|
||||
Task ID: M-TIME-03
|
||||
Role: opus-implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
- Wave 11 package step B1b (gate G1 satisfied: M-FUNCTIONAL-03 committed `26edf65`; M-TIME-03 B1
|
||||
TimerQueue committed on the branch). Repo VoidLibrary, branch `feat/roadmap-p2-wave11`. You work
|
||||
in an isolated worktree; first fast-forward it to the HEAD stated in your prompt.
|
||||
- Baseline: full suite at `38436b1` = 1,484 tests (1,480 ✔, 4 ⊘). Since then: A1 adds RetryState (23
|
||||
tests), B1 adds TimerQueue (15), DeadlineDomains (2), ClockSaturation (1).
|
||||
- Observed source:
|
||||
- `include/Void/Functional/RetryState.hpp`: `RetrySpec`, `RetryState<URBG>::create(spec, start, urbg,
|
||||
admission_deadline)`, `begin/next/resume/succeed` (stop decisions are final), `RetryError<E>{reason,
|
||||
attempts, last_error, config}`, `RetryEveryError`, `AttemptOutcome`, `detail::seeded_engine<G>()`.
|
||||
- `include/Void/Functional/Retry.hpp`: `retry_blocking` (reference shape for error mapping).
|
||||
- `include/Void/Async/Timer.hpp`: `TimerQueue::sleep_until(when, OperationOptions)` → `{}` on expiry
|
||||
after poll, `cancelled` on stop (only if the stop wins the timer cancel race; a stop after poll or
|
||||
close claimed the timer yields `{}`/`stopped`), `timeout` when `options.deadline < when`, `stopped`
|
||||
after close; resumes via `executor().post_completion`; `clock()` is the injected clock.
|
||||
- Requirements: roadmap row M-TIME-03 ("Validate injected-deadline domains with Async and blocking retry
|
||||
adapters; advancing manual time plus explicit polling expires an operation once"); C-03/C-04; D-038.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
1. NEW `include/Void/Async/Retry.hpp`: `Void::Async::retry_async`.
|
||||
2. NEW `tests/standalone/Async/AsyncRetry.cpp`.
|
||||
3. EDIT `tests/standalone/Async/DeadlineDomains.cpp`: add `deadline_domain_blocking_retry_manual_clock`.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
Out: changes to Timer.hpp, RetryState.hpp, Retry.hpp, Executor/Operation/TaskScope, build files.
|
||||
|
||||
## 4. Files to inspect
|
||||
The three headers above, `include/Void/Async/{Task,Executor,TaskScope}.hpp`, `include/Void/Async/Detail/Types.hpp`,
|
||||
`tests/standalone/Async/{TimerQueue,DeadlineDomains}.cpp`, `tests/standalone/Functional/RetryBlocking.cpp`,
|
||||
`docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-TIME-03.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: `include/Void/Async/Retry.hpp` (NEW), `tests/standalone/Async/AsyncRetry.cpp` (NEW),
|
||||
`tests/standalone/Async/DeadlineDomains.cpp`.
|
||||
Forbidden: every other path. Other implementers work concurrently in other worktrees (IO files; Async
|
||||
ThreadExecutor/FuturePool/AsyncChannel/ParallelFor). No git operations except the root-authorized
|
||||
fast-forward in your prompt.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
MANDATORY semantics:
|
||||
- "now" is always `timers.clock().now()`; admission deadline = `options.deadline`; stop = `options.stop`.
|
||||
- Invalid spec → `RetryError{config=err, attempts=0}` without calling `fn`.
|
||||
- Loop: `begin(now, stop_requested)` → on `attempt` call `fn`; `fn` may return `std::expected<T,E>` or
|
||||
`Coro::Task<std::expected<T,E>>` (co_await it). Success → return `T` (also when stop was requested
|
||||
during the attempt). Failure → `next(now, classify(error), stop_requested)`.
|
||||
- On `wait_until(at)`: `co_await timers.sleep_until(at, OperationOptions{options.stop, options.deadline})`.
|
||||
Then ALWAYS call `resume(now, options.stop.stop_requested())` — it re-checks stop itself, which covers
|
||||
the TimerQueue choice where a late stop yields `{}`. Sleep result mapping: `{}` → resume;
|
||||
`cancelled` → stop with `stop_requested`; `timeout` → stop with `deadline_exceeded`; `stopped` (queue
|
||||
closed) → stop with `stop_requested` (documented: queue closure aborts the retry; no further attempt);
|
||||
`overloaded` → stop with `stop_requested` and document (no silent busy retry).
|
||||
- Never sleep with the host clock; never spin; no attempt after any stop decision; `last_error` holds
|
||||
the most recent `E` (empty iff no attempt ran).
|
||||
- Default URBG seeded via `Void::Retry::detail::seeded_engine<URBG>()`.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
```cpp
|
||||
namespace Void::Async {
|
||||
template <class F, class Classify = Void::Retry::RetryEveryError, class URBG = std::mt19937_64>
|
||||
requires std::invocable<F&>
|
||||
[[nodiscard]] auto retry_async(Void::Retry::RetrySpec spec, F fn, TimerQueue& timers,
|
||||
OperationOptions options = {}, Classify classify = {},
|
||||
URBG urbg = Void::Retry::detail::seeded_engine<URBG>())
|
||||
-> Coro::Task<std::expected<T, Void::Retry::RetryError<E>>>; // T,E deduced from fn's (awaited) result
|
||||
}
|
||||
```
|
||||
The coroutine owns `fn`, `classify`, `urbg` and `spec` by value. `timers` (and its executor) must outlive
|
||||
the returned task (document).
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Upstream: A1 (`26edf65`), B1 (TimerQueue). Downstream: none in this wave beyond conformance. Root
|
||||
integrates and commits.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Stop before first attempt; stop during `fn` (success preserved, no retry); stop during backoff; queue
|
||||
closed during backoff; deadline between attempts; zero attempts; move-only `T`/`E`/`F`; Task-returning
|
||||
`fn` that throws (exception propagates out of the retry task — document); manual clock far-future start.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. `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`, `async_retry_queue_closed_during_backoff_stops`,
|
||||
`async_retry_late_stop_after_timer_fired_no_further_attempt`, `async_retry_move_only_value` — all pass.
|
||||
2. `DeadlineDomains.cpp`: `deadline_domain_blocking_retry_manual_clock` (`retry_blocking` with
|
||||
`now = manual.now`, a sleep callable that advances the ManualClock) passes; existing 2 tests pass.
|
||||
3. Existing `TimerQueue`, `RetryState`, `RetryBlocking`, `OperationScope`, `Executor`, `Coro` pass.
|
||||
4. TSan 0 races and ASan+UBSan 0 errors on `AsyncRetry|DeadlineDomains|TimerQueue`.
|
||||
5. `-Werror` syntax check of the new/edited test files and `Async/Retry.hpp` clean.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Cwd = worktree root; `dev` with the sandbox disabled. Confirm the new suite appears in the output.
|
||||
```sh
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3b -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3b --parallel 8 && /tmp/void-w11-time3b/tests/VoidTests --filter "^(AsyncRetry|DeadlineDomains|TimerQueue|RetryState|RetryBlocking|OperationScope|Executor|Coro)\." && ctest --test-dir /tmp/void-w11-time3b --output-on-failure --timeout 60'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3b-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-time3b-tsan --parallel 8 && /tmp/void-w11-time3b-tsan/tests/VoidTests --filter "^(AsyncRetry|DeadlineDomains|TimerQueue)\."'
|
||||
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3b-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-time3b-asan --parallel 8 && /tmp/void-w11-time3b-asan/tests/VoidTests --filter "^(AsyncRetry|DeadlineDomains|TimerQueue)\."'
|
||||
dev cpp-gcc -c bash -lc 'for f in Async/AsyncRetry Async/DeadlineDomains; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/$f.cpp || exit 1; done'
|
||||
```
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
No edits outside write scope; no weakened assertions. Stop and report BLOCKED if the TimerQueue or
|
||||
RetryState contract is insufficient (needs a forbidden edit), or two repair attempts at one check fail.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
Root decisions D-034, D-038, D-040, D-042 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; checks not run; residual risks; worktree path. Do not spawn children.
|
||||
@@ -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<detail::FileWorkerShared>`, 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<void>`.
|
||||
- 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<void>` 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<detail::FileWorkerShared>` and `weak_ptr<DriverBackend>`,
|
||||
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::byte>, std::uint64_t) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult pwrite(int, std::span<const std::byte>, std::uint64_t) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult sync(int, SyncMode) noexcept;
|
||||
[[nodiscard]] virtual FileSyscallResult close(int) noexcept;
|
||||
[[nodiscard]] static FileSyscalls& native() noexcept; };
|
||||
class File { public: File() noexcept; File(File&&) noexcept; File& operator=(File&&) noexcept; ~File();
|
||||
[[nodiscard]] bool valid() const noexcept; [[nodiscard]] DescriptorId id() const noexcept;
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(std::uint64_t, BufferLease&, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at_owned(std::uint64_t, const BufferLease&, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(SyncMode = SyncMode::full, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(Async::OperationOptions = {}); };
|
||||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> read_exact_at(File&, std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
|
||||
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> write_all_at(File&, std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
|
||||
}
|
||||
// Driver.hpp additions
|
||||
[[nodiscard]] Void::Result::Result<File> Driver::open_file(const std::filesystem::path&, FileOpenOptions = {});
|
||||
[[nodiscard]] Void::Result::Result<File> Driver::adopt_file_fd(int fd);
|
||||
[[nodiscard]] Void::Result::Result<void> Driver::start_file_workers();
|
||||
[[nodiscard]] Void::Result::Result<std::size_t> 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<DriverShutdownReport> 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<Void::Result::Result<void>(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<DriverShutdownReport> advance_shutdown(
|
||||
std::optional<Void::Time::MonotonicClock::time_point> 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 <Void/IO/$h.hpp>" | 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.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Wave 11 contract amendment R2 (root resolutions of PREFLIGHT-2)
|
||||
|
||||
Source findings: [W11-PREFLIGHT-2-OUTPUT](W11-PREFLIGHT-2-OUTPUT.md). Base contracts:
|
||||
[W11-PLAN-OUTPUT](W11-PLAN-OUTPUT.md) amended by [W11-PLAN-REV1-OUTPUT](W11-PLAN-REV1-OUTPUT.md).
|
||||
These rules are MANDATORY text for the B2, B3, B4, A2, A3, A4 specs (decision D-040). Where this
|
||||
file and earlier documents disagree, this file wins.
|
||||
|
||||
## N1 — Host destruction and shutdown budgets (B3/B4)
|
||||
- `~HostCore` blocks until shutdown is complete: it loops an internal no-deadline shutdown
|
||||
(equivalent to repeated `shutdown_blocking({})` ignoring the total-timeout cap) until
|
||||
`complete == true`. Documented: "destruction blocks until complete".
|
||||
- `poll_shutdown(Async::OperationOptions = {})` takes options; every shutdown entry point
|
||||
(`shutdown_blocking`, `poll_shutdown`, `shutdown_pumping`) uses the same per-call budget
|
||||
`min(options.deadline, deadline_after(clock, total_timeout))`.
|
||||
- The budget test uses an already-expired caller deadline (or manual-clock deadline) with
|
||||
`shutdown_blocking`/`poll_shutdown`, so expiry is observable.
|
||||
- Waiting phases that return `complete=false` on call-deadline expiry: 2, 4, 5, 6, 8, 9 (P3-1).
|
||||
|
||||
## N2 — Embedded mode (B3/B4)
|
||||
- `shutdown_blocking` returns `RuntimeErrorCode::invalid_argument` when the Host's executor has
|
||||
no background workers (`!has_background_workers()`); `shutdown_pumping` in managed (owned
|
||||
executor) mode returns `invalid_argument` (the reactor owns polling).
|
||||
- `~HostCore` in embedded mode: if the borrowed executor is a `ManualExecutor`
|
||||
(`dynamic_cast`), it loops `shutdown_pumping(manual)` until complete; otherwise, if shutdown is
|
||||
not already complete, it prints a diagnostic and calls `std::terminate` (documented
|
||||
programmer error: embedded Host destroyed before shutdown completed).
|
||||
- The "destroyed on a Runtime worker" terminate check applies only to OWNED executors/reactor/
|
||||
IO workers; never to a borrowed executor's `is_executor_thread()`.
|
||||
|
||||
## N3 — Who polls during shutdown (B2, A4, B3/B4)
|
||||
- B2: every poll turn drains cancels, control messages and file completions BEFORE any
|
||||
stop-flag early return. `begin_shutdown` sets the existing stopping flag (admission closed).
|
||||
While stopping (but not yet shut down), a turn with no work waits in `epoll_wait` up to
|
||||
`max_wait` (wake fd stays registered) instead of returning immediately; it must not spin.
|
||||
- B2: after shutdown completes, `poll_once` returns 0 without touching any fd (F2), and
|
||||
`shutdown_complete()` is true; library loops must exit on it (below).
|
||||
- B2: `poll_once` checks the thread-local polling marker before `try_lock(poll_mu_)`; a
|
||||
reentrant call from inside a turn returns `busy` (no recursive try_lock UB).
|
||||
- B2: `advance_shutdown` releases `poll_mu_` between its ≤1 ms slices; other pollers may run
|
||||
turns in between (they only drain/dispatch). If its stop token fires it returns the current
|
||||
report with `complete=false` (not an error).
|
||||
- B2: when `advance_shutdown`/teardown dispatches resume tickets, it does so after releasing
|
||||
poll ownership (P3-9). Document: an owned executor must not be joined before the Driver is
|
||||
torn down.
|
||||
- A4: `Driver::run` and `pump_until` on `busy` wait up to `max_wait` (stop-aware, at most 1 ms
|
||||
slices) and retry; they exit when `shutdown_complete()` is true.
|
||||
- B3/B4: Runtime phase 8 first requests reactor stop and JOINS the reactor thread, then drives
|
||||
`driver->shutdown(remaining)` from the shutdown thread. The reactor loop also exits on
|
||||
`shutdown_complete()`; on `busy` it waits as A4's loops do.
|
||||
|
||||
## N4 — File descriptor state machine (B2)
|
||||
- `detail::FileState` has `enum { open, closing, closed }` guarded by the pool mutex; the
|
||||
handle-drop / in-flight count / `close_pending` transitions happen under that mutex, so
|
||||
exactly one close is enqueued and whoever closes the fd sets `closed`.
|
||||
- Driver teardown closes any still-open file fds after joining workers and marks them
|
||||
`closed`. Afterwards File reads/writes/syncs return `IoErrorCode::closed` without a syscall,
|
||||
`~File` does nothing, and `close_and_join` returns success immediately (idempotent).
|
||||
- Files count against `IoLimits::max_descriptors`; that bounds the reserved close capacity.
|
||||
The close request node is preallocated inside `FileState`, so `~File` (noexcept) never
|
||||
allocates.
|
||||
- `~File` wakes the poller only through a weak→strong backend lock or the worker condition
|
||||
variable, never through the raw waker pointer.
|
||||
|
||||
## N5 — Channel timer callbacks (A2; B1 documents)
|
||||
- B1 documents: `TimerHandle::cancel() == false` means the callback fired or is firing, not
|
||||
that it finished.
|
||||
- A2: an AsyncChannel timer callback captures shared waiter state (`shared_ptr` control block
|
||||
for the waiter) or a `weak_ptr` to the channel plus a waiter id looked up under the channel
|
||||
lock. It never holds a raw pointer into a coroutine frame.
|
||||
|
||||
## N6 — EventBus destruction (A3)
|
||||
- `~EventBus` gates every admitted-but-not-started delivery on every thread before returning
|
||||
(shared core `closed` flag checked under the core lock before each delivery starts).
|
||||
- It waits for callbacks running on OTHER threads to finish, excluding the current thread's own
|
||||
in-progress callback (thread-local dispatch depth). Residual documented: destroying a bus from
|
||||
inside a callback that another thread's callback waits on can deadlock (caller error).
|
||||
- A throwing `error_sink` is caught and counted (D-W11-06 condition, P3-8).
|
||||
|
||||
## P3 lines
|
||||
- P3-2 (B3/B4): owned `BudgetResource`, executor and driver objects live until `~HostCore`;
|
||||
NEW `[[nodiscard]] std::size_t Host::cpu_admitted() const noexcept` (0 when not started or
|
||||
embedded) for the budget test; a `BufferLease` must not outlive its resource.
|
||||
- P3-3 (B3/B4): the borrowed `SignalGate` must outlive the Host; Host tracks `gate_installed_`
|
||||
so `uninstall` runs at most once (failed-start cleanup and teardown cannot double-uninstall);
|
||||
the off-owner signal test restores the owner mask and drains SIGUSR2 before finishing.
|
||||
- P3-4 (root): MIGRATION records "concurrent `poll_once` returns `busy`" and "`~Driver` on a
|
||||
file worker or inside a poll turn terminates"; `Runtime.md` shows the `TimerQueue*` parameter
|
||||
on `shutdown_pumping`.
|
||||
- P3-5 (B2): the D1 seam clock is armed only after submission (`submit_io` reads the clock at
|
||||
`EpollDriver.cpp:503`).
|
||||
- P3-6 (A1): `seeded_engine` constructs with parentheses `G(std::random_device{}())` (sent).
|
||||
- P3-7 (B3): moved-from Host reference accessors (`options`, `lifecycle_plan`,
|
||||
`embedded_resources`) have precondition `valid()` (documented, asserted in debug); `HostCore`
|
||||
holds no pointers into `Host` members.
|
||||
- P3-8 (B3): stop-and-report if an IO edit is needed (IO files are owned elsewhere).
|
||||
@@ -0,0 +1,162 @@
|
||||
# W11-PREFLIGHT-2 output (opus-reviewer, 2026-11-29)
|
||||
|
||||
Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`.
|
||||
|
||||
**Task W11-PREFLIGHT-2. Verdict: CHANGES_REQUIRED.** The addendum and the root edits fix the first review's P1 (F1) and most of F2–F13. Six P2 gaps remain. One is a contradiction inside the addendum itself (N1). Four are gaps that the addendum's own resolutions create (N3–N6), and one is a state the addendum never covers (N2). All six can be fixed by adding sentences to the contract text. No re-plan, gate change or ownership change is needed.
|
||||
|
||||
- **Blocked until the text is amended:** B2 (N3, N4), B3/B4 (N1, N2, N3), A2's channel deadlines (N5; the rest of A2 can proceed), A3's EventBus work (N6). A4 picks up N3's loop rules when its spec is written.
|
||||
- **Not blocked:** A1 (M-FUNCTIONAL-03) can continue. B1 (M-TIME-03) can continue but needs one documentation-only note (N5). Neither needs an interface change.
|
||||
|
||||
Paths are relative to `/home/faumaray/Projects/VoidLibrary`. "Addendum" means `docs/agent-workflow/tasks/W11-PLAN-REV1-OUTPUT.md`; "plan" means `W11-PLAN-OUTPUT.md`.
|
||||
|
||||
## Item status
|
||||
|
||||
| Item | Status | Evidence / residual |
|
||||
|---|---|---|
|
||||
| F1 | RESOLVED | Workers only run a syscall and queue the result, so no completion runs on a worker. They hold a separate worker-pool object, never the backend. Backend destructors never block, and only `~Driver` does a blocking teardown, behind two terminate markers. Residual: P3-9. |
|
||||
| F2 | RESOLVED for sockets | The epoll and wake fds still close in the backend destructor (`EpollDriver.cpp:953-963`). Every socket-path `wake()` caller holds a strong reference (`:589-596`, `Backend.hpp:89-96`, `Stream.hpp:105-120`). The file path depends on N4. |
|
||||
| F3 | RESOLVED | Phase 7 drops the components before IO stops (phase 8) and before the executor is joined (phase 9). |
|
||||
| F4 | PARTIAL | The per-call budget fixes the zero-budget repeat call, but it contradicts the destructor rule (N1). Phase 2 is missing from the waiting-phase list (P3-1). |
|
||||
| F5 | PARTIAL | Moved-from rules are fine; gaps in N1, N2, P3-3 and P3-7. |
|
||||
| F6 | PARTIAL | Borrowed resources are skipped, but the embedded `ManualExecutor` path hangs (N2). |
|
||||
| F7 | PARTIAL | The single-lock claim/hand-off rule is sound. The timer callback can still reach a destroyed waiter (N5). |
|
||||
| F8 | RESOLVED | `seeded_engine` is in `M-FUNCTIONAL-03.md:114-142`. Nit: P3-6. |
|
||||
| F9 | PARTIAL | The routing fix is done. Choosing `busy` without loop rules creates N3. |
|
||||
| F10 | RESOLVED | The `7f95f89` doc edits match the addendum. Small gaps: P3-4. |
|
||||
| F11 | RESOLVED | The IO and executor start hooks plus `cleanup_timeout` cover failures inside a step (a later destructor finishes the cleanup, see N1). |
|
||||
| F12 | PARTIAL | `TimerHandle` shared state and the `parallel_for` shared state are fine. Gaps: N5 (timer) and N6 (EventBus). |
|
||||
| F13 | PARTIAL | The `FileState` deferred close is right in direction. The fd state machine is incomplete (N4). |
|
||||
|
||||
**First-review P3 items**
|
||||
|
||||
| Item | Status |
|
||||
|---|---|
|
||||
| `retry_blocking` template defaults | RESOLVED (`M-FUNCTIONAL-03.md:135-142`) |
|
||||
| Observable/Signal move-only and "state restored" | RESOLVED |
|
||||
| Downstream build list | RESOLVED |
|
||||
| Error-kind alignment | RESOLVED; observed in `Runtime/Options.hpp`, `shutdown_incomplete` maps to `conflict` |
|
||||
| D1 regression seam | RESOLVED (seam at `:1083`/`:1098`); see P3-5 |
|
||||
| Mock reactor spin | PARTIAL: the mock case is covered, the epoll cases are open (N3) |
|
||||
| Business scope `stop_on_first_error` | RESOLVED |
|
||||
| MIGRATION: `shutdown_and_join` blocks / `max_file_queue==0` / Sync snapshot / `parallel_for` | RESOLVED, all four observed in `MIGRATION.md:61` |
|
||||
| Unspecified: concurrent `poll_once` | PARTIAL (N3) |
|
||||
| Unspecified: IO file ownership after G5 | RESOLVED (G6) |
|
||||
| Unspecified: stop-and-report if an IO edit is needed | PARTIAL: stated for B4 and A4, not for B3 |
|
||||
| Unspecified: worker detection | RESOLVED (`is_io_worker_thread`) |
|
||||
| `ThreadExecutor` endless drain, destructor without join | RESOLVED |
|
||||
| Acceptance gaps (layering `rg`, within-step faults, ordering, budget test, receiver stop, legacy-mode captures) | RESOLVED; budget test lifetime in P3-2 |
|
||||
|
||||
**Named checks (§3)**
|
||||
|
||||
| Check | Answer |
|
||||
|---|---|
|
||||
| `busy` breaking existing callers | It does not. The only library loop that polls is `~Session` (`src/IPC/Session.cpp:1118-1129`): bounded to 1,000 iterations, result ignored. Every test drives a driver from one thread, and the one cross-thread test polls from only one thread (`IoDriver.cpp:458-508`). The hazard is in the new loops (N3). |
|
||||
| `wake_closed_` atomic argument | Sound. The last `shared_ptr` release orders the destructor after every `wake()`. The flag is effectively optional because the fd closes only in the destructor. The file wake path is not enumerated (N4). |
|
||||
| `FileState` reserved close capacity | Bounded only if files take descriptor slots. The addendum doesn't say so (N4). |
|
||||
| `ThreadExecutor::idle()` in phase 9 | Usable, but it is a snapshot, so "join never unbounded" is overstated (posts after the snapshot still extend the join). Safe in Runtime because phase 8 has already stopped IO dispatch. |
|
||||
|
||||
**Named hazards (§6.2)**
|
||||
|
||||
| Hazard | Answer |
|
||||
|---|---|
|
||||
| Raw waker pointer lifetime | Sound for workers: every backend destruction path goes through `~Driver`, which joins the workers first. `~File` must not use that waker (N4). |
|
||||
| `busy` and loop callers | See N3. |
|
||||
| Reserved close capacity unbounded | See N4. |
|
||||
| Phase-9 idle wait vs inline resume after join | Unreachable from IO, because phase 8 runs first. External posts (stop callbacks, user threads) resume inline; this is documented. |
|
||||
| `~HostCore` unbounded shutdown on destruction | Contradicted by the per-call budget (N1). Hangs in embedded mode (N2). |
|
||||
|
||||
**Planner adjustments**
|
||||
|
||||
| Adjustment | Verdict |
|
||||
|---|---|
|
||||
| Signal adapter closes its fd off the owner thread | Agree. It matches `src/System/SignalWatcher.cpp:27-37`, and `Runtime.md` is updated. Test hygiene: P3-3. |
|
||||
| Injected syscall shim as the one exception | Agree. `IO.md:94-96` is updated. |
|
||||
| Observable FIFO ordering change | Agree. It is recorded in `MIGRATION.md`. |
|
||||
|
||||
## New findings
|
||||
|
||||
**N1 (P2, observed contradiction): the destructor's shutdown is called "unbounded" but the budget rule caps it at 30 s.**
|
||||
- **Where:** addendum `:85` says "(unbounded)". Addendum `:75-79` caps every call at `min(deadline, now + total_timeout)` and returns `complete=false` on expiry. `validate_options` rejects `total_timeout <= 0`, so the cap can't be switched off. The failed-start continuation (`:230`) relies on the same path.
|
||||
- **What happens:** a stall longer than 30 s makes `~HostCore` return from the shutdown call incomplete. A joinable reactor `std::thread` then calls `std::terminate`. If it didn't, members would tear down while components still exist.
|
||||
- **Related:** `poll_shutdown()` takes no options, so its budget restarts on every call. The plan test `runtime_shutdown_budget_min_caller_policy_manual_clock (poll_shutdown)` (plan `:745`) can therefore never see an expiry.
|
||||
- **Fix:** `~HostCore` loops `shutdown_blocking({})` until `complete` (or calls an internal no-deadline variant). State "destruction blocks until complete". Move that test to `shutdown_blocking` with an expired or manual-clock deadline. Define how `poll_shutdown` relates to the budget.
|
||||
|
||||
**N2 (P2, inferred hang): embedded mode with a borrowed `ManualExecutor`.**
|
||||
- **Where:** `~HostCore` calls `shutdown_blocking`. Phase 4 then reaches `TaskScope::join_blocking`, which waits on a condition variable that nothing will ever pump (`include/Void/Async/TaskScope.hpp:289-303`). Component `stop()` tasks also need pumping.
|
||||
- **What happens:** destroying an unstopped embedded Host that has a business task or any component hangs forever.
|
||||
- **Second problem:** the terminate check uses `executor->is_executor_thread()`, which is true inside an ordinary `manual.drain()` of the borrowed executor.
|
||||
- **Fix:**
|
||||
- `shutdown_blocking` returns `invalid_argument` when the executor has no background workers, as `flush_blocking` already does.
|
||||
- `~HostCore` with a `ManualExecutor` pumps, following the `~TaskScope` pattern (`TaskScope.hpp:562-575`).
|
||||
- The terminate check applies only to owned executors.
|
||||
- `shutdown_pumping` in managed mode returns `invalid_argument`, because the reactor owns polling and `pump_until` would just get `busy`.
|
||||
|
||||
**N3 (P2, inferred spin plus one hang path): who polls during shutdown is never specified.**
|
||||
- **Spins:**
|
||||
- `busy` returns immediately, so the B3 reactor loop (`poll_once(5ms)`), A4's `Driver::run` and `pump_until` spin hot while `advance_shutdown` holds poll ownership.
|
||||
- The 1.x early return once stopping is set (`EpollDriver.cpp:1057-1059`) skips `epoll_wait`, so loops spin throughout the shutdown window.
|
||||
- After `shut_down_`, `poll_once` returns 0 immediately, so the reactor spins until phase 9 joins it.
|
||||
- **Hang:** the addendum doesn't say where file completions are drained relative to that early return. If the drain sits after `epoll_wait` (the natural place, next to `drain_wake_fd`), in-flight file requests are never retired. `quiescent()` then never becomes true, `advance_shutdown` never completes, and `teardown_blocking` in `~Driver` hangs.
|
||||
- **Undefined behaviour:** `try_lock` on `poll_mu_` by the thread that already owns it, reachable through an inline resume inside a turn.
|
||||
- **Fix, one sentence each:**
|
||||
- Cancels, controls and file completions drain before any stop-flag return.
|
||||
- Say whether `begin_shutdown` sets `stopping_`.
|
||||
- Library loops wait up to `max_wait` (stop-aware) on `busy` and exit on `shutdown_complete()`.
|
||||
- Choose one: phase 8 stops and joins the reactor before `advance_shutdown`, or the reactor exits on completion.
|
||||
- `advance_shutdown` either releases `poll_mu_` between its 1 ms slices or makes the other pollers park.
|
||||
- `poll_once` checks the thread-local polling marker before `try_lock`.
|
||||
- Define what `advance_shutdown` returns when its stop token fires.
|
||||
|
||||
**N4 (P2, inferred double close / use-after-free): the File fd state machine is incomplete (F13).**
|
||||
- **Missing invariants:**
|
||||
- The transitions between handle drop, in-flight count and `close_pending` happen under one mutex, so exactly one close is enqueued.
|
||||
- A File that outlives shutdown completion or `~Driver` holds an fd that teardown closed. A later `~File` or `close_and_join` must not close that number again, because it may now belong to someone else. Reads and writes must return `closed` without a syscall.
|
||||
- `close_and_join` after the workers are joined has nothing to run the close on ("close always executes on a worker or `run_file_work`").
|
||||
- `~File` must wake through a weak→strong backend lock or the worker condition variable, never the raw waker.
|
||||
- Reserved close capacity is not stated as bounded.
|
||||
- **Fix:**
|
||||
- Give `FileState` an `open → closing → closed` state under the pool mutex; whoever closes sets `closed`.
|
||||
- After completion, `close_and_join` returns at once and `~File` does nothing.
|
||||
- Files count against `max_descriptors`, which bounds the reserved close capacity.
|
||||
- Preallocate the close node inside `FileState`, so the `noexcept` `~File` path never allocates.
|
||||
|
||||
**N5 (P2, inferred use-after-free; affects B1, which is running): channel timer callbacks vs waiter nodes.**
|
||||
- **Where:** `M-TIME-03.md:63-65,89,113` says callbacks fire outside the lock after pending→fired, and that `cancel()` returning true means "never runs". It does not cover a callback that has fired and is still running. Addendum F7 puts waiter nodes in coroutine frames and has the timer callback "do nothing if claimed".
|
||||
- **What happens:** a sender claims the waiter, the receiver resumes and its `cancel()` returns false, its frame is destroyed, and the in-progress callback then reads the dead node.
|
||||
- **Fix:**
|
||||
- B1, documentation only: `cancel()==false` does not mean the callback has finished. B1 may continue.
|
||||
- A2: the timer callback captures shared waiter state, or the channel plus a waiter id that it looks up under the channel lock. It must never hold a raw pointer into a frame.
|
||||
|
||||
**N6 (P2, inferred use-after-free): `~EventBus` on an executor thread doesn't wait (F12).**
|
||||
- **Where:** `Subscription` holds a raw `EventBus*` (`include/Void/Async/EventBus.hpp:137-146`), and handlers commonly capture `EventBus&` to publish follow-up events.
|
||||
- **What happens:** frames already queued keep delivering after the destructor returns, and any handler that touches the bus hits a dead object.
|
||||
- **Fix:** `~EventBus` gates every admitted-but-not-started delivery on every thread before it returns. Either wait for callbacks running on other threads (excluding the current one, via a thread-local depth) or document that residual.
|
||||
|
||||
**P3 (each changes one spec line)**
|
||||
1. Add phase 2 to the list of phases that return incomplete when the call deadline expires. Today a caller deadline shorter than the drain grace is ambiguous.
|
||||
2. The owned BudgetResource, executor and driver objects must live until `~HostCore`.
|
||||
- The budget test reads `memory_budget()` and `admitted()` after `complete`, and `admitted()` needs `ThreadExecutor`, not `Executor*`.
|
||||
- A `BufferLease` that outlives its resource is a use-after-free.
|
||||
3. Signal gate:
|
||||
- The borrowed `signal_gate` must outlive the Host.
|
||||
- `uninstall` must be idempotent or tracked, because failed-start cleanup already uninstalls.
|
||||
- The off-owner signal test must restore the owner's mask and drain SIGUSR2 at the end.
|
||||
4. MIGRATION and Runtime.md:
|
||||
- Add "concurrent `poll_once` returns `busy`" and "`~Driver` on a file worker or inside a poll turn terminates" to MIGRATION.
|
||||
- `Runtime.md` is missing the `TimerQueue*` parameter on `shutdown_pumping`.
|
||||
5. The D1 seam clock must be armed after submission. `submit_io` reads the clock at `:503`, and a stop there takes the pre-queue path, so D1 never reproduces.
|
||||
6. Use `G(std::random_device{}())` (parentheses). Braces are a narrowing error for engines whose seed type is narrower than `unsigned`. Documentation-only for A1.
|
||||
7. Moved-from Host and HostCore:
|
||||
- The moved-from rules omit the reference accessors (`options`, `lifecycle_plan`, `embedded_resources`).
|
||||
- HostCore must not hold pointers into Host members, because Host is movable.
|
||||
8. Carry D-W11-06's condition into A3: a throwing `error_sink` is caught and counted. Add a B3 stop-and-report rule for IO edits.
|
||||
9. Teardown with an already-joined `ThreadExecutor` resumes continuations inline inside the shutdown's own poll turn. Either dispatch after releasing ownership, or document that the executor must not be joined before the Driver is torn down (the Runtime order already satisfies this).
|
||||
|
||||
## Re-review scope
|
||||
Only the amended text for N1–N6 and the P3 lines above. This can be checked on the B2, B3, B4, A2 and A3 task specs; no new planner round is needed.
|
||||
|
||||
## Checks not run
|
||||
- No builds, tests or compile probes. Everything above comes from direct `sed`/`rg` reads. No Serena or codebase-memory coverage checks.
|
||||
- Not read: `EpollDriver.cpp:1475-1640` (the rest of `drive_read` and `drive_write`), `ThreadPool.hpp`, `ResourceGraph.hpp`, the `RuntimeHost.cpp` tests, and TASKS/STATE.
|
||||
- `M-TIME-03.md` and `M-FUNCTIONAL-03.md` were only partly read.
|
||||
- A new commit, `a8a9249` (D-039), landed during the review. I checked it: it does not touch the W11 contracts.
|
||||
@@ -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<void>` 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<detail::FileWorkerShared>` and `weak_ptr<DriverBackend>`, 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.
|
||||
@@ -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.
|
||||
@@ -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. 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 |
|
||||
| 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; a concurrent `poll_once` caller gets `busy`; `~Driver` on a file worker or inside a poll turn terminates with a diagnostic |
|
||||
| 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 |
|
||||
|
||||
@@ -49,8 +49,9 @@ public:
|
||||
Async::Executor* executor();
|
||||
IO::Driver* io();
|
||||
Result<ShutdownReport> shutdown_blocking(Async::OperationOptions);
|
||||
Result<ShutdownReport> poll_shutdown(); // non-blocking step
|
||||
Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions);
|
||||
Result<ShutdownReport> poll_shutdown(Async::OperationOptions); // non-blocking step
|
||||
Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions,
|
||||
Async::TimerQueue* timers = nullptr);
|
||||
// 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.
|
||||
|
||||
@@ -0,0 +1,686 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// ── TimerQueue ────────────────────────────────────────────────────────────────
|
||||
// Injected-clock timer queue for Async code (C-03/C-04).
|
||||
//
|
||||
// * Deadlines are interpreted ONLY in the injected `MonotonicClock` domain. The
|
||||
// host clock is never consulted, so a `ManualClock` starting at epoch 0 (or at
|
||||
// a far-future point) behaves deterministically.
|
||||
// * Nothing fires on its own: there is no background thread. A timer expires
|
||||
// only when an owner calls `poll_expired()` after the injected clock reached
|
||||
// its deadline. `next_deadline()` / `wait_duration()` tell a driver how long
|
||||
// it may block before the next poll.
|
||||
// * Timers are kept in a stable min-heap ordered by `(deadline, submission
|
||||
// seq)`, so equal deadlines fire in submission order.
|
||||
// * Callbacks run exactly once, with `TimerEvent::expired` (from
|
||||
// `poll_expired()`) or `TimerEvent::closed` (from `close()` / destruction),
|
||||
// or never when `TimerHandle::cancel()` returned true. They are always
|
||||
// invoked on the polling/closing thread OUTSIDE the queue's internal lock, so
|
||||
// a callback may schedule, cancel, poll or close without deadlocking.
|
||||
// * `cancel() == false` means the callback has fired or is firing; it does
|
||||
// NOT mean the callback has finished running. Callbacks referencing state
|
||||
// that may be destroyed concurrently must capture shared ownership (or look
|
||||
// the target up under the owner's lock), never a raw pointer into a frame.
|
||||
// * `sleep_until` / `sleep_for` suspend a coroutine until the timer fires and
|
||||
// resume it through `executor().post_completion(...)`, never inline from
|
||||
// `poll_expired()`, `close()` or a stop callback.
|
||||
//
|
||||
// Lifetime: the completion executor and the clock must outlive the queue, and
|
||||
// the executor must keep accepting completions until every sleeper settled by
|
||||
// `close()` / `~TimerQueue()` has been resumed. A `TimerHandle` may safely
|
||||
// outlive the queue. A suspended sleep task may be destroyed only while its
|
||||
// timer is still pending and the destruction is serialized with poll, close
|
||||
// and stop; once its timer has been settled (fired, cancelled or closed) the
|
||||
// task must stay alive until its posted resume has run. Shutdown order:
|
||||
// `close()`, then drain the completion executor, then destroy sleep tasks.
|
||||
// `close()` does not wait for callbacks already claimed by a concurrent
|
||||
// `poll_expired()` or for a stop callback mid-settle; they may still post
|
||||
// after `close()` returns.
|
||||
|
||||
namespace Void::Async
|
||||
{
|
||||
|
||||
struct TimerQueueOptions {
|
||||
// Maximum number of simultaneously pending timers (sleepers included).
|
||||
// Zero is rejected by TimerQueue::create with invalid_argument.
|
||||
std::size_t max_timers{1024};
|
||||
};
|
||||
|
||||
enum class TimerEvent : std::uint8_t {
|
||||
expired,
|
||||
closed
|
||||
};
|
||||
|
||||
using TimerCallback = std::move_only_function<void(TimerEvent) noexcept>;
|
||||
|
||||
class TimerHandle;
|
||||
class TimerQueue;
|
||||
|
||||
namespace detail
|
||||
{
|
||||
|
||||
enum class TimerEntryState : std::uint8_t {
|
||||
pending,
|
||||
fired,
|
||||
cancelled
|
||||
};
|
||||
|
||||
class TimerCore;
|
||||
|
||||
// Shared per-timer state. The single atomic pending -> {fired, cancelled}
|
||||
// transition decides the timer's fate; the transition winner exclusively owns
|
||||
// `callback` afterwards (fire/close: invoke then destroy; cancel: destroy).
|
||||
struct TimerEntry {
|
||||
TimerEntry(TimerCallback cb, std::weak_ptr<TimerCore> owner) noexcept
|
||||
: callback(std::move(cb))
|
||||
, core(std::move(owner))
|
||||
{
|
||||
}
|
||||
|
||||
TimerEntry(const TimerEntry&) = delete;
|
||||
TimerEntry& operator=(const TimerEntry&) = delete;
|
||||
|
||||
[[nodiscard]] bool try_leave_pending(TimerEntryState to) noexcept
|
||||
{
|
||||
TimerEntryState expected = TimerEntryState::pending;
|
||||
return state.compare_exchange_strong(
|
||||
expected, to, std::memory_order_acq_rel, std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_pending() const noexcept
|
||||
{
|
||||
return state.load(std::memory_order_acquire) == TimerEntryState::pending;
|
||||
}
|
||||
|
||||
std::atomic<TimerEntryState> state{TimerEntryState::pending};
|
||||
TimerCallback callback;
|
||||
// Weak: the heap owns entries, so a strong back-reference would form a
|
||||
// core -> heap -> entry -> core cycle.
|
||||
std::weak_ptr<TimerCore> core;
|
||||
};
|
||||
|
||||
struct TimerNode {
|
||||
Void::Time::MonotonicClock::time_point deadline{};
|
||||
std::uint64_t seq{0};
|
||||
std::shared_ptr<TimerEntry> entry{};
|
||||
};
|
||||
|
||||
// Heap comparator: std::*_heap build max-heaps, so "later" yields a min-heap
|
||||
// on (deadline, seq).
|
||||
struct TimerNodeLater {
|
||||
[[nodiscard]] bool operator()(const TimerNode& a, const TimerNode& b) const noexcept
|
||||
{
|
||||
if (a.deadline != b.deadline) {
|
||||
return a.deadline > b.deadline;
|
||||
}
|
||||
return a.seq > b.seq;
|
||||
}
|
||||
};
|
||||
|
||||
// Shared queue core. Owned by the TimerQueue and by in-flight sleep frames;
|
||||
// referenced weakly by entries so TimerHandle::cancel() stays valid after the
|
||||
// queue is gone.
|
||||
//
|
||||
// Invariants (under mu_): every pending entry is in heap_; heap_ holds only
|
||||
// pending entries and cancelled tombstones; heap_.size() == live_ +
|
||||
// tombstones_; live_ <= max_timers_; tombstones are compacted away before an
|
||||
// admission whenever they exceed max_timers_, so heap_.size() <= 2*max_timers_.
|
||||
// No user code (callbacks, callback destructors, clock reads) runs under mu_.
|
||||
class TimerCore : public std::enable_shared_from_this<TimerCore>
|
||||
{
|
||||
public:
|
||||
using time_point = Void::Time::MonotonicClock::time_point;
|
||||
|
||||
TimerCore(Executor& executor,
|
||||
const Void::Time::MonotonicClock& clock,
|
||||
std::size_t max_timers) noexcept
|
||||
: executor_(executor)
|
||||
, clock_(clock)
|
||||
, max_timers_(max_timers)
|
||||
{
|
||||
}
|
||||
|
||||
TimerCore(const TimerCore&) = delete;
|
||||
TimerCore& operator=(const TimerCore&) = delete;
|
||||
|
||||
[[nodiscard]] Executor& executor() noexcept { return executor_; }
|
||||
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept { return clock_; }
|
||||
|
||||
[[nodiscard]] bool is_closed() const noexcept
|
||||
{
|
||||
return closed_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t live() const noexcept
|
||||
{
|
||||
return live_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<std::shared_ptr<TimerEntry>, AdmissionError>
|
||||
admit(time_point when, TimerCallback callback)
|
||||
{
|
||||
if (closed_.load(std::memory_order_acquire)) {
|
||||
return std::unexpected{AdmissionError::stopped};
|
||||
}
|
||||
// Declared before the lock: on rejection the entry (and the caller's
|
||||
// callback inside it) is destroyed after the lock is released.
|
||||
auto entry = std::make_shared<TimerEntry>(std::move(callback), weak_from_this());
|
||||
std::lock_guard lk{mu_};
|
||||
if (closed_.load(std::memory_order_relaxed)) {
|
||||
return std::unexpected{AdmissionError::stopped};
|
||||
}
|
||||
if (live_.load(std::memory_order_relaxed) >= max_timers_) {
|
||||
return std::unexpected{AdmissionError::overloaded};
|
||||
}
|
||||
if (tombstones_ > max_timers_) {
|
||||
compact_locked();
|
||||
}
|
||||
heap_.push_back(TimerNode{when, next_seq_, entry});
|
||||
std::push_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
|
||||
++next_seq_;
|
||||
live_.fetch_add(1, std::memory_order_acq_rel);
|
||||
return entry;
|
||||
}
|
||||
|
||||
// pending -> cancelled under the lock (serialized with poll/close/compact).
|
||||
[[nodiscard]] bool cancel_transition(TimerEntry& entry) noexcept
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
if (!entry.try_leave_pending(TimerEntryState::cancelled)) {
|
||||
return false;
|
||||
}
|
||||
live_.fetch_sub(1, std::memory_order_acq_rel);
|
||||
++tombstones_;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t poll_expired()
|
||||
{
|
||||
const time_point now = clock_.now();
|
||||
std::vector<std::shared_ptr<TimerEntry>> due;
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
while (!heap_.empty() && !(now < heap_.front().deadline)) {
|
||||
if (due.size() == due.capacity()) {
|
||||
// Reserve before popping so a fired entry always has a
|
||||
// slot; under allocation failure the rest stays queued for
|
||||
// the next poll instead of being lost.
|
||||
try {
|
||||
due.reserve(due.empty() ? std::size_t{8} : due.size() * 2);
|
||||
} catch (...) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::pop_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
|
||||
std::shared_ptr<TimerEntry> entry = std::move(heap_.back().entry);
|
||||
heap_.pop_back();
|
||||
if (entry->try_leave_pending(TimerEntryState::fired)) {
|
||||
live_.fetch_sub(1, std::memory_order_acq_rel);
|
||||
due.push_back(std::move(entry));
|
||||
} else {
|
||||
// Cancelled tombstone; cancel() already took its callback.
|
||||
--tombstones_;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto& entry : due) {
|
||||
invoke_and_release(*entry, TimerEvent::expired);
|
||||
}
|
||||
return due.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<time_point> next_deadline()
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
prune_top_locked();
|
||||
if (heap_.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return heap_.front().deadline;
|
||||
}
|
||||
|
||||
void close() noexcept
|
||||
{
|
||||
std::vector<TimerNode> drained;
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
if (closed_.load(std::memory_order_relaxed)) {
|
||||
return;
|
||||
}
|
||||
closed_.store(true, std::memory_order_release);
|
||||
drained.swap(heap_);
|
||||
tombstones_ = 0;
|
||||
std::size_t kept = 0;
|
||||
for (auto& node : drained) {
|
||||
if (node.entry->try_leave_pending(TimerEntryState::fired)) {
|
||||
if (&drained[kept] != &node) {
|
||||
drained[kept] = std::move(node);
|
||||
}
|
||||
++kept;
|
||||
}
|
||||
}
|
||||
drained.erase(drained.begin() + static_cast<std::ptrdiff_t>(kept),
|
||||
drained.end());
|
||||
live_.store(0, std::memory_order_release);
|
||||
}
|
||||
std::sort(drained.begin(), drained.end(),
|
||||
[](const TimerNode& a, const TimerNode& b) noexcept {
|
||||
return TimerNodeLater{}(b, a);
|
||||
});
|
||||
for (auto& node : drained) {
|
||||
invoke_and_release(*node.entry, TimerEvent::closed);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static void invoke_and_release(TimerEntry& entry, TimerEvent event) noexcept
|
||||
{
|
||||
// Move the callback to this stack frame so it outlives anything the
|
||||
// invocation may destroy, and is released after it returns.
|
||||
TimerCallback callback{std::move(entry.callback)};
|
||||
entry.callback = nullptr;
|
||||
if (callback) {
|
||||
callback(event);
|
||||
}
|
||||
}
|
||||
|
||||
void prune_top_locked() noexcept
|
||||
{
|
||||
while (!heap_.empty() && !heap_.front().entry->is_pending()) {
|
||||
std::pop_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
|
||||
heap_.pop_back();
|
||||
--tombstones_;
|
||||
}
|
||||
}
|
||||
|
||||
void compact_locked() noexcept
|
||||
{
|
||||
std::erase_if(heap_, [](const TimerNode& node) noexcept {
|
||||
return !node.entry->is_pending();
|
||||
});
|
||||
std::make_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
|
||||
tombstones_ = 0;
|
||||
}
|
||||
|
||||
Executor& executor_;
|
||||
const Void::Time::MonotonicClock& clock_;
|
||||
const std::size_t max_timers_;
|
||||
std::mutex mu_{};
|
||||
std::vector<TimerNode> heap_{};
|
||||
std::uint64_t next_seq_{0};
|
||||
std::size_t tombstones_{0};
|
||||
std::atomic<std::size_t> live_{0};
|
||||
std::atomic<bool> closed_{false};
|
||||
};
|
||||
|
||||
[[nodiscard]] inline bool cancel_timer_entry(TimerEntry& entry) noexcept
|
||||
{
|
||||
bool won = false;
|
||||
if (auto core = entry.core.lock()) {
|
||||
won = core->cancel_transition(entry);
|
||||
} else {
|
||||
// The core is gone only after close() moved every pending entry to
|
||||
// `fired`, so this transition is expected to fail; it is still the
|
||||
// authoritative check.
|
||||
won = entry.try_leave_pending(TimerEntryState::cancelled);
|
||||
}
|
||||
if (won) {
|
||||
// The cancel winner owns the callback: release it now, outside the
|
||||
// queue lock, so a cancelled tombstone retains no user state.
|
||||
TimerCallback discarded{std::move(entry.callback)};
|
||||
entry.callback = nullptr;
|
||||
}
|
||||
return won;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
// Move-only reference to one scheduled timer. Destroying or overwriting a
|
||||
// handle does NOT cancel the timer (the timer is detached and still fires).
|
||||
class TimerHandle
|
||||
{
|
||||
public:
|
||||
TimerHandle() noexcept = default;
|
||||
TimerHandle(TimerHandle&&) noexcept = default;
|
||||
TimerHandle& operator=(TimerHandle&&) noexcept = default;
|
||||
TimerHandle(const TimerHandle&) = delete;
|
||||
TimerHandle& operator=(const TimerHandle&) = delete;
|
||||
~TimerHandle() = default;
|
||||
|
||||
// Returns true when this call moved the timer from pending to cancelled:
|
||||
// the callback will never run and has already been destroyed (released
|
||||
// outside the queue lock) when cancel() returns.
|
||||
//
|
||||
// Returns false when the handle is empty, the timer was already cancelled,
|
||||
// or the callback has fired / is firing (expired or closed). false does
|
||||
// NOT mean the callback has finished running: it may still be executing on
|
||||
// the polling or closing thread. A callback that touches state which may
|
||||
// be destroyed after a failed cancel() (e.g. a waiter node inside a
|
||||
// coroutine frame) must capture shared ownership of that state, or look it
|
||||
// up under the owner's own lock; it must never hold a raw pointer into a
|
||||
// frame. Safe to call after the TimerQueue was destroyed (returns false,
|
||||
// since destruction already delivered TimerEvent::closed).
|
||||
//
|
||||
// WARNING: when cancel() returns true (and when schedule_at() rejects a
|
||||
// timer) the callback object is destroyed synchronously on the caller's
|
||||
// thread. Do not call cancel() while holding a lock L if the callback may
|
||||
// hold the last reference to something whose destructor takes or waits on
|
||||
// L (e.g. a std::stop_callback whose callback blocks on L): move the
|
||||
// handle out under the lock and cancel after unlocking, or make the
|
||||
// callback hold only a weak/non-last reference.
|
||||
bool cancel() noexcept
|
||||
{
|
||||
return entry_ ? detail::cancel_timer_entry(*entry_) : false;
|
||||
}
|
||||
|
||||
// True when the handle refers to a timer (i.e. it was returned by
|
||||
// schedule_at and not moved from); unaffected by the timer's state.
|
||||
[[nodiscard]] bool valid() const noexcept { return entry_ != nullptr; }
|
||||
|
||||
private:
|
||||
friend class TimerQueue;
|
||||
|
||||
explicit TimerHandle(std::shared_ptr<detail::TimerEntry> entry) noexcept
|
||||
: entry_(std::move(entry))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<detail::TimerEntry> entry_{};
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
|
||||
struct TimerSleepTarget {
|
||||
bool relative{false};
|
||||
Void::Time::MonotonicClock::time_point when{};
|
||||
std::chrono::nanoseconds delta{};
|
||||
};
|
||||
|
||||
// Stop callback for a pending sleep. The entry's pending -> cancelled
|
||||
// transition is the arbiter: the sleep settles `cancelled` only when this
|
||||
// callback won it; otherwise the timer callback (expired/closed) settles it.
|
||||
class TimerSleepStop
|
||||
{
|
||||
public:
|
||||
TimerSleepStop(std::shared_ptr<TimerEntry> entry,
|
||||
std::shared_ptr<OperationState<void>> state) noexcept
|
||||
: entry_(std::move(entry))
|
||||
, state_(std::move(state))
|
||||
{
|
||||
}
|
||||
|
||||
void operator()() const noexcept
|
||||
{
|
||||
// Copy first: once the continuation is dispatched, the frame that
|
||||
// owns this callback object may resume and be destroyed.
|
||||
auto entry = entry_;
|
||||
auto state = state_;
|
||||
if (cancel_timer_entry(*entry)) {
|
||||
if (auto ticket = state->try_commit_cancelled("TimerQueue sleep cancelled");
|
||||
ticket.has_value()) {
|
||||
ticket->dispatch();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<TimerEntry> entry_;
|
||||
std::shared_ptr<OperationState<void>> state_;
|
||||
};
|
||||
|
||||
// Cancels the sleep's timer when the frame ends, including destruction of a
|
||||
// suspended sleep task, so an abandoned frame is never resumed by a later
|
||||
// poll or close (unless the timer already fired).
|
||||
struct TimerSleepGuard {
|
||||
std::shared_ptr<TimerEntry> entry{};
|
||||
|
||||
TimerSleepGuard() noexcept = default;
|
||||
explicit TimerSleepGuard(std::shared_ptr<TimerEntry> e) noexcept : entry(std::move(e)) {}
|
||||
TimerSleepGuard(const TimerSleepGuard&) = delete;
|
||||
TimerSleepGuard& operator=(const TimerSleepGuard&) = delete;
|
||||
|
||||
~TimerSleepGuard()
|
||||
{
|
||||
if (entry) {
|
||||
(void)cancel_timer_entry(*entry);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error timer_admission_error(AdmissionError error)
|
||||
{
|
||||
if (error == AdmissionError::overloaded) {
|
||||
return make_async_error(AdmissionError::overloaded, "TimerQueue capacity exceeded");
|
||||
}
|
||||
if (error == AdmissionError::stopped) {
|
||||
return make_async_error(AdmissionError::stopped, "TimerQueue is closed");
|
||||
}
|
||||
return make_async_error(error);
|
||||
}
|
||||
|
||||
// The sleep body is a free coroutine holding the core by value: it never
|
||||
// touches the TimerQueue object, so a lazily started or suspended sleep task
|
||||
// may outlive the queue.
|
||||
inline Coro::Task<Void::Result::Result<void>> timer_sleep(
|
||||
std::shared_ptr<TimerCore> core,
|
||||
TimerSleepTarget target,
|
||||
OperationOptions options)
|
||||
{
|
||||
using Void::Result::Result;
|
||||
|
||||
if (options.stop.stop_requested()) {
|
||||
co_return Result<void>{std::unexpect, make_async_error(
|
||||
AsyncErrorCode::cancelled, "TimerQueue sleep cancelled before admission")};
|
||||
}
|
||||
if (core->is_closed()) {
|
||||
co_return Result<void>{std::unexpect, timer_admission_error(AdmissionError::stopped)};
|
||||
}
|
||||
|
||||
// Single read of the injected clock; the host clock is never consulted.
|
||||
const auto now = core->clock().now();
|
||||
const auto when =
|
||||
target.relative ? Void::Time::saturating_add(now, target.delta) : target.when;
|
||||
if (options.deadline.has_value() && now >= *options.deadline) {
|
||||
co_return Result<void>{std::unexpect, make_async_error(
|
||||
AsyncErrorCode::timeout, "TimerQueue sleep deadline expired before admission")};
|
||||
}
|
||||
|
||||
// One timer per sleeper at min(when, deadline); the outcome is fixed at
|
||||
// registration: timeout only when the deadline is strictly earlier.
|
||||
const bool deadline_first = options.deadline.has_value() && *options.deadline < when;
|
||||
const auto fire_at = deadline_first ? *options.deadline : when;
|
||||
|
||||
// Non-null resume executor: every dispatch goes through post_completion.
|
||||
auto state = OperationState<void>::create(OperationOptions{}, &core->executor());
|
||||
auto admitted = core->admit(
|
||||
fire_at,
|
||||
TimerCallback{[state, deadline_first](TimerEvent event) noexcept {
|
||||
std::optional<ResumeTicket> ticket;
|
||||
if (event == TimerEvent::closed) {
|
||||
ticket = state->try_commit_error(
|
||||
make_async_error(AsyncErrorCode::stopped, "TimerQueue closed while sleeping"),
|
||||
DomainOutcomeKind::cancelled);
|
||||
} else if (deadline_first) {
|
||||
ticket = state->try_commit_timeout("TimerQueue sleep deadline expired");
|
||||
} else {
|
||||
ticket = state->try_commit_value();
|
||||
}
|
||||
if (ticket.has_value()) {
|
||||
ticket->dispatch();
|
||||
}
|
||||
}});
|
||||
if (!admitted.has_value()) {
|
||||
co_return Result<void>{std::unexpect, timer_admission_error(admitted.error())};
|
||||
}
|
||||
|
||||
TimerSleepGuard guard{std::move(*admitted)};
|
||||
// Registered after admission so it can cancel the timer. If stop was
|
||||
// requested meanwhile, the constructor runs the callback inline; the
|
||||
// state then settles before suspension and the co_await completes
|
||||
// without suspending (no inline resume of a suspended frame).
|
||||
std::optional<std::stop_callback<TimerSleepStop>> stop_cb;
|
||||
if (options.stop.stop_possible()) {
|
||||
stop_cb.emplace(options.stop, TimerSleepStop{guard.entry, state});
|
||||
}
|
||||
|
||||
auto result = co_await state->awaitable(nullptr);
|
||||
// Waits for a concurrently running stop callback before the frame moves on.
|
||||
stop_cb.reset();
|
||||
co_return result;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
class TimerQueue
|
||||
{
|
||||
public:
|
||||
using time_point = Void::Time::MonotonicClock::time_point;
|
||||
|
||||
// Errors: invalid_argument when options.max_timers == 0.
|
||||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
|
||||
create(Executor& completion_executor,
|
||||
const Void::Time::MonotonicClock& clock,
|
||||
TimerQueueOptions options = {})
|
||||
{
|
||||
if (options.max_timers == 0) {
|
||||
return std::unexpected{make_async_error(
|
||||
AsyncErrorCode::invalid_argument,
|
||||
"TimerQueue max_timers must be greater than zero")};
|
||||
}
|
||||
auto core = std::make_shared<detail::TimerCore>(
|
||||
completion_executor, clock, options.max_timers);
|
||||
return std::unique_ptr<TimerQueue>(new TimerQueue(std::move(core)));
|
||||
}
|
||||
|
||||
TimerQueue(const TimerQueue&) = delete;
|
||||
TimerQueue& operator=(const TimerQueue&) = delete;
|
||||
TimerQueue(TimerQueue&&) = delete;
|
||||
TimerQueue& operator=(TimerQueue&&) = delete;
|
||||
|
||||
// Equivalent to close(): pending callbacks receive TimerEvent::closed and
|
||||
// pending sleepers settle `stopped` (resumed via the completion executor).
|
||||
~TimerQueue() { close(); }
|
||||
|
||||
// Suspends until `when` (in the injected clock domain) has been reached
|
||||
// and observed by poll_expired(). A `when` already in the past still needs
|
||||
// a poll. Results (exactly one):
|
||||
// {} — the timer fired at `when`;
|
||||
// cancelled — options.stop requested (before admission or while pending);
|
||||
// timeout — options.deadline is already expired at admission, or
|
||||
// is strictly earlier than `when` and fired first;
|
||||
// overloaded — max_timers pending timers already;
|
||||
// stopped — the queue is (or becomes) closed.
|
||||
// Checks before admission complete without suspending. A suspended sleep
|
||||
// is always resumed via executor().post_completion. Destroying a suspended
|
||||
// sleep task cancels its timer only while the timer is still pending (see
|
||||
// the lifetime rules at the top of this header); after settlement the task
|
||||
// must outlive its posted resume.
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>>
|
||||
sleep_until(time_point when, OperationOptions options = {})
|
||||
{
|
||||
return detail::timer_sleep(
|
||||
core_, detail::TimerSleepTarget{false, when, {}}, std::move(options));
|
||||
}
|
||||
|
||||
// sleep_until(saturating_add(clock().now(), duration)); "now" is read when
|
||||
// the task starts. Negative or huge durations saturate instead of wrapping.
|
||||
[[nodiscard]] Coro::Task<Void::Result::Result<void>>
|
||||
sleep_for(std::chrono::nanoseconds duration, OperationOptions options = {})
|
||||
{
|
||||
return detail::timer_sleep(
|
||||
core_, detail::TimerSleepTarget{true, {}, duration}, std::move(options));
|
||||
}
|
||||
|
||||
// Schedules `on_event` to run exactly once with TimerEvent::expired (from
|
||||
// poll_expired at or after `when`) or TimerEvent::closed (from close or
|
||||
// destruction), or never when TimerHandle::cancel() returns true.
|
||||
// Errors: invalid_argument (empty callback), overloaded (max_timers
|
||||
// pending), stopped (closed). On error the callback is destroyed unrun.
|
||||
[[nodiscard]] std::expected<TimerHandle, AdmissionError>
|
||||
schedule_at(time_point when, TimerCallback on_event)
|
||||
{
|
||||
if (!on_event) {
|
||||
return std::unexpected{AdmissionError::invalid_argument};
|
||||
}
|
||||
auto admitted = core_->admit(when, std::move(on_event));
|
||||
if (!admitted.has_value()) {
|
||||
return std::unexpected{admitted.error()};
|
||||
}
|
||||
return TimerHandle{std::move(*admitted)};
|
||||
}
|
||||
|
||||
// Reads clock().now() once, removes every pending timer whose deadline is
|
||||
// <= now in (deadline, seq) order, then runs their callbacks outside the
|
||||
// internal lock. Timers scheduled by those callbacks fire on a later poll.
|
||||
// Returns the number of callbacks fired.
|
||||
[[nodiscard]] std::size_t poll_expired() { return core_->poll_expired(); }
|
||||
|
||||
// Earliest pending deadline (cancelled timers are skipped).
|
||||
[[nodiscard]] std::optional<time_point> next_deadline() const
|
||||
{
|
||||
return core_->next_deadline();
|
||||
}
|
||||
|
||||
// Time until the next pending deadline measured with the injected clock,
|
||||
// clamped to [0, max_wait]; 0 when a timer is already due; max_wait when
|
||||
// nothing is pending.
|
||||
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept
|
||||
{
|
||||
const auto cap = max_wait < std::chrono::nanoseconds::zero()
|
||||
? std::chrono::nanoseconds::zero()
|
||||
: max_wait;
|
||||
const auto next = core_->next_deadline();
|
||||
if (!next.has_value()) {
|
||||
return cap;
|
||||
}
|
||||
return std::min(Void::Time::remaining_until(core_->clock(), *next), cap);
|
||||
}
|
||||
|
||||
// Number of pending timers (sleepers included); cancelled timers excluded.
|
||||
[[nodiscard]] std::size_t active_timers() const noexcept { return core_->live(); }
|
||||
|
||||
// Idempotent. Marks the queue closed (later schedule_at/sleep_* return
|
||||
// stopped), then runs every pending callback once with TimerEvent::closed
|
||||
// in (deadline, seq) order, outside the internal lock.
|
||||
void close() noexcept { core_->close(); }
|
||||
|
||||
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept
|
||||
{
|
||||
return core_->clock();
|
||||
}
|
||||
|
||||
[[nodiscard]] Executor& executor() noexcept { return core_->executor(); }
|
||||
|
||||
private:
|
||||
explicit TimerQueue(std::shared_ptr<detail::TimerCore> core) noexcept
|
||||
: core_(std::move(core))
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<detail::TimerCore> core_;
|
||||
};
|
||||
|
||||
} // namespace Void::Async
|
||||
@@ -1,13 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/RetryState.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <stop_token>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Retry
|
||||
{
|
||||
@@ -72,8 +82,7 @@ namespace Void::Retry
|
||||
// any backoff to randomize its delay and avoid thundering-herd retries.
|
||||
// Full: uniform in [0, base]
|
||||
// Equal: base/2 + uniform in [0, base/2] (keeps a guaranteed floor)
|
||||
|
||||
enum class JitterMode { Full, Equal };
|
||||
// JitterMode is defined in RetryState.hpp (same name, same namespace).
|
||||
|
||||
template <typename Backoff = ExponentialBackoff> struct Jittered {
|
||||
Backoff inner{};
|
||||
@@ -210,4 +219,174 @@ namespace Void::Retry
|
||||
return last;
|
||||
}
|
||||
|
||||
// ── retry_blocking — named blocking adapter over RetryState
|
||||
// ────────────────── Drives a RetryState with an injected clock and sleeper,
|
||||
// so the retry schedule is testable without real time. Unlike the 1.x
|
||||
// `retry`, an invalid spec (including max_attempts == 0) is reported as an
|
||||
// error and never as a success, and the result says why retrying stopped.
|
||||
|
||||
// Clock for production use.
|
||||
struct SteadyNow {
|
||||
[[nodiscard]] SteadyTimePoint operator()() const noexcept
|
||||
{
|
||||
return std::chrono::steady_clock::now();
|
||||
}
|
||||
};
|
||||
|
||||
// Blocks the calling thread for `wait` or until `stop` is requested.
|
||||
// Returns false when the wait was cut short by a stop request. A zero or
|
||||
// negative `wait` returns immediately without blocking.
|
||||
struct ThreadSleep {
|
||||
bool operator()(std::chrono::nanoseconds wait,
|
||||
std::stop_token stop) const
|
||||
{
|
||||
if (stop.stop_requested()) {
|
||||
return false;
|
||||
}
|
||||
if (wait <= std::chrono::nanoseconds::zero()) {
|
||||
return true;
|
||||
}
|
||||
std::mutex mutex;
|
||||
std::condition_variable_any cv;
|
||||
std::unique_lock lock{mutex};
|
||||
const SteadyTimePoint until =
|
||||
saturating_add(std::chrono::steady_clock::now(), wait);
|
||||
// The predicate is "stop requested": the call returns when it
|
||||
// becomes true or when `until` passes.
|
||||
(void)cv.wait_until(lock, stop, until, [&stop] {
|
||||
return stop.stop_requested();
|
||||
});
|
||||
return !stop.stop_requested();
|
||||
}
|
||||
};
|
||||
|
||||
// NowFn: SteadyTimePoint()
|
||||
// SleepFn: bool(std::chrono::nanoseconds wait, std::stop_token)
|
||||
// false means the wait was interrupted by a stop request
|
||||
// Classify: AttemptOutcome(const E&) for the error type E of the callable
|
||||
// URBG: random engine used for jitter (seeded from random_device by
|
||||
// default)
|
||||
// deadline: optional absolute admission deadline; the effective deadline
|
||||
// is the earlier of it and the spec's budget.
|
||||
template <class NowFn = SteadyNow, class SleepFn = ThreadSleep,
|
||||
class Classify = RetryEveryError, class URBG = std::mt19937_64>
|
||||
struct BlockingRetryOptions {
|
||||
NowFn now{};
|
||||
SleepFn sleep{};
|
||||
Classify classify{};
|
||||
URBG urbg = detail::seeded_engine<URBG>();
|
||||
std::stop_token stop{};
|
||||
std::optional<SteadyTimePoint> deadline{};
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
template <class R> struct expected_traits;
|
||||
|
||||
template <class T, class E> struct expected_traits<std::expected<T, E>> {
|
||||
using value_type = T;
|
||||
using error_type = E;
|
||||
};
|
||||
|
||||
template <class F>
|
||||
using blocking_result_t = std::expected<
|
||||
typename expected_traits<
|
||||
std::remove_cvref_t<std::invoke_result_t<F&>>>::value_type,
|
||||
RetryError<typename expected_traits<
|
||||
std::remove_cvref_t<std::invoke_result_t<F&>>>::error_type>>;
|
||||
} // namespace detail
|
||||
|
||||
// Runs `fn` (callable returning std::expected<T, E>) until it succeeds or
|
||||
// RetryState says to stop.
|
||||
// success -> the value of the successful attempt
|
||||
// invalid spec -> RetryError{config = error, attempts = 0},
|
||||
// `fn` is never called
|
||||
// anything else that stops -> RetryError{reason, attempts, last_error}
|
||||
// Waits are `decision.at - now()` (never negative) handed to `sleep`
|
||||
// together with `options.stop`; when `sleep` returns false the call ends
|
||||
// with stop_requested and no further attempt. `T` may be move-only.
|
||||
template <class F, class NowFn = SteadyNow, class SleepFn = ThreadSleep,
|
||||
class Classify = RetryEveryError, class URBG = std::mt19937_64>
|
||||
requires std::invocable<F&>
|
||||
[[nodiscard]] auto
|
||||
retry_blocking(const RetrySpec& spec, F&& fn,
|
||||
BlockingRetryOptions<NowFn, SleepFn, Classify, URBG>
|
||||
options = {}) -> detail::blocking_result_t<F>
|
||||
{
|
||||
using Result = std::remove_cvref_t<std::invoke_result_t<F&>>;
|
||||
using T = typename detail::expected_traits<Result>::value_type;
|
||||
using E = typename detail::expected_traits<Result>::error_type;
|
||||
using Error = RetryError<E>;
|
||||
using Out = std::expected<T, Error>;
|
||||
static_assert(
|
||||
std::is_invocable_r_v<AttemptOutcome, Classify&, const E&>,
|
||||
"Classify must be callable as AttemptOutcome(const E&)");
|
||||
|
||||
if (const auto valid = validate(spec); !valid) {
|
||||
return Out(std::unexpect,
|
||||
Error{RetryStopReason::none, 0, std::nullopt,
|
||||
valid.error()});
|
||||
}
|
||||
|
||||
const SteadyTimePoint start = options.now();
|
||||
auto created = RetryState<URBG>::create(
|
||||
spec, start, std::move(options.urbg), options.deadline);
|
||||
if (!created.has_value()) { // unreachable after validate()
|
||||
return Out(std::unexpect,
|
||||
Error{RetryStopReason::none, 0, std::nullopt,
|
||||
created.error()});
|
||||
}
|
||||
RetryState<URBG>& state = *created;
|
||||
|
||||
std::optional<E> last_error;
|
||||
RetryDecision decision =
|
||||
state.begin(start, options.stop.stop_requested());
|
||||
for (;;) {
|
||||
if (decision.action == RetryAction::attempt) {
|
||||
auto result = fn();
|
||||
if (result.has_value()) {
|
||||
(void)state.succeed();
|
||||
if constexpr (std::is_void_v<T>) {
|
||||
return Out{};
|
||||
} else {
|
||||
return Out(std::in_place, std::move(*result));
|
||||
}
|
||||
}
|
||||
last_error.emplace(std::move(result).error());
|
||||
const AttemptOutcome outcome =
|
||||
options.classify(std::as_const(*last_error));
|
||||
decision = state.next(options.now(), outcome,
|
||||
options.stop.stop_requested());
|
||||
} else if (decision.action == RetryAction::wait_until) {
|
||||
const SteadyTimePoint now = options.now();
|
||||
std::chrono::nanoseconds wait = std::chrono::nanoseconds::zero();
|
||||
if (decision.at > now) {
|
||||
// Saturating `at - now`: an injected clock may step backwards
|
||||
// to a negative epoch while `at` is near max().
|
||||
using Rep = SteadyTimePoint::duration::rep;
|
||||
const Rep at_ticks = decision.at.time_since_epoch().count();
|
||||
const Rep now_ticks = now.time_since_epoch().count();
|
||||
const bool overflows = now_ticks < 0 &&
|
||||
at_ticks > std::numeric_limits<Rep>::max() + now_ticks;
|
||||
wait = overflows
|
||||
? std::chrono::nanoseconds::max()
|
||||
: std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
SteadyTimePoint::duration{at_ticks - now_ticks});
|
||||
}
|
||||
if (!options.sleep(wait, options.stop)) {
|
||||
return Out(std::unexpect,
|
||||
Error{RetryStopReason::stop_requested,
|
||||
state.attempts_started(),
|
||||
std::move(last_error), std::nullopt});
|
||||
}
|
||||
decision = state.resume(options.now(),
|
||||
options.stop.stop_requested());
|
||||
} else {
|
||||
return Out(std::unexpect,
|
||||
Error{decision.reason, decision.attempts_started,
|
||||
std::move(last_error), std::nullopt});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Void::Retry
|
||||
@@ -0,0 +1,416 @@
|
||||
#pragma once
|
||||
|
||||
// Pure retry decision engine.
|
||||
//
|
||||
// Standard-library only: it pulls in no threading header and no other Void
|
||||
// header. Nothing in this header reads a clock, sleeps or calls user code:
|
||||
// callers pass the current time in and carry out the returned decision
|
||||
// themselves. The blocking adapter
|
||||
// lives in Retry.hpp (`retry_blocking`); asynchronous adapters live in the
|
||||
// modules that own a timer.
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace Void::Retry
|
||||
{
|
||||
|
||||
using SteadyTimePoint = std::chrono::steady_clock::time_point;
|
||||
|
||||
// ── Jitter
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// Full: uniform in [0, d]
|
||||
// Equal: d/2 + uniform in [0, d - d/2] (keeps a guaranteed floor)
|
||||
// (Relocated from Retry.hpp; name and namespace are unchanged.)
|
||||
|
||||
enum class JitterMode { Full, Equal };
|
||||
|
||||
// ── Specification
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
// Explicit "no total time budget" marker for RetrySpec::budget.
|
||||
struct NoDeadline {
|
||||
constexpr bool operator==(const NoDeadline&) const noexcept
|
||||
= default;
|
||||
};
|
||||
|
||||
inline constexpr NoDeadline no_deadline{};
|
||||
|
||||
struct BackoffSpec {
|
||||
// Delay before the first retry.
|
||||
std::chrono::nanoseconds initial{std::chrono::milliseconds{100}};
|
||||
// Upper bound on any single (unjittered) delay.
|
||||
std::chrono::nanoseconds cap{std::chrono::seconds{30}};
|
||||
// Growth factor between consecutive retries; finite and >= 1.
|
||||
double multiplier{2.0};
|
||||
// Randomisation applied to every non-zero delay.
|
||||
std::optional<JitterMode> jitter{};
|
||||
};
|
||||
|
||||
struct RetrySpec {
|
||||
// Total attempts including the first one; must be >= 1.
|
||||
std::uint32_t max_attempts{3};
|
||||
// Total time budget measured from the start of the operation, or
|
||||
// `no_deadline`. A zero or negative duration is invalid.
|
||||
std::variant<std::chrono::nanoseconds, NoDeadline> budget{
|
||||
std::chrono::seconds{30}};
|
||||
BackoffSpec backoff{};
|
||||
};
|
||||
|
||||
enum class RetryConfigError : std::uint8_t {
|
||||
zero_attempts,
|
||||
negative_duration,
|
||||
zero_budget,
|
||||
nonfinite_multiplier,
|
||||
multiplier_below_one,
|
||||
cap_below_initial,
|
||||
};
|
||||
|
||||
// ── Decisions
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
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};
|
||||
// Absolute time to wait until; meaningful for `wait_until` only.
|
||||
SteadyTimePoint at{};
|
||||
RetryStopReason reason{RetryStopReason::none};
|
||||
// Attempts that have been started so far.
|
||||
std::uint32_t attempts_started{0};
|
||||
};
|
||||
|
||||
// Validation order (first failing check wins): zero_attempts,
|
||||
// negative_duration (initial, cap or budget < 0), zero_budget,
|
||||
// nonfinite_multiplier, multiplier_below_one, cap_below_initial.
|
||||
[[nodiscard]] inline std::expected<void, RetryConfigError>
|
||||
validate(const RetrySpec& spec) noexcept
|
||||
{
|
||||
using std::chrono::nanoseconds;
|
||||
if (spec.max_attempts == 0) {
|
||||
return std::unexpected{RetryConfigError::zero_attempts};
|
||||
}
|
||||
const nanoseconds* const budget =
|
||||
std::get_if<nanoseconds>(&spec.budget);
|
||||
if (spec.backoff.initial < nanoseconds::zero() ||
|
||||
spec.backoff.cap < nanoseconds::zero() ||
|
||||
(budget != nullptr && *budget < nanoseconds::zero())) {
|
||||
return std::unexpected{RetryConfigError::negative_duration};
|
||||
}
|
||||
if (budget != nullptr && *budget == nanoseconds::zero()) {
|
||||
return std::unexpected{RetryConfigError::zero_budget};
|
||||
}
|
||||
if (!std::isfinite(spec.backoff.multiplier)) {
|
||||
return std::unexpected{RetryConfigError::nonfinite_multiplier};
|
||||
}
|
||||
if (spec.backoff.multiplier < 1.0) {
|
||||
return std::unexpected{RetryConfigError::multiplier_below_one};
|
||||
}
|
||||
if (spec.backoff.cap < spec.backoff.initial) {
|
||||
return std::unexpected{RetryConfigError::cap_below_initial};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
// `initial * multiplier^retry_index`, saturated at `cap`, without jitter.
|
||||
// The product is computed and compared in floating point and only converted
|
||||
// to an integer once it is known to lie strictly below `cap`, so it never
|
||||
// overflows. The function is total: for a spec that fails validate() the
|
||||
// result is unspecified but always lies in [0, max(cap, 0)].
|
||||
[[nodiscard]] inline std::chrono::nanoseconds
|
||||
backoff_delay(const BackoffSpec& spec,
|
||||
std::uint32_t retry_index) noexcept
|
||||
{
|
||||
using std::chrono::nanoseconds;
|
||||
if (spec.initial <= nanoseconds::zero() ||
|
||||
spec.cap <= nanoseconds::zero()) {
|
||||
return nanoseconds::zero();
|
||||
}
|
||||
const nanoseconds first = std::min(spec.initial, spec.cap);
|
||||
if (retry_index == 0 || spec.multiplier == 1.0) {
|
||||
return first;
|
||||
}
|
||||
const double cap = static_cast<double>(spec.cap.count());
|
||||
const double raw =
|
||||
static_cast<double>(spec.initial.count()) *
|
||||
std::pow(spec.multiplier, static_cast<double>(retry_index));
|
||||
// `!(raw < cap)` also catches NaN and +infinity.
|
||||
if (!(raw < cap)) {
|
||||
return spec.cap;
|
||||
}
|
||||
if (raw <= 0.0) {
|
||||
return nanoseconds::zero();
|
||||
}
|
||||
// 0 < raw < cap <= 2^63, so the conversion is in range; the final
|
||||
// min() only guards against rounding of `cap` to double.
|
||||
return std::min(nanoseconds{static_cast<nanoseconds::rep>(raw)},
|
||||
spec.cap);
|
||||
}
|
||||
|
||||
// `tp + delta`, clamped to [time_point::min(), time_point::max()].
|
||||
[[nodiscard]] constexpr SteadyTimePoint
|
||||
saturating_add(SteadyTimePoint tp,
|
||||
std::chrono::nanoseconds delta) noexcept
|
||||
{
|
||||
using Rep = SteadyTimePoint::rep;
|
||||
static_assert(std::is_integral_v<Rep> && std::is_signed_v<Rep>,
|
||||
"steady_clock must have a signed integral rep");
|
||||
const Rep base = tp.time_since_epoch().count();
|
||||
const Rep step =
|
||||
std::chrono::duration_cast<SteadyTimePoint::duration>(delta)
|
||||
.count();
|
||||
if (step >= 0) {
|
||||
if (base > std::numeric_limits<Rep>::max() - step) {
|
||||
return SteadyTimePoint::max();
|
||||
}
|
||||
} else if (base < std::numeric_limits<Rep>::min() - step) {
|
||||
return SteadyTimePoint::min();
|
||||
}
|
||||
return SteadyTimePoint{SteadyTimePoint::duration{base + step}};
|
||||
}
|
||||
|
||||
namespace detail
|
||||
{
|
||||
// Default random engine: seeded from std::random_device when the
|
||||
// engine can be seeded from one integer, default-constructed
|
||||
// otherwise.
|
||||
template <class G> G seeded_engine()
|
||||
{
|
||||
if constexpr (std::is_constructible_v<
|
||||
G, std::random_device::result_type>) {
|
||||
// Parentheses, not braces: braces would make a seed type
|
||||
// narrower than random_device::result_type a narrowing error.
|
||||
return G(std::random_device{}());
|
||||
} else {
|
||||
return G{};
|
||||
}
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
// ── RetryState
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Drives one retried operation. Protocol:
|
||||
//
|
||||
// begin(now) -> attempt | stop
|
||||
// ... run the attempt ...
|
||||
// succeed() -> stop(succeeded)
|
||||
// next(now, outcome) -> wait_until(at) | stop
|
||||
// ... wait until `at` ...
|
||||
// resume(now) -> attempt | stop
|
||||
//
|
||||
// `next` never returns `attempt`: a retry always goes through a wait
|
||||
// decision (possibly of zero length) and a resume() that re-checks the
|
||||
// stop request and the deadline at the time the wait actually ended.
|
||||
// No decision method allocates, reads a clock or blocks.
|
||||
|
||||
template <std::uniform_random_bit_generator URBG = std::mt19937_64>
|
||||
class RetryState
|
||||
{
|
||||
public:
|
||||
|
||||
// Validates `spec`. The effective deadline is
|
||||
// min(start + budget, admission_deadline); with `no_deadline` it
|
||||
// is `admission_deadline` alone (possibly none).
|
||||
[[nodiscard]] static std::expected<RetryState, RetryConfigError>
|
||||
create(const RetrySpec& spec, SteadyTimePoint start,
|
||||
URBG urbg = detail::seeded_engine<URBG>(),
|
||||
std::optional<SteadyTimePoint> admission_deadline =
|
||||
std::nullopt)
|
||||
{
|
||||
if (const auto valid = validate(spec); !valid) {
|
||||
return std::unexpected{valid.error()};
|
||||
}
|
||||
std::optional<SteadyTimePoint> deadline = admission_deadline;
|
||||
if (const auto* budget =
|
||||
std::get_if<std::chrono::nanoseconds>(&spec.budget)) {
|
||||
const SteadyTimePoint by_budget =
|
||||
saturating_add(start, *budget);
|
||||
deadline = admission_deadline.has_value()
|
||||
? std::min(by_budget, *admission_deadline)
|
||||
: by_budget;
|
||||
}
|
||||
return RetryState{spec.max_attempts, spec.backoff, deadline,
|
||||
std::move(urbg)};
|
||||
}
|
||||
|
||||
// Decide whether the first attempt may start. Calling it again
|
||||
// behaves like resume().
|
||||
[[nodiscard]] RetryDecision
|
||||
begin(SteadyTimePoint now, bool stop_requested = false) noexcept
|
||||
{
|
||||
if (final_reason_.has_value()) {
|
||||
return stop_decision(*final_reason_);
|
||||
}
|
||||
return start_attempt(now, stop_requested);
|
||||
}
|
||||
|
||||
// Record the outcome of the attempt that just finished and decide
|
||||
// what follows: stop, or wait until an absolute time.
|
||||
// Checked in order: permanent failure, attempts exhausted, stop
|
||||
// request, jittered delay overshooting the deadline.
|
||||
[[nodiscard]] RetryDecision
|
||||
next(SteadyTimePoint now, AttemptOutcome outcome,
|
||||
bool stop_requested = false) noexcept
|
||||
{
|
||||
if (final_reason_.has_value()) {
|
||||
return stop_decision(*final_reason_);
|
||||
}
|
||||
if (outcome == AttemptOutcome::permanent_failure) {
|
||||
return stop_decision(RetryStopReason::not_retryable);
|
||||
}
|
||||
if (attempts_started_ >= max_attempts_) {
|
||||
return stop_decision(RetryStopReason::attempts_exhausted);
|
||||
}
|
||||
if (stop_requested) {
|
||||
return stop_decision(RetryStopReason::stop_requested);
|
||||
}
|
||||
const std::uint32_t retry_index =
|
||||
attempts_started_ == 0 ? 0 : attempts_started_ - 1;
|
||||
const SteadyTimePoint at = saturating_add(
|
||||
now, jittered(backoff_delay(backoff_, retry_index)));
|
||||
// A wake-up exactly at the deadline is already too late.
|
||||
if (deadline_.has_value() && at >= *deadline_) {
|
||||
return stop_decision(RetryStopReason::deadline_exceeded);
|
||||
}
|
||||
return RetryDecision{RetryAction::wait_until, at,
|
||||
RetryStopReason::none, attempts_started_};
|
||||
}
|
||||
|
||||
// Call after a `wait_until` decision has elapsed (or was cut
|
||||
// short): re-checks the stop request and the deadline, then
|
||||
// starts the next attempt.
|
||||
[[nodiscard]] RetryDecision
|
||||
resume(SteadyTimePoint now, bool stop_requested = false) noexcept
|
||||
{
|
||||
if (final_reason_.has_value()) {
|
||||
return stop_decision(*final_reason_);
|
||||
}
|
||||
return start_attempt(now, stop_requested);
|
||||
}
|
||||
|
||||
[[nodiscard]] RetryDecision succeed() noexcept
|
||||
{
|
||||
return stop_decision(RetryStopReason::succeeded);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::uint32_t attempts_started() const noexcept
|
||||
{
|
||||
return attempts_started_;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<SteadyTimePoint>
|
||||
deadline() const noexcept
|
||||
{
|
||||
return deadline_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
RetryState(std::uint32_t max_attempts, const BackoffSpec& backoff,
|
||||
std::optional<SteadyTimePoint> deadline, URBG urbg)
|
||||
: max_attempts_{max_attempts}, backoff_{backoff},
|
||||
deadline_{deadline}, urbg_{std::move(urbg)}
|
||||
{
|
||||
}
|
||||
|
||||
// Every stop decision is final: later begin/next/resume calls
|
||||
// repeat it instead of starting another attempt.
|
||||
[[nodiscard]] RetryDecision
|
||||
stop_decision(RetryStopReason reason) noexcept
|
||||
{
|
||||
final_reason_ = reason;
|
||||
return RetryDecision{RetryAction::stop, SteadyTimePoint{},
|
||||
reason, attempts_started_};
|
||||
}
|
||||
|
||||
[[nodiscard]] RetryDecision
|
||||
start_attempt(SteadyTimePoint now, bool stop_requested) noexcept
|
||||
{
|
||||
if (stop_requested) {
|
||||
return stop_decision(RetryStopReason::stop_requested);
|
||||
}
|
||||
if (deadline_.has_value() && now >= *deadline_) {
|
||||
return stop_decision(RetryStopReason::deadline_exceeded);
|
||||
}
|
||||
// Only reachable when the protocol above is violated; keeps
|
||||
// the counter bounded by max_attempts_ (<= UINT32_MAX).
|
||||
if (attempts_started_ >= max_attempts_) {
|
||||
return stop_decision(RetryStopReason::attempts_exhausted);
|
||||
}
|
||||
++attempts_started_;
|
||||
return RetryDecision{RetryAction::attempt, SteadyTimePoint{},
|
||||
RetryStopReason::none, attempts_started_};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::chrono::nanoseconds
|
||||
jittered(std::chrono::nanoseconds delay) noexcept
|
||||
{
|
||||
if (!backoff_.jitter.has_value() ||
|
||||
delay <= std::chrono::nanoseconds::zero()) {
|
||||
return delay;
|
||||
}
|
||||
using Rep = std::chrono::nanoseconds::rep;
|
||||
const Rep full = delay.count();
|
||||
const Rep floor =
|
||||
*backoff_.jitter == JitterMode::Equal ? full / 2 : 0;
|
||||
std::uniform_int_distribution<Rep> dist{0, full - floor};
|
||||
return std::chrono::nanoseconds{floor + dist(urbg_)};
|
||||
}
|
||||
|
||||
std::uint32_t max_attempts_;
|
||||
BackoffSpec backoff_;
|
||||
std::optional<SteadyTimePoint> deadline_;
|
||||
URBG urbg_;
|
||||
std::uint32_t attempts_started_{0};
|
||||
std::optional<RetryStopReason> final_reason_{};
|
||||
};
|
||||
|
||||
// ── Results and classification
|
||||
// ────────────────────────────────────────────────
|
||||
|
||||
// Error half of a retried operation's result.
|
||||
// attempts attempts that were started (0 when none ran)
|
||||
// last_error the most recent attempt error; empty iff no attempt ran
|
||||
// config set (with attempts == 0) when the spec was rejected
|
||||
template <class E> struct RetryError {
|
||||
RetryStopReason reason{};
|
||||
std::uint32_t attempts{0};
|
||||
std::optional<E> last_error{};
|
||||
std::optional<RetryConfigError> config{};
|
||||
};
|
||||
|
||||
// Default classifier: every error is worth retrying.
|
||||
struct RetryEveryError {
|
||||
template <class E>
|
||||
[[nodiscard]] constexpr AttemptOutcome
|
||||
operator()(const E&) const noexcept
|
||||
{
|
||||
return AttemptOutcome::retryable_failure;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::Retry
|
||||
@@ -5,6 +5,8 @@
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <limits>
|
||||
#include <ratio>
|
||||
#include <type_traits>
|
||||
|
||||
namespace Void::Time
|
||||
{
|
||||
@@ -207,4 +209,46 @@ private:
|
||||
return std::chrono::nanoseconds{dl_ns - now_ns};
|
||||
}
|
||||
|
||||
/// Overflow-safe `point + delta` in the monotonic domain. A result that would
|
||||
/// leave the representable range clamps to `time_point::max()` (positive
|
||||
/// overflow) or `time_point::min()` (negative overflow) instead of wrapping.
|
||||
/// Negative `delta` values are allowed.
|
||||
[[nodiscard]] inline MonotonicClock::time_point
|
||||
saturating_add(MonotonicClock::time_point point,
|
||||
std::chrono::nanoseconds delta) noexcept
|
||||
{
|
||||
using TimePoint = MonotonicClock::time_point;
|
||||
using Duration = TimePoint::duration;
|
||||
using Rep = Duration::rep;
|
||||
static_assert(std::is_integral_v<Rep> && std::is_signed_v<Rep>,
|
||||
"saturating_add requires a signed integral time_point rep");
|
||||
static_assert(std::ratio_greater_equal_v<Duration::period, std::nano> &&
|
||||
std::numeric_limits<Rep>::digits >=
|
||||
std::numeric_limits<std::chrono::nanoseconds::rep>::digits,
|
||||
"saturating_add requires a time_point period of at least "
|
||||
"one nanosecond and a rep at least as wide as nanoseconds");
|
||||
|
||||
// Converting to an equal or coarser period only shrinks the magnitude, so
|
||||
// this cast never overflows.
|
||||
const Rep step = std::chrono::duration_cast<Duration>(delta).count();
|
||||
const Rep base = point.time_since_epoch().count();
|
||||
if (step > 0 && base > std::numeric_limits<Rep>::max() - step) {
|
||||
return TimePoint::max();
|
||||
}
|
||||
if (step < 0 && base < std::numeric_limits<Rep>::min() - step) {
|
||||
return TimePoint::min();
|
||||
}
|
||||
return TimePoint{Duration{base + step}};
|
||||
}
|
||||
|
||||
/// Deadline `timeout` after `clock.now()`, computed in `clock`'s own domain
|
||||
/// with `saturating_add` (so a huge or `nanoseconds::max()` timeout yields
|
||||
/// `time_point::max()` rather than an overflowed, already-expired deadline).
|
||||
[[nodiscard]] inline MonotonicClock::time_point
|
||||
deadline_after(const MonotonicClock& clock,
|
||||
std::chrono::nanoseconds timeout) noexcept
|
||||
{
|
||||
return saturating_add(clock.now(), timeout);
|
||||
}
|
||||
|
||||
} // namespace Void::Time
|
||||
@@ -0,0 +1,244 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/TaskScope.hpp>
|
||||
#include <Void/Async/Timer.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using namespace Void::Async;
|
||||
using namespace std::chrono_literals;
|
||||
using TimePoint = Void::Time::MonotonicClock::time_point;
|
||||
using Void::Time::ManualClock;
|
||||
|
||||
TimePoint at(std::chrono::nanoseconds offset)
|
||||
{
|
||||
return TimePoint{std::chrono::duration_cast<TimePoint::duration>(offset)};
|
||||
}
|
||||
|
||||
void advance_clock(ManualClock& clock, std::chrono::nanoseconds delta)
|
||||
{
|
||||
Void::Testing::require(clock.advance(delta).has_value());
|
||||
}
|
||||
|
||||
std::optional<AsyncErrorCode> code_of(const Void::Result::Result<void>& res)
|
||||
{
|
||||
if (res.has_value()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<AsyncErrorCode>(res.error().code().value);
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> schedule_into(Executor* exec,
|
||||
OperationOptions options,
|
||||
const Void::Time::MonotonicClock* clock,
|
||||
std::optional<Void::Result::Result<void>>* out)
|
||||
{
|
||||
*out = co_await schedule_on(*exec, std::move(options), *clock);
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> schedule_host_into(Executor* exec,
|
||||
OperationOptions options,
|
||||
std::optional<Void::Result::Result<void>>* out)
|
||||
{
|
||||
*out = co_await schedule_on(*exec, std::move(options));
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> increment_task(int* counter)
|
||||
{
|
||||
++(*counter);
|
||||
co_return;
|
||||
}
|
||||
|
||||
struct SleepProbe {
|
||||
int resumes{0};
|
||||
std::optional<Void::Result::Result<void>> result{};
|
||||
};
|
||||
|
||||
Void::Coro::Task<void> await_sleep(Void::Coro::Task<Void::Result::Result<void>> sleep,
|
||||
SleepProbe* probe)
|
||||
{
|
||||
auto res = co_await sleep;
|
||||
probe->result = std::move(res);
|
||||
++probe->resumes;
|
||||
}
|
||||
|
||||
void start(Void::Coro::Task<void>& task)
|
||||
{
|
||||
task.handle().resume();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test deadline_domain_schedule_on_and_scope_admission_injected_clock()
|
||||
{
|
||||
// Precondition: the host steady clock is far past the manual-domain
|
||||
// deadline used below, so host comparisons treat it as expired.
|
||||
Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms);
|
||||
|
||||
ManualExecutor exec;
|
||||
ManualClock clock; // epoch 0
|
||||
const OperationOptions opts{.deadline = at(5ms)};
|
||||
|
||||
// One deadline value, two domains.
|
||||
Void::Testing::expect(is_deadline_expired(opts));
|
||||
Void::Testing::expect(!is_deadline_expired(opts, clock));
|
||||
auto op = OperationState<void>::create(opts);
|
||||
Void::Testing::expect(op->is_deadline_expired());
|
||||
Void::Testing::expect(!op->is_deadline_expired(clock));
|
||||
|
||||
// schedule_on in the manual domain is admitted and runs.
|
||||
std::optional<Void::Result::Result<void>> admitted;
|
||||
auto t1 = schedule_into(&exec, opts, &clock, &admitted);
|
||||
start(t1);
|
||||
Void::Testing::expect(!admitted.has_value());
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(admitted.has_value());
|
||||
Void::Testing::expect(admitted->has_value());
|
||||
|
||||
// The default (host) clock rejects the same manual-domain deadline.
|
||||
std::optional<Void::Result::Result<void>> host_rejected;
|
||||
auto t2 = schedule_host_into(&exec, opts, &host_rejected);
|
||||
start(t2);
|
||||
Void::Testing::require(host_rejected.has_value());
|
||||
Void::Testing::expect(code_of(*host_rejected) == AsyncErrorCode::timeout);
|
||||
Void::Testing::expect(exec.empty());
|
||||
|
||||
// Expiry in the manual domain happens only when the manual clock advances.
|
||||
advance_clock(clock, 4ms);
|
||||
std::optional<Void::Result::Result<void>> still_ok;
|
||||
auto t3 = schedule_into(&exec, opts, &clock, &still_ok);
|
||||
start(t3);
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(still_ok.has_value());
|
||||
Void::Testing::expect(still_ok->has_value());
|
||||
|
||||
advance_clock(clock, 1ms);
|
||||
std::optional<Void::Result::Result<void>> expired;
|
||||
auto t4 = schedule_into(&exec, opts, &clock, &expired);
|
||||
start(t4);
|
||||
Void::Testing::require(expired.has_value());
|
||||
Void::Testing::expect(code_of(*expired) == AsyncErrorCode::timeout);
|
||||
Void::Testing::expect(exec.empty());
|
||||
|
||||
// Expiry observed between admission and execution is reported on resume.
|
||||
ManualClock hop_clock;
|
||||
std::optional<Void::Result::Result<void>> hop;
|
||||
auto t5 = schedule_into(&exec, opts, &hop_clock, &hop);
|
||||
start(t5);
|
||||
Void::Testing::expect(!hop.has_value());
|
||||
advance_clock(hop_clock, 5ms);
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(hop.has_value());
|
||||
Void::Testing::expect(code_of(*hop) == AsyncErrorCode::timeout);
|
||||
|
||||
// TaskScope admission uses the scope's injected clock.
|
||||
ManualClock scope_clock;
|
||||
int ran = 0;
|
||||
{
|
||||
TaskScope scope{exec, TaskScopeOptions{}, scope_clock};
|
||||
auto first = scope.spawn(increment_task(&ran), opts);
|
||||
Void::Testing::expect(first.has_value());
|
||||
advance_clock(scope_clock, 5ms);
|
||||
auto late = scope.spawn(increment_task(&ran), opts);
|
||||
Void::Testing::require(!late.has_value());
|
||||
Void::Testing::expect(late.error() == AdmissionError::deadline_expired);
|
||||
Void::Testing::expect(scope.join_pumping(exec).has_value());
|
||||
}
|
||||
{
|
||||
TaskScope host_scope{exec};
|
||||
auto host_late = host_scope.spawn(increment_task(&ran), opts);
|
||||
Void::Testing::require(!host_late.has_value());
|
||||
Void::Testing::expect(host_late.error() == AdmissionError::deadline_expired);
|
||||
Void::Testing::expect(host_scope.join_pumping(exec).has_value());
|
||||
}
|
||||
Void::Testing::expect_eq(ran, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test deadline_domain_timer_and_operation_deadline_same_manual_clock()
|
||||
{
|
||||
Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms);
|
||||
|
||||
ManualExecutor exec;
|
||||
ManualClock clock; // epoch 0
|
||||
auto created = TimerQueue::create(exec, clock);
|
||||
Void::Testing::require(created.has_value());
|
||||
auto q = std::move(*created);
|
||||
Void::Testing::expect(&q->clock() == &clock);
|
||||
Void::Testing::expect(&q->executor() == &exec);
|
||||
|
||||
// An OperationOptions deadline in the ManualClock domain bounds the sleep.
|
||||
const OperationOptions opts{.deadline = at(3ms)};
|
||||
SleepProbe probe;
|
||||
auto task = await_sleep(q->sleep_until(at(8ms), opts), &probe);
|
||||
start(task);
|
||||
Void::Testing::expect(!task.done()); // the host clock would call it expired
|
||||
|
||||
Void::Testing::require(q->next_deadline().has_value());
|
||||
Void::Testing::expect(*q->next_deadline() == at(3ms));
|
||||
Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{3ms});
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{0});
|
||||
Void::Testing::expect(exec.empty());
|
||||
|
||||
advance_clock(clock, 2ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{0});
|
||||
Void::Testing::expect(exec.empty());
|
||||
Void::Testing::expect_eq(probe.resumes, 0);
|
||||
|
||||
// Advance + explicit poll expires it once; the resume goes through the
|
||||
// completion executor.
|
||||
advance_clock(clock, 1ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{1});
|
||||
Void::Testing::expect_eq(probe.resumes, 0);
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::expect_eq(probe.resumes, 1);
|
||||
Void::Testing::require(probe.result.has_value());
|
||||
Void::Testing::expect(code_of(*probe.result) == AsyncErrorCode::timeout);
|
||||
Void::Testing::expect_eq(q->active_timers(), std::size_t{0});
|
||||
|
||||
// Passing `when` later fires nothing and never produces a second result.
|
||||
advance_clock(clock, 10ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{0});
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{0});
|
||||
Void::Testing::expect_eq(probe.resumes, 1);
|
||||
|
||||
// The same deadline is expired for schedule_on in the same manual domain.
|
||||
std::optional<Void::Result::Result<void>> scheduled;
|
||||
auto sched = schedule_into(&exec, opts, &q->clock(), &scheduled);
|
||||
start(sched);
|
||||
Void::Testing::require(scheduled.has_value());
|
||||
Void::Testing::expect(code_of(*scheduled) == AsyncErrorCode::timeout);
|
||||
|
||||
// A deadline equal to `when` is not earlier: the sleep completes normally.
|
||||
SleepProbe equal;
|
||||
const auto target = Void::Time::deadline_after(clock, 5ms);
|
||||
auto equal_task =
|
||||
await_sleep(q->sleep_until(target, OperationOptions{.deadline = target}), &equal);
|
||||
start(equal_task);
|
||||
advance_clock(clock, 5ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{1});
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(equal.result.has_value());
|
||||
Void::Testing::expect(equal.result->has_value());
|
||||
|
||||
// A deadline later than `when` does not interfere either.
|
||||
SleepProbe later;
|
||||
auto later_task = await_sleep(
|
||||
q->sleep_for(1ms, OperationOptions{.deadline = Void::Time::deadline_after(clock, 2ms)}),
|
||||
&later);
|
||||
start(later_task);
|
||||
advance_clock(clock, 2ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{1});
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(later.result.has_value());
|
||||
Void::Testing::expect(later.result->has_value());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,112 @@
|
||||
#include <Void/Time/Clock.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <utility>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using TimePoint = Void::Time::MonotonicClock::time_point;
|
||||
|
||||
constexpr std::int64_t kMax = std::numeric_limits<std::int64_t>::max();
|
||||
constexpr std::int64_t kMin = std::numeric_limits<std::int64_t>::min();
|
||||
|
||||
std::int64_t ns_of(TimePoint tp)
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
TimePoint at_ns(std::int64_t ns)
|
||||
{
|
||||
return TimePoint{std::chrono::duration_cast<TimePoint::duration>(
|
||||
std::chrono::nanoseconds{ns})};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test clock_saturating_add_and_deadline_after_bounds()
|
||||
{
|
||||
using Void::Time::deadline_after;
|
||||
using Void::Time::saturating_add;
|
||||
|
||||
static_assert(noexcept(saturating_add(std::declval<TimePoint>(),
|
||||
std::declval<std::chrono::nanoseconds>())));
|
||||
static_assert(noexcept(
|
||||
deadline_after(std::declval<const Void::Time::MonotonicClock&>(),
|
||||
std::declval<std::chrono::nanoseconds>())));
|
||||
|
||||
// In-range arithmetic, positive and negative steps.
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), 5ns)), std::int64_t{5});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(10), -3ns)), std::int64_t{7});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(-10), 0ns)), std::int64_t{-10});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(-1), std::chrono::nanoseconds::max())),
|
||||
kMax - 1);
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), std::chrono::nanoseconds::max())),
|
||||
kMax);
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), std::chrono::nanoseconds::min())),
|
||||
kMin);
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(1), std::chrono::nanoseconds::min())),
|
||||
kMin + 1);
|
||||
|
||||
// Positive overflow clamps to time_point::max().
|
||||
Void::Testing::expect(saturating_add(at_ns(kMax - 1), 2ns) == TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(TimePoint::max(), 1ns) == TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(at_ns(1), std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(TimePoint::max(), std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(TimePoint::max(), 0ns) == TimePoint::max());
|
||||
|
||||
// Negative overflow clamps to time_point::min().
|
||||
Void::Testing::expect(saturating_add(at_ns(kMin + 1), -2ns) == TimePoint::min());
|
||||
Void::Testing::expect(saturating_add(TimePoint::min(), -1ns) == TimePoint::min());
|
||||
Void::Testing::expect(saturating_add(at_ns(-1), std::chrono::nanoseconds::min()) ==
|
||||
TimePoint::min());
|
||||
Void::Testing::expect(saturating_add(TimePoint::min(), std::chrono::nanoseconds::min()) ==
|
||||
TimePoint::min());
|
||||
|
||||
// Extremes in the other direction stay exact.
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(TimePoint::max(), std::chrono::nanoseconds::min())),
|
||||
std::int64_t{-1});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(TimePoint::min(), std::chrono::nanoseconds::max())),
|
||||
std::int64_t{-1});
|
||||
|
||||
// deadline_after uses the injected clock's own domain, never the host clock.
|
||||
Void::Time::ManualClock epoch_clock;
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(epoch_clock, 1s)),
|
||||
std::int64_t{1'000'000'000});
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(epoch_clock, -5ns)), std::int64_t{-5});
|
||||
Void::Testing::expect(deadline_after(epoch_clock, std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect(deadline_after(epoch_clock, std::chrono::nanoseconds::min()) ==
|
||||
TimePoint::min());
|
||||
|
||||
Void::Time::ManualClock offset_clock{at_ns(100)};
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(offset_clock, 50ns)), std::int64_t{150});
|
||||
Void::Testing::require(offset_clock.advance(25ns).has_value());
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(offset_clock, 50ns)), std::int64_t{175});
|
||||
|
||||
Void::Time::ManualClock far_clock{at_ns(kMax - 10)};
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(far_clock, 10ns)), kMax);
|
||||
Void::Testing::expect(deadline_after(far_clock, 1s) == TimePoint::max());
|
||||
Void::Testing::expect(deadline_after(far_clock, std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(far_clock, -10ns)), kMax - 20);
|
||||
|
||||
// A saturated deadline is consistent with remaining_until (no wrap to 0).
|
||||
Void::Testing::expect_eq(
|
||||
Void::Time::remaining_until(epoch_clock,
|
||||
deadline_after(epoch_clock, std::chrono::nanoseconds::max())),
|
||||
std::chrono::nanoseconds::max());
|
||||
Void::Testing::expect_eq(
|
||||
Void::Time::remaining_until(far_clock, deadline_after(far_clock, 1h)),
|
||||
std::chrono::nanoseconds{10});
|
||||
}
|
||||
Reference in new issue
Block a user