Author SHA1 Message Date
faumaray 3c018d6dad docs(workflow): record Wave 11 completion and verification evidence 2026-12-01 22:33:50 +03:00
faumaray c6de7842f7 fix(wave11): resolve adversarial review findings in EventBus, IO, and Runtime 2026-12-01 22:03:35 +03:00
faumaray 7bea7df46d feat(runtime): add 8-step Host start, SignalGate, and 11-phase structured shutdown (S-RUNTIME-02/03) 2026-12-01 16:58:29 +03:00
faumaray 50029e1f7b feat(io): add Driver::run, embedded pump_until, and shutdown conformance tests (S-IO-04) 2026-12-01 16:25:20 +03:00
faumaray ef85ce07b7 feat(async): add EventBus injected/joined lifecycle and Observable reentrancy queue (M-ASYNC-05) 2026-12-01 10:27:50 +03:00
faumaray 1e752da590 feat(io): add positional File workers, sync, bounded shutdown core, and epoll D1 fixes (S-IO-03) 2026-12-01 10:15:03 +03:00
faumaray b2c84114fe feat(async): add ThreadExecutor, FuturePool, AsyncChannel, bounded parallel_for, and spawn fix (M-ASYNC-04) 2026-12-01 10:15:03 +03:00
faumarayandClaude Opus 5.5 5c24f8e84f feat(async): add retry_async over TimerQueue and deadline-domain conformance (M-TIME-03 B1b)
- NEW Async/Retry.hpp: retry_async drives RetryState with the TimerQueue's
  injected clock, awaits backoff via sleep_until, resumes only after a clean
  sleep (any sleep error ends the retry), preserves success after stop,
  supports Task-returning and move-only callables
- Tests: AsyncRetry (15), DeadlineDomains blocking-retry manual-clock case

Review: W11-REVIEW-B1b READY (deviation accepted; doc fix applied by root)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 00:35:20 +03:00
faumarayandClaude Opus 5.5 3ce21be53a docs(wave11): record review/verification progress
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 00:34:21 +03:00
faumarayandClaude Opus 5.5 09789ae141 docs(wave11): S-IO-04 and combined S-RUNTIME-02/03 specs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 00:20:28 +03:00
faumarayandClaude Opus 5.5 7c1fd3cac1 docs(workflow): record merge-to-main requirement (D-043)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 00:07:35 +03:00
faumarayandClaude Opus 5.5 4ea63844f0 docs(wave11): record M-TIME-03 B1 verification
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:36:37 +03:00
faumarayandClaude Opus 5.5 99a1100bb1 feat(async,time): add injected-clock TimerQueue and clock saturation helpers (M-TIME-03 B1)
- NEW Async/Timer.hpp: TimerQueue (stable (deadline, seq) min-heap, bounded
  tombstones, explicit poll_expired, callbacks outside the lock, close/destroy
  deliver TimerEvent::closed), shared-state TimerHandle safe after queue
  destruction, sleep_until/sleep_for settling exactly once and resuming via
  post_completion; documented sleep-task lifetime and cancel-under-lock rules
- Time/Clock.hpp: saturating_add, deadline_after
- Tests: TimerQueue (15), DeadlineDomains (2), ClockSaturation (1); race loops
  count failures to stay under the runner's 1,000-assertion retention (X-QA-02)

Review: W11-REVIEW-B1 (CHANGES_REQUIRED F1-F3 fixed by root: test counters,
header lifetime/cancel docs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:36:37 +03:00
faumarayandClaude Opus 5.5 95785ed47a docs(wave11): B1b and M-ASYNC-05 specs, STATE checkpoint
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:32:39 +03:00
faumarayandClaude Opus 5.5 c6789e7dbf docs(wave11): S-IO-03 and M-ASYNC-04 specs with review amendments (D-042)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:45:03 +03:00
faumarayandClaude Opus 5.5 26edf653e3 feat(functional): add pure RetryState and named retry_blocking adapter (M-FUNCTIONAL-03)
- NEW std-only Functional/RetryState.hpp: RetrySpec/BackoffSpec validation,
  begin/next/resume/succeed decisions, saturating backoff, Full/Equal jitter,
  explicit no_deadline, random_device-seeded default engine, final stop decisions
- Retry.hpp: relocate JitterMode, add SteadyNow/ThreadSleep/BlockingRetryOptions
  and retry_blocking with injected now/sleep; saturating wait computation
- 1.x retry/retry_while/retry_or_throw unchanged (zero-attempt defect pinned)
- Tests: RetryState (13), RetryBlocking (10)

Review: W11-REVIEW-A1 READY (P3 fixes 1, 2, 5 applied by root)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:34:46 +03:00
faumarayandClaude Opus 5.5 99203ce1f3 docs(wave11): record PREFLIGHT-2 findings and contract amendment R2 (D-040)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:57:11 +03:00
faumarayandClaude Opus 5.5 a8a9249101 docs(wave11): add A1/B1 specs, VoidForge backlog items, push authorization (D-039)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:47:03 +03:00
faumarayandClaude Opus 5.5 7f95f89d52 chore(wave11): plan execution-path backfill, reserve error codes, update area plans
- Audit roadmap vs TASKS (D-033); scope Wave 11 to M-FUNCTIONAL-03, M-TIME-03,
  M-ASYNC-04/05, S-IO-03/04, S-RUNTIME-02/03 (D-034..D-036)
- Schedule VoidForge upstream requests after Wave 11 (D-037)
- Persist planner output, PREFLIGHT findings and contract addendum (D-038)
- Add AsyncErrorCode::closed, IoErrorCode::sync_failed,
  RuntimeErrorCode::{self_join, shutdown_incomplete}
- Update Functional/IO/Runtime area plans and MIGRATION per C-13

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:31:14 +03:00
faumaray 38436b18c8 update version
Release / release (push) Failing after 5m4s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-29 07:06:52 +03:00
faumaray 7d7d23ec0a Merge branch 'feat/roadmap-p3-wave10' (P3 Discovery, Scheduler, Messaging) 2026-11-27 05:55:45 +03:00
faumaray f3f66e0c8c docs(workflow): record Wave 10 P3 Discovery, Scheduler, and Messaging verification 2026-11-27 05:55:45 +03:00
faumaray 60ee28e4ca feat(messaging): implement P3 S-MESSAGING-01..04 Messaging queue, StorageQueue/OutboxInbox, and MessagingRpc adapter 2026-11-27 05:45:43 +03:00
faumaray aaeab50758 feat(scheduler): implement P3 S-SCHEDULER-01..04 Scheduler engine, calendar/DST, and SchedulerStorage durable store 2026-11-27 05:38:06 +03:00
faumaray ec8c0bd40a feat(discovery): implement P3 S-DISCOVERY-01..04 Discovery catalog and optional DiscoveryRpc adapter 2026-11-27 05:25:43 +03:00
faumaray 0cf187d664 docs(wave10): add P3 Discovery, Scheduler, and Messaging specs and error domains 2026-11-27 05:14:52 +03:00
faumaray 65ad9b3f31 Merge branch 'feat/roadmap-p2-wave9' (P2 Net, TestingMock, ShortUrl, RPC) 2026-11-27 01:37:15 +03:00
faumaray 385a441b0b docs(workflow): record Wave 9 P2 Net, TestingMock, ShortUrl, and RPC verification 2026-11-27 01:37:15 +03:00
faumaray 5184d1cf8c feat(rpc): implement P2 S-RPC-01..03 Wire v1 binary codec and unary HTTP/1.1 RPC subsystem 2026-11-27 01:27:32 +03:00
faumaray 691808eab6 feat(shorturl): complete P2 M-SHORTURL-01..04 V2 local, storage, and remote providers with frozen V1 2026-11-27 01:27:32 +03:00
faumaray 658c21a2fa feat(testing-mock): complete P2 M-TESTINGMOCK-01..04 sessions, action-outside-lock, move-only, combinators 2026-11-27 01:15:36 +03:00
faumaray 86d777eae6 feat(net): complete P2 M-NET-01..05 codec, pool, safe static open, redirects, and RFC 6455 WebSocket 2026-11-27 01:15:36 +03:00
faumaray 700024a24d docs(wave9): add P2 Net, TestingMock, ShortUrl, and RPC task specs and error domains 2026-11-26 22:58:30 +03:00
faumaray 3e254055e0 Merge branch 'feat/upstream-vbs-requests' (VL-001..VL-013) 2026-11-26 22:01:33 +03:00
165 changed files with 50825 additions and 772 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 4.0.0)
project(Void VERSION 1.2.1 LANGUAGES C CXX)
project(Void VERSION 1.2.3 LANGUAGES C CXX)
if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
elseif(NOT DEFINED BUILD_SHARED_LIBS)
+20
View File
@@ -73,3 +73,23 @@ plans requiring updates. Do not record a proposal as user approval.
| D-030 | Create dedicated git branch (`feat/roadmap-p0-p1-foundations`) and make focused commits per completed milestone/task; leave local untracked files (`.env`, `.serena/`, `WG.conf`, `keys`) untouched | CONFIRMED by user |
| D-031 | Proceed continuously across roadmap waves without pausing for confirmation between waves, and merge verified waves locally into `main` (without pushing to remote) | CONFIRMED by user |
| D-032 | Push verified `main` (and active feature branches) to `origin` (`git@git.faumaray.com:Void/VoidLibrary.git`) after each verified wave merge, superseding the local-only constraint in `D-031` | CONFIRMED by user ("dont forget to push") |
## Root decisions (2026-11-29)
These are root-owned sequencing decisions made under D-027/D-031 (continuous roadmap-order
execution without pausing between waves). They are not new user approvals.
| ID | Decision | Contract / rationale |
| --- | --- | --- |
| D-033 | Gap audit: `STATE.md`'s "all P2 modules complete" was inaccurate. Against the roadmap task tables, 2 P1 tasks (`M-FUNCTIONAL-03`, `M-TIME-03`) and 40 P2 tasks remain open; pre-roadmap headers (`Async/{Channel,EventBus,Observable,ParallelFor,ThreadPool}.hpp`, `Functional/{Retry,Memo}.hpp`, `Core/TypeMap.hpp`) are unchanged since `f1f9ba3`. | Roadmap order (D-027) and P2 outcome in `DELIVERY.md` |
| D-034 | Wave 11 is the execution-path backfill (`M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`, `S-RUNTIME-02`, `S-RUNTIME-03`) on `feat/roadmap-p2-wave11`. The platform half of the former "Wave 11" note (`P-NETWORKED-*`, `P-RELOADABLE-*`, `S-RPC-05`) is deferred because `P-*-02` require these Runtime/Async/IO lifecycle gates. `S-RPC-04` may ride along only if the planner finds it ready and file-disjoint. | G-EXEC, G-IO; C-03–C-06 |
| D-035 | P0 characterization tasks (`M-*-01`, `S-ALGORITHMS-01`, `S-MEMORY-01`) are not scheduled as separate waves; each follow-on spec records its observed baseline instead. Distributed `-01`/`-02` planning tasks stay with P4. | Avoids documentation-only waves; evidence lives in each task spec |
| D-036 | Remaining foundation P2 tasks (Core, Functional-04..06, Containers, Math, Text, Data, Binary, Time-04/05, Algorithms, Unicode, Memory-05, Testing-04/05) form a later parallel wave after Wave 11. | Independent of the execution-path gate |
| D-037 | VoidForge upstream requests (received 2026-11-29 from the VoidForge session on the user's behalf; source `VoidForge/docs/agent-workflow/VOIDLIBRARY_GAPS.md`) are scheduled as an out-of-band wave after Wave 11 and before the D-036 foundation wave, following the `VL-001`..`VL-013` precedent: first `VL-STREAM-01` + `VL-PROC-01` (P0), then `VL-WASM-01`, `VL-TOML-01`, `VL-MCP-01` (P1; MCP after STREAM), `VL-WIN-01` when the Windows runner needs it, and `VL-LUA-01`/`VL-STORE-01` (P2) later. Signatures are VoidLibrary-owned; peer proposals are inputs, not approvals. | Peer request is not user approval of scope beyond scheduling; licensing question escalated to the user |
| D-038 | Wave 11 contracts adopted from `tasks/W11-PLAN-OUTPUT.md` as amended by `tasks/W11-PLAN-REV1-OUTPUT.md` after PREFLIGHT `tasks/W11-PREFLIGHT-OUTPUT.md` (CHANGES_REQUIRED: F1 P1, F2–F13 P2, P3 list). Accepted D-W11-01..04, 06..15; D-W11-05 modified per F9 (S-IO-03/opus owns the bounded shutdown core and poll-owner exclusion; S-IO-04/sonnet adds thin wrappers, `pump_until`, conformance). Root resolutions for F1 (file workers never call executors/user code except the injected syscall shim; `~Driver` is the only blocking teardown; destruction on a worker/inside a poll turn terminates with a diagnostic), F2 (epoll/eventfd close in backend destructor; `wake()` after shutdown is a no-op), F3–F6 (phase renumbering, per-call shutdown budgets, teardown in `~HostCore`, embedded borrowed resources never shut down), F7–F13 as in the addendum. Area plans `Functional.md`, `Runtime.md`, `IO.md` and `MIGRATION.md` updated per C-13. A1/B1 (Functional/Timer) may start before the PREFLIGHT re-review because the P1 is confined to IO/Runtime; re-review findings on F8/F12 are applied as corrections. | C-03–C-06, C-13; D-029 |
| 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 |
| D-043 | User reminder (2026-11-30): all wave work must end up in `main`. Each wave (Wave 11, then the VoidForge wave, then later waves) finishes with full RelWithDebInfo + ASan/UBSan + TSan verification on the integrated branch, a fresh adversarial review, a `--no-ff` merge into `main`, and a push of `main` (D-032/D-039). Feature-branch-only completion does not count as done. | CONFIRMED by user |
+48 -9
View File
@@ -1,8 +1,9 @@
# Workflow state
Updated: 2026-11-26.
Repository: VoidLibrary; active branch `feat/upstream-vbs-requests` (from `main`
at `53d42bd`, merged Waves 1–8 and pushed to `origin/main`).
Updated: 2026-12-01.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave11` (from `main` at `38436b1`;
Waves 1–11 + `VL-001`..`VL-013` complete and merging into `main`, pushed to `origin/main`).
Current wave: **Wave 11 — execution-path backfill COMPLETE**; next: **Wave 12 — VoidForge upstream requests (`D-041`) + `X-QA-01..04`**.
## Completed objective
@@ -339,11 +340,49 @@ while leaving local untracked files untouched.
- Full Debug ASan+UBSan (`/tmp/void-vbs-asan`, 45 modules, `-Werror`): `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB (+ post-`9920bfd` `Http|Net|Server` `9/9 ✔` in `1.58s`).
- Debug TSan (`/tmp/void-vbs-tsan`, `Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`, 17 modules, `-Werror`): `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings.
### Wave 9 — P2 Completion: `Net`, `TestingMock`, `ShortUrl`, `RPC` (`feat/roadmap-p2-wave9`)
- **Specs & Error Domains (`700024a`)**: authored `M-NET-01-05.md`, `M-TESTINGMOCK-01-04.md`, `M-SHORTURL-01-04.md`, `S-RPC-01-03.md`; reserved `kTestingMockErrorDomain = 27`, `kShortUrlErrorDomain = 28`, `kRpcErrorDomain = 29`, `kDiscoveryErrorDomain = 30`.
- **`Net` P2 Hardening (`86d777e`, `M-NET-01..05`)**: native incremental RFC 9110/9112 `HttpRequestParser` / `HttpResponseParser`, bounded `ConnectionPool` (`PoolKey` origin+proxy+TLS generation, `MonotonicClock` idle eviction, RAII `ConnectionLease`), descriptor-pinned `StaticFileResolver::open_safe()` (`openat`+`O_NOFOLLOW`), `HttpClient` `303`/`307` redirect & single-deadline hardening, RFC 6455 `WebSocket` codec/decoder/`WebSocketClient` & `HttpServer::add_websocket_route()`.
- **`TestingMock` P2 Hardening (`658c21a`, `M-TESTINGMOCK-01..04`)**: explicit `MockSession` (`freeze`, `verify_and_close`, `MockLimits`, `RegistrationToken`), `Sequence` order groups, action-outside-lock reservation (same-thread reentry + `ConcurrentActions`), perfect forwarding + `returns_once`/`invokes_once` move-only support, `never()`/`at_least`/`at_most`/`between`, matcher combinators (`Ne`, `EndsWith`, `IsNull`, `NotNull`, `NotOf`, `AllOf`, `AnyOf`, depth bound 32), `TestingMockOnly` consumer.
- **`ShortUrl` P2 Completion (`691808e`, `M-SHORTURL-01..04`)**: preserved frozen `V1` ABI; added `Void::ShortUrl::V2` (`LocalProvider`, URL/key validation, base62 keys, civil expiry, tombstone non-reuse, 24h idempotency, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (pre-mutation capability checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer.
- **`RPC` Subsystem (`5184d1c`, `S-RPC-01..03`)**: NEW `Void::RPC` module with Wire v1 deterministic binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` (`AuthHook`, schema check, timeout clamp, sanitized exceptions, `Registration::unregister_and_drain()`), `RpcOnly` consumer.
- **Full-suite & sanitizer checks**:
- Full integrated RelWithDebInfo (`/tmp/void-w9-full`, 48 modules, `-Werror`): `VoidTests` `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `23.56s`; `ctest` `2/2` in `91.13s` (`VoidTests` `23.27s`, `VoidInstalledComponentConsumers` `67.86s` across all `38` consumers); `VoidFoundationBench` (`rev=5184d1cf8cdd`) recorded.
- Full Debug ASan+UBSan (`/tmp/void-w9-asan`, 48 modules, `-Werror`): `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB.
- Debug TSan (`/tmp/void-w9-tsan`, `Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`, 22 modules, `-Werror`): `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings.
### Wave 10 — P3 Core Subsystems: `Discovery`, `Scheduler`, `Messaging` (`feat/roadmap-p3-wave10`)
- **Specs & Error Domains (`0cf187d`)**: authored `S-DISCOVERY-01-04.md`, `S-SCHEDULER-01-04.md`, `S-MESSAGING-01-04.md`; reserved `kSchedulerErrorDomain = 31` and `kMessagingErrorDomain = 32` (`kDiscoveryErrorDomain = 30` reserved in Wave 9).
- **`Discovery` & `DiscoveryRpc` (`ec8c0bd`, `S-DISCOVERY-01..04`)**: NEW zero-external-dep `Void::Discovery` subsystem (`Catalog` with pure thread-free construction, atomic `replace_static()`, provider generation resets, local RAII `Registration` handles with steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` overflow recovery + self-cancel + `SelfJoin` diagnosis, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` endpoint adapter preserving `expected_tls_name` / blocking TLS downgrades while keeping `RPC` independent; `DiscoveryOnly` consumer (`_no_external_deps`).
- **`Scheduler` & `SchedulerStorage` (`aaeab50`, `S-SCHEDULER-01..04`)**: NEW zero-external-dep `Void::Scheduler` subsystem (monotonic min-heap ordered by `(due_time, sequence)`, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` with DST gap/fold & unknown-zone rejection without silent UTC fallback, O(1) backward-scanning `CoalesceLatest` over millions of missed slots, 100/pass `CatchUpBounded`, `Forbid`/`QueueOne`/`AllowBounded` overlap, exponential full-jitter retries & dead-letter acknowledgement, revision invalidation watermark, `close_and_join` returning incomplete report on deadline) + durable `Void::SchedulerStorage` (`StorageJobStore` on `Void::Storage::Engine` conditional batches, exclusive owner lock, unique civil-slot dedup, startup `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause without cursor loss); `SchedulerOnly` consumer (`_no_external_deps`).
- **`Messaging`, `MessagingStorage`, & `MessagingRpc` (`60ee28e`, `S-MESSAGING-01..04`)**: NEW zero-external-dep `Void::Messaging` subsystem (explicit `PublishDurability::{Memory,Durable}`, `InMemoryQueue` rejecting `Durable`, `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`, competing & `SingleActive` groups, stale-receipt fencing & idempotent repeat ack, bounded retries -> DLQ, corrupt-payload quarantine) + `Void::MessagingStorage` (`StorageQueue` on `Void::Storage::Engine` conditional batches, restart `InFlight -> Pending` generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency ledger refusing silent eviction, `BlockAtQuota` default & clock-health expiry pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`); `MessagingOnly` consumer (`_no_external_deps`).
- **Full-suite & sanitizer checks**:
- Full integrated RelWithDebInfo (`/tmp/void-w10-full`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly` with `_no_external_deps`); `VoidFoundationBench` (`rev=60ee28e4ca9b`) recorded.
- 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`, verified & merged to `main`)
- **Planning & contracts (`7f95f89`, `a8a9249`, `99203ce`, `c6789e7`, `95785ed`, `4ea6384`, `7c1fd3c`, `09789ae`, `3ce21be`)**: `W11-PLAN-OUTPUT.md`, PREFLIGHT 1 & 2 (`W11-PLAN-REV1-OUTPUT.md`, `W11-CONTRACT-R2.md`), spec reviews (`D-038`, `D-040`, `D-042`), error code reservations, area plans (`Functional.md`, `Runtime.md`, `IO.md`, `MIGRATION.md`).
- **Execution-path implementation**:
- `M-FUNCTIONAL-03` (`26edf65`): pure retry policy state machine + `retry_blocking`.
- `M-TIME-03` (`99a1100`, `5c24f8e`): injected-clock `TimerQueue` + saturation helpers + `retry_async`.
- `M-ASYNC-04` (`b2c8411`): `ThreadExecutor`, `FuturePool`, `AsyncChannel`, bounded `parallel_for`, `Executor.hpp` `spawn()` race fix.
- `S-IO-03` (`1e752da`): bounded positional `File` workers, sync, active-cancel, shutdown core, D1 retire-once fixes.
- `M-ASYNC-05` (`ef85ce0`): `EventBus` injected/joined lifecycle + `Observable` reentrancy queue.
- `S-IO-04` (`50029e1`): `Driver::run`, `Pump.hpp` `pump_until`, `SystemAsync` shutdown conformance.
- `S-RUNTIME-02/03` (`7bea7df`): `Host` explicit start, readiness, reverse failed-start cleanup, phased shutdown (`Lifecycle.hpp`, `Detail/HostCore.hpp`, `Host.hpp`).
- **Adversarial review & post-fix hardening (`c6de784`)**:
- Fresh adversarial review (`925b2cd8-7c57-4121-b6c5-b925c6a434f6`) returned `CHANGES_REQUIRED` (1 P1 + 7 P2 + 1 P3) across `EventBus.hpp`, `Pump.hpp`, `Driver.hpp`, `EpollDriver.cpp`, and `HostCore.hpp`.
- Resolved all 9 findings in `c6de784` with 10 regression tests (`EventBus::finish_entry_dispatch` + pumping `self_join`; `pump_until` / `Driver::run` / `run_reactor_loop` `steady_clock` idle pacing + `EpollBackend` `EPOLLIN` disarming; `MockBackend::try_acquire` shutdown/closing TOCTOU guard; `HostCore` `start_running`/mutex sync, `flushing_exporters` single-drain poll, embedded background-worker `shutdown_blocking`, and incomplete `stopping_io` worker count). Post-fix review: `READY`.
- **Integrated post-fix verification (`c6de784`, `-DVOID_WARNINGS_AS_ERRORS=ON`)**:
- Targeted TSan & Runtime (`verify_w11_fixes.sh` + `verify_runtime.sh`): `110/110 ✔` TSan (`599.1ms`), all 6 Runtime gates passed (`37/37 ✔`, `nosys` `ctest` `2/2`, TSan, ASan, zero `Void/System/` includes in `include/Void/Runtime/**`).
- Full RelWithDebInfo (`/tmp/void-w11-full`, 55 modules): `VoidTests` `1,694` (`1,690 ✔`, `4 ⊘`, `0 ✘`) in `25.13s`; `ctest` `2/2` in `110.10s` (`VoidTests` `25.01s`, `VoidInstalledComponentConsumers` `85.09s` across all `41` consumers); `VoidFoundationBench` (`rev=c6de7842f732`, `/tmp/void-w11-full/post-w11.json`): `harness_empty_loop` `0.40ns`, `core_uuid_parse_hyphenated` `26.06ns`, `core_uuid_to_string` `18.06ns`, `core_hash_fnv1a64_256b` `186.38ns`, `core_hash_murmur3_256b` `69.57ns`, `functional_result_ok_chain` `1.16ns`, `functional_error_with_context` `61.13ns`, `math_checked_add_loop` `0.50ns`, `containers_spsc_ring_push_pop` `9.33ns`, `containers_lru_get_put` `22.02ns`, `binary_reader_u64_be` `1.19ns`, `data_json_parse_small_object` `302.08ns`, `data_json_serialize_small_object` `170.90ns`.
- Full Debug ASan+UBSan (`/tmp/void-w11-asan`, 55 modules): `VoidTests` `1,694` (`1,690 ✔`, `4 ⊘`, `0 ✘`) in `67.61s`, `0` leaks, `0` UB.
- Wave 11 Debug TSan (`/tmp/void-w11-tsan`, 21 modules): unfiltered `VoidTests` `1,035` (`1,032 ✔`, `3 ⊘`, `0 ✘`) in `34.78s`; 3x 169-test stress loop `169/169 ✔` (`2.12s`, `3.07s`, `2.14s`), `0` data races / lock-order warnings.
## Ownership and next step
Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`,
`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`,
`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`,
`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`)
and the VoidBuildSystem upstream feature wave (`VL-001`..`VL-013`) are complete,
verified, and merged to `main` via `--no-ff`.
Waves 1–11 (`P0`, `P1` incl. `M-FUNCTIONAL-03`/`M-TIME-03`, P2 execution/operations/storage/lifecycle/network modules, `VL-001`..`VL-013`, and P3 core subsystems `Discovery`, `Scheduler`, `Messaging`) are complete, verified, merged into `main`, and pushed. Next: **Wave 12** VoidForge upstream requests (`D-041`: `VL-STREAM-01`, `VL-PROC-01`, `VL-CRYPTO-01/02`, `VL-TEXT-01`, `VL-NET-W01`, `VL-NET-02`, `VL-WASM-01`, `VL-TOML-01`, `VL-MCP-01`, `VL-SQLITE-01..06`, `VL-SEC-01`) + root QA backlog (`X-QA-01..04`); then remaining P2 foundation tasks (`D-036`), P3 (`S-RPC-04/05`, `NetworkedApplications`, `ReloadableApplications`), and P4.
+79
View File
@@ -119,8 +119,87 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| VL-006, VL-007 | Optional `OpenSSL::Crypto` (`VOID_CRYPTO_HAS_OPENSSL`) + pure-C++ FIPS 180-4 SHA-1/256/512 & RFC 7693 BLAKE2b-256/512 + HMAC/HKDF + `snake_case` hash aliases (`22c8538`); optional `LibArchive` (`VOID_ARCHIVE_HAS_LIBARCHIVE`) + pure-C++ USTAR/PAX tar & deterministic `ArchiveCompression::Gzip` + `create()` (`22c8538`) | — | VERIFIED | Zero-OpenSSL `534 ✔ / 3 ⊘` (`1.09s`, `ctest` `2/2` `5.59s`); zero-LibArchive `405 ✔ / 3 ⊘` (`1.45s`, `ctest` `2/2` `6.22s`); full-backend `888 ✔ / 3 ⊘` (`3.70s`, `ctest` `2/2` `15.53s`); full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
| VL-004, VL-005 | POSIX TCP HTTP/1.1 `HttpServer` (`query`, `file_body`/`from_file`, `Router::allowed_methods`, `bound_port`, `431`/`413`, TE+CL smuggling `400`, streaming `BodyReader`, `HEAD`->`GET`, `shutdown`), streaming `HttpClient` + `HttpClient::secure()` TLS >= 1.2 + CA/SAN + cross-origin/downgrade/redaction + `NetErrorCode` (`kNetErrorDomain = 26`) + `std::stop_token` + `NetOnly` consumer (`66baae7`) + TSan `-Wno-tsan` scope & `StallServer` fix (`9920bfd`) | — | VERIFIED | Standalone `Net;System;Crypto;Testing` `563 ✔ / 3 ⊘` (`2.36s`), `ctest` `2/2` (`8.48s` incl. `NetOnly`); Debug TSan `954 ✔ / 3 ⊘` (`10.65s`, `0` races); full RelWithDebInfo `1,452 ✔ / 4 ⊘` (`22.09s`), `ctest` `2/2` (`82.82s`, `35` consumers); ASan+UBSan `1,452 ✔` (`39.11s`) + `Http\|Net\|Server` `9/9` (`1.58s`, `0` leaks/UB) |
## Wave 9 — P2 Completion: Net, TestingMock, ShortUrl, RPC (`feat/roadmap-p2-wave9`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| M-NET-01..05 | Native incremental RFC 9110/9112 `HttpRequestParser` / `HttpResponseParser` (smuggling rejection, 1xx/HEAD/chunked/trailers/EOF), bounded `ConnectionPool` (`PoolKey` origin+proxy+TLS generation, `MonotonicClock` idle eviction, RAII `ConnectionLease`), descriptor-pinned `StaticFileResolver::open_safe()` (`openat`+`O_NOFOLLOW`), `HttpClient` `303`/`307` redirect & single-deadline hardening, RFC 6455 `WebSocket` codec/decoder/`WebSocketClient` & `HttpServer::add_websocket_route()` (`86d777e`) | [M-NET-01-05](tasks/M-NET-01-05.md) | VERIFIED | Standalone `Net;System;Crypto;TestingMock;Testing` `44/44 ✔` (`1.31s`), `ctest` `2/2` (`10.96s` incl. `NetOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔ / 4 ⊘` (`23.56s`, `ctest` `2/2` `91.13s`, `38` consumers); ASan+UBSan `1,466 ✔` (`41.95s`, `0` leaks/UB) |
| M-TESTINGMOCK-01..04 | Explicit `MockSession` (`kTestingMockErrorDomain = 27`, `freeze(SingleThread\|ConcurrentActions)`, `verify_and_close()`, `MockLimits`, `RegistrationToken`), `Sequence` order groups, action-outside-lock reservation (same-thread reentry + concurrent actions), perfect forwarding + `returns_once`/`invokes_once` move-only support, `never()`/`at_least`/`at_most`/`between`, matcher combinators (`Ne`, `EndsWith`, `IsNull`, `NotNull`, `NotOf`, `AllOf`, `AnyOf`, depth bound 32), `TestingMockOnly` consumer (`658c21a`) | [M-TESTINGMOCK-01-04](tasks/M-TESTINGMOCK-01-04.md) | VERIFIED | Standalone `TestingMock*` 18/18 ✔ + `ctest` `TestingMockOnly`; Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
| M-SHORTURL-01..04 | Frozen `V1` ABI preserved + additive `Void::ShortUrl::V2` (`kShortUrlErrorDomain = 28`, URL/key validation, base62 rejection-sampled keys, civil expiry, tombstone non-reuse, 24h idempotency, `LocalProvider`, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (capability pre-checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer (`691808e`) | [M-SHORTURL-01-04](tasks/M-SHORTURL-01-04.md) | VERIFIED | Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing` `ShortUrl*` 5/5 ✔, `ctest` `2/2` (`36.84s` incl. `ShortUrlOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
| S-RPC-01..03 | NEW `Void::RPC` subsystem (`kRpcErrorDomain = 29`), Wire v1 big-endian binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` with `AuthHook`, schema negotiation, timeout clamping, sanitized handler exceptions, `Registration::unregister_and_drain()`, `RpcOnly` consumer (`5184d1c`) | [S-RPC-01-03](tasks/S-RPC-01-03.md) | VERIFIED | Standalone `Rpc` 2/2 ✔, `ctest` `2/2` (`36.84s` incl. `RpcOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
## Wave 10 — P3 Core Subsystems: Discovery, Scheduler, Messaging (`feat/roadmap-p3-wave10`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| S-DISCOVERY-01..04 | NEW `Void::Discovery` (`kDiscoveryErrorDomain = 30`, pure `Catalog`, atomic `replace_static()`, provider generation resets, local RAII `Registration` + steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` + self-cancel + `SelfJoin`, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` (identity-preserving TLS refresh; `RPC` remains Discovery-free), `DiscoveryOnly` consumer (`ec8c0bd`) | [S-DISCOVERY-01-04](tasks/S-DISCOVERY-01-04.md) | VERIFIED | Standalone `Discovery;DiscoveryRpc;Testing` `5/5 ✔` (`9.4ms`), `ctest` `2/2` (`11.26s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔ / 4 ⊘` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
| S-SCHEDULER-01..04 | NEW `Void::Scheduler` (`kSchedulerErrorDomain = 31`, monotonic min-heap, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` DST gap/fold & unknown-zone rejection, O(1) `CoalesceLatest` over >2.6M missed minutes, 100/pass `CatchUpBounded`, overlap policies, retries/dead-letter, revision invalidation watermark, `close_and_join`) + durable `Void::SchedulerStorage` (`StorageJobStore` exclusive owner lock, unique civil-slot dedup, crash `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause), `SchedulerOnly` consumer (`aaeab50`) | [S-SCHEDULER-01-04](tasks/S-SCHEDULER-01-04.md) | VERIFIED | Standalone `Scheduler;SchedulerStorage;System;Testing` `5/5 ✔` (`167.3ms`), `ctest` `2/2` (`30.06s` incl. `SchedulerOnly` `_no_external_deps`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
| S-MESSAGING-01..04 | NEW `Void::Messaging` (`kMessagingErrorDomain = 32`, explicit `PublishDurability`, nondurable `InMemoryQueue`, `Pending -> InFlight(gen, visibility) -> Acked \| Pending \| DeadLetter`, competing/`SingleActive` groups, stale-receipt fencing, idempotent ack, retries/DLQ, corrupt quarantine) + `Void::MessagingStorage` (`StorageQueue` durable batches, restart generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency, `BlockAtQuota` & clock-health pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`), `MessagingOnly` consumer (`60ee28e`) | [S-MESSAGING-01-04](tasks/S-MESSAGING-01-04.md) | VERIFIED | Standalone `Messaging;MessagingStorage;MessagingRpc;System;Testing` `4/4 ✔` (`217.4ms`), `ctest` `2/2` (`31.73s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
All workers share the checkout and have disjoint file ownership defined in their
persisted task specifications. Root owns all cross-cutting files and resolves contract
changes. No worker owns application code, build files, existing docs/short-url.md, or Git
operations. Configured roles use XHigh; runtime model identity is not independently
verified by the available spawn response.
## Wave 11 — Execution-path backfill (`feat/roadmap-p2-wave11`)
Baseline: `main` at `38436b1`; full RelWithDebInfo `-Werror` (`/tmp/void-w11-base`, 55 modules):
`VoidTests` 1,484 discovered (1,480 ✔, 4 ⊘, 0 ✘) in 26.99 s; `ctest` 2/2 (111.68 s).
Post-fix integrated verification (`c6de784`): adversarial review (`CHANGES_REQUIRED`: 1 P1 + 7 P2 + 1 P3 on `7bea7df`) fixed in `c6de784` (+10 regression tests, post-fix review `READY`); full 55-module RelWithDebInfo `1,694` (`1,690 ✔`, `4 ⊘`, `0 ✘`), `ctest` `2/2` (`110.10s`, `41` consumers), Debug ASan+UBSan `1,694` (`0` leaks/UB), Debug TSan `1,035` (`1,032 ✔`, `3 ⊘`) + 3×`169/169 ✔` stress loop (`0` races).
Decisions: D-033..D-043.
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| W11-PLAN | Architecture/task plan + REV1 addendum + R2 contract | [W11-PLAN](tasks/W11-PLAN.md), [output](tasks/W11-PLAN-OUTPUT.md), [REV1](tasks/W11-PLAN-REV1-OUTPUT.md), [R2](tasks/W11-CONTRACT-R2.md) | DONE | PREFLIGHT 1 & 2 resolved via REV1/D-038 & R2/D-040; spec review S1–S9, A1–A3 adopted via D-042 |
| M-FUNCTIONAL-03 | Pure retry decisions + named blocking adapter (A1) | [spec](tasks/M-FUNCTIONAL-03.md) | VERIFIED (`26edf65`) | Review W11-REVIEW-A1 READY; ResilienceAsync subset 475 (472 ✔, 3 ⊘), filtered 43/43, ctest 2/2, TSan 40/40 (0 races), ASan+UBSan 40/40; verified in post-W11 full suite (`c6de784`) |
| 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) | VERIFIED (`99a1100`, `5c24f8e`) | W11-REVIEW-B1 & B1b READY; root 697 (694 ✔, 3 ⊘), TSan 33/33 + 5×15/15, ASan 468 ✔; verified in post-W11 full/TSan suites (`c6de784`) |
| M-ASYNC-04 | ThreadExecutor, FuturePool, AsyncChannel, bounded ParallelFor (A2) + `spawn()` race & ParallelFor last-ref fixes | [spec](tasks/M-ASYNC-04.md) | VERIFIED (`b2c8411`) | 109/109, TSan 6×47/47, ASan 46/46; verified in post-W11 full/ASan/TSan+3×stress suites (`c6de784`) |
| M-ASYNC-05 | EventBus/Observable snapshot dispatch, joined subscriptions (A3) + post-review capture-lifetime & pumping self-join fixes | [spec](tasks/M-ASYNC-05.md) | VERIFIED (`ef85ce0`, `c6de784`) | Targeted TSan 110/110 ✔; verified in post-W11 full/ASan (`1,690 ✔`) & TSan (`1,032 ✔` + 3×`169/169 ✔`) |
| S-IO-03 | Bounded positional file workers, sync, active-cancel, shutdown core, D1 fixes (B2) + `MockBackend::try_acquire` TOCTOU & epoll `EPOLLIN` fixes | [spec](tasks/S-IO-03.md) | VERIFIED (`1e752da`, `c6de784`) | IO 37/37, TSan 37/37 + 30 loops, ASan clean; post-fix `c6de784` full/ASan/TSan+3×stress (`1,690 ✔` / `1,032 ✔` + 3×`169/169 ✔`) |
| S-IO-04 | `Driver::run`, `Pump.hpp` `pump_until`, SystemAsync shutdown conformance (A4) + steady_clock idle pacing fixes | [spec](tasks/S-IO-04.md) | VERIFIED (`50029e1`, `c6de784`) | Targeted & integrated post-W11 RelWithDebInfo, `ctest` 2/2 (`41` consumers), ASan+UBSan, & TSan+3×stress (`0` races) |
| S-RUNTIME-02 | Explicit start, readiness, reverse failed-start cleanup + concurrent start/shutdown synchronization | [spec](tasks/S-RUNTIME-02-03.md) | VERIFIED (`7bea7df`, `c6de784`) | `verify_runtime.sh` 6/6 gates (incl. `nosys` & zero `Void/System/` includes), full/ASan/TSan+3×stress (`c6de784`) |
| S-RUNTIME-03 | Structured shutdown, repeated join, exporter-before-executor ordering + embedded background-worker & poll exporter fixes | [spec](tasks/S-RUNTIME-02-03.md) | VERIFIED (`7bea7df`, `c6de784`) | `RuntimeStart`/`RuntimeSignals`/`RuntimeShutdown`/`RuntimeHost` `37/37 ✔` (RelWithDebInfo, TSan, ASan) & post-W11 full/ASan/TSan (`c6de784`) |
P0 characterization tasks (`M-*-01`, `S-ALGORITHMS-01`, `S-MEMORY-01`): folded into follow-on
specs' observed baselines (D-035); not separately scheduled.
## VoidForge upstream requests (scheduled after Wave 11; D-037)
| ID | Priority | Request (VoidLibrary owns final signatures) | State |
| --- | --- | --- | --- |
| VL-STREAM-01 | P0 | Duplex HTTP response streaming: `HttpServer` duplex route + scoped response writer (begin/write_some/finish), per-exchange cancel/deadline, chunked/fixed/bodyless framing, pre-header error vs post-header abort | PLANNED |
| VL-PROC-01 | P0 | Binary subprocess session (argv-only, env allowlist, independent stdout/stderr drain, bounded buffering, NUL-safe, distinguishable EOF/exit/timeout/cancel/truncation) | PLANNED |
| VL-WIN-01 | P0 (later) | Windows HANDLE backend for VL-PROC-01 and HttpClient file transfer; client-only Net selection | PLANNED (deferred until requested) |
| VL-WASM-01 | P1 | Bounded `Text/Diff.hpp` (`DiffLimits`, checked sizes, work/memory caps, cancellation, explicit incomplete result, reflection-free build) | PLANNED |
| VL-MCP-01 | P1 | Generic MCP foundations (envelope, bounded JSON-RPC framing, Streamable HTTP + stdio bindings, auth callback); depends on VL-STREAM-01; RPC untouched | PLANNED |
| VL-TOML-01 | P1 | Qualify `Data/Toml` limits for dotted keys/table paths/inline tables; API change only with reproducer | PLANNED |
| VL-LUA-01 | P2 | Sandboxed Lua runtime (allocation/step budgets, no ambient IO) | PLANNED (backend decision needed) |
| VL-STORE-01 | P2 | Native Storage conformance support for Forge | PLANNED |
| VL-SQLITE-01 | P2 (non-blocking) | Structural SQLite primary/extended result codes (distinguish UNIQUE/CONSTRAINT vs BUSY/LOCKED) instead of message-only (`Sqlite/Types.hpp`, `Sqlite.cpp`) | PLANNED |
| VL-SQLITE-02 | P2 (non-blocking) | Documented `Unknown` commit outcome for failed COMMIT under WAL I/O error (like `Storage` `Outcome::Unknown`) | PLANNED |
| VL-SEC-01 | P2 (non-blocking) | Public CSPRNG bytes API (e.g. `Security::random_bytes(std::span<unsigned char>)`) | PLANNED |
| VL-SQLITE-03 | P3 (non-blocking) | Per-connection, phase-targetable `ScopedFaultGuard` (incl. "COMMIT succeeded but reported failure") | PLANNED |
| VL-SQLITE-04 | P3 (non-blocking) | Per-call busy-timeout override | PLANNED |
| VL-NET-W01 | P2 (hygiene) | `src/Net/HttpServer.cpp:1797,1871` ignore `read()`/`write()` results (`-Wunused-result` under consumer flags, likely `_FORTIFY_SOURCE`); VoidLibrary's own `-Werror` build at `38436b1` passes | PLANNED |
| 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 |
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | PLANNED |
+18
View File
@@ -291,3 +291,21 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
| Full Debug ASan+UBSan (`66baae7`, `9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-vbs-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB; post-`9920bfd` incremental `--filter 'Http\|Net\|Server'` `9/9 ✔` in `1.58s` |
| Debug TSan (`9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug TSan (`-Werror`, `/tmp/void-vbs-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 17 modules (`Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`) | **PASSED**: `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings |
| Post-VBS Benchmark (`66baae7`, `rev=66baae74a0b7`) | `/tmp/void-vbs-full/benchmarks/VoidFoundationBench --json /tmp/void-vbs-full/post-vbs.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 26.35ns, `core_uuid_to_string` 18.33ns, `core_hash_fnv1a64_256b` 185.86ns, `core_hash_murmur3_256b` 69.58ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 59.59ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.97ns, `containers_lru_get_put` 21.17ns, `binary_reader_u64_be` 1.34ns, `data_json_parse_small_object` 316.05ns, `data_json_serialize_small_object` 174.83ns |
| Wave 9 `Net` & `TestingMock` standalone (`86d777e`, `658c21a`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w9-net`, `Net;System;Crypto;TestingMock;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `44/44 ✔` in `1.31s` (`NetHardening` 5/5, `SessionHardening` 4/4, all legacy Net/TestingMock suites); `ctest` `2/2` in `10.96s` (`VoidTests` `2.46s`, `VoidInstalledComponentConsumers` `8.50s` incl. `NetOnly` & `TestingMockOnly`) |
| Wave 9 `ShortUrl` & `RPC` standalone (`691808e`, `5184d1c`) | `dev cpp-gcc -p openssl -p libsodium -c` RelWithDebInfo (`-Werror`, `/tmp/void-w9-shorturl-rpc`, `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `7/7 ✔` in `1.20s` (`Rpc` 2/2, `ShortUrl` 2/2, `ShortUrlV2` 1/1, `StorageRepository` 1/1, `RemoteProvider` 1/1); `ctest` `2/2` in `36.84s` (`VoidTests` `17.31s`, `VoidInstalledComponentConsumers` `19.54s` incl. `ShortUrlOnly` & `RpcOnly`) |
| Wave 9 integrated RelWithDebInfo + consumers (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w9-full`), 48 modules, `VoidTests` + `ctest` | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `23.56s`; `ctest` `2/2` in `91.13s` (`VoidTests` `23.27s`, `VoidInstalledComponentConsumers` `67.86s` across all `38` consumers incl. `NetOnly`, `TestingMockOnly`, `ShortUrlOnly`, `RpcOnly`) |
| Wave 9 full Debug ASan+UBSan (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w9-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 48 modules | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB |
| Wave 9 Debug TSan (`5184d1c`) | `dev cpp-gcc -p openssl -p libsodium` Debug TSan (`-Werror`, `/tmp/void-w9-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 22 modules (`Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`) | **PASSED**: `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings |
| Post-W9 Benchmark (`5184d1c`, `rev=5184d1cf8cdd`) | `/tmp/void-w9-full/benchmarks/VoidFoundationBench --json /tmp/void-w9-full/post-w9.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.49ns, `core_uuid_parse_hyphenated` 25.02ns, `core_uuid_to_string` 16.55ns, `core_hash_fnv1a64_256b` 183.63ns, `core_hash_murmur3_256b` 69.12ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.06ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.93ns, `containers_lru_get_put` 21.47ns, `binary_reader_u64_be` 1.15ns, `data_json_parse_small_object` 297.72ns, `data_json_serialize_small_object` 172.85ns |
| Wave 10 `Discovery` & `DiscoveryRpc` standalone (`ec8c0bd`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m1`, `Discovery;DiscoveryRpc;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `9.4ms` (`Catalog` 4/4, `EndpointAdapter` 1/1); `ctest` `2/2` in `11.26s` (`VoidTests` `0.60s`, `VoidInstalledComponentConsumers` `10.66s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`) |
| Wave 10 `Scheduler` & `SchedulerStorage` standalone (`aaeab50`) | `dev cpp-gcc -c` zero external deps RelWithDebInfo (`-Werror`, `/tmp/void-w10-m2`, `Scheduler;SchedulerStorage;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `167.3ms` (`Scheduler` 3/3, `StorageJobStore` 2/2); `ctest` `2/2` in `30.06s` (`VoidTests` `16.51s`, `VoidInstalledComponentConsumers` `13.54s` incl. `SchedulerOnly` `_no_external_deps`) |
| Wave 10 `Messaging`, `MessagingStorage`, & `MessagingRpc` standalone (`60ee28e`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m3`, `Messaging;MessagingStorage;MessagingRpc;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `4/4 ✔` in `217.4ms` (`Messaging` 1/1, `StorageQueue` 2/2, `RpcAdapter` 1/1); `ctest` `2/2` in `31.73s` (`VoidTests` `16.09s`, `VoidInstalledComponentConsumers` `15.63s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`) |
| Wave 10 integrated RelWithDebInfo + consumers (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w10-full`), 55 modules, `VoidTests` + `ctest` | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly`) |
| Wave 10 full Debug ASan+UBSan (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w10-asan`), 55 modules | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB |
| Wave 10 Debug TSan (`60ee28e`) | `dev cpp-gcc -p openssl` Debug TSan (`-Werror`, `/tmp/void-w10-tsan`), 23 modules (`Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`) | **PASSED**: `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings |
| Post-W10 Benchmark (`60ee28e`, `rev=60ee28e4ca9b`) | `/tmp/void-w10-full/benchmarks/VoidFoundationBench --json /tmp/void-w10-full/post-w10.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.18ns, `core_uuid_to_string` 16.66ns, `core_hash_fnv1a64_256b` 182.46ns, `core_hash_murmur3_256b` 68.53ns, `functional_result_ok_chain` 1.14ns, `functional_error_with_context` 59.10ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.85ns, `containers_lru_get_put` 20.87ns, `binary_reader_u64_be` 1.14ns, `data_json_parse_small_object` 287.18ns, `data_json_serialize_small_object` 164.76ns |
| Wave 11 adversarial review & targeted fixes (`c6de784`) | Fresh adversarial review (`925b2cd8-7c57-4121-b6c5-b925c6a434f6`) on `7bea7df` -> `c6de784` (`verify_w11_fixes.sh` + `verify_runtime.sh`: Debug TSan `Async;IO;Runtime;System;Testing` + 6 Runtime gates, `-Werror`) | Review `CHANGES_REQUIRED` (1 P1 + 7 P2 + 1 P3) resolved in `c6de784` (+10 regression tests); post-fix review `READY`. Targeted TSan `110/110 ✔` in `599.1ms`; `verify_runtime.sh` 6/6 gates passed (`37/37 ✔` RelWithDebInfo, `nosys` `ctest` 2/2, TSan, ASan `224.8ms`, zero `Void/System/` includes in `include/Void/Runtime/**`) |
| Wave 11 integrated RelWithDebInfo + consumers (`c6de784`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w11-full`), 55 modules, `VoidTests` + `ctest` | **PASSED**: `1,694` discovered (`1,690 ✔`, `4 ⊘` skipped, `0 ✘`) in `25.13s`; `ctest` `2/2` in `110.10s` (`VoidTests` `25.01s`, `VoidInstalledComponentConsumers` `85.09s` across all `41` consumers) |
| Wave 11 full Debug ASan+UBSan (`c6de784`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w11-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 55 modules | **PASSED**: `1,694` discovered (`1,690 ✔`, `4 ⊘` skipped, `0 ✘`) in `67.61s`, `0` leaks, `0` UB |
| Wave 11 Debug TSan + 3x stress loop (`c6de784`) | `dev cpp-gcc` Debug TSan (`-Werror`, `/tmp/void-w11-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 21 modules (`Async;IO;IPC;SystemAsync;Storage;Runtime;ConfigurationAsync;System;Testing`) | **PASSED**: unfiltered `1,035` (`1,032 ✔`, `3 ⊘` skipped, `0 ✘`) in `34.78s`; 3x Wave 11 stress loop `169/169 ✔` (`2.12s`, `3.07s`, `2.14s`), `0` data races / lock-order warnings |
| Post-W11 Benchmark (`c6de784`, `rev=c6de7842f732`) | `/tmp/void-w11-full/benchmarks/VoidFoundationBench --json /tmp/void-w11-full/post-w11.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 26.06ns, `core_uuid_to_string` 18.06ns, `core_hash_fnv1a64_256b` 186.38ns, `core_hash_murmur3_256b` 69.57ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 61.13ns, `math_checked_add_loop` 0.50ns, `containers_spsc_ring_push_pop` 9.33ns, `containers_lru_get_put` 22.02ns, `binary_reader_u64_be` 1.19ns, `data_json_parse_small_object` 302.08ns, `data_json_serialize_small_object` 170.90ns |
+228
View File
@@ -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.
+151
View File
@@ -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,202 @@
# M-FUNCTIONAL-03 — Pure retry decisions and named blocking adapter
Task ID: M-FUNCTIONAL-03
Role: sonnet-implementer
Status: READY
## 1. Context and baseline
- Wave 11 package step A1.
- Repo: `/home/faumaray/Projects/VoidLibrary`, branch `feat/roadmap-p2-wave11`, HEAD `7f95f89`
(root prep on `main` `38436b1`). You work in an isolated git worktree of `7f95f89`; your cwd is
that worktree root. Do not touch the user's untracked files (`.env`, `WG.conf`, `keys`, `jev_token`).
- Baseline: full suite at `38436b1` = 1,484 tests, 1,480 passed, 4 skipped, 0 failed.
- Observed source (M-FUNCTIONAL-01 characterization folded in, D-035):
- `include/Void/Functional/Retry.hpp` (tabs for indentation): backoff structs in milliseconds
(`NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`), `JitterMode` + `Jittered`
(thread_local `mt19937_64` seeded from `std::random_device`, ~:76-95), `Policy{max_attempts=3,
max_elapsed=0 → unlimited}` (~:100-110), `Detail::backoff_sleep` hard-wired to
`steady_clock::now()`/`sleep_for` (~:117-142), `retry`/`retry_or_throw`/`retry_while`; with
`max_attempts == 0` legacy `retry` returns a default-constructed (successful) `expected` without
calling `fn` (~:150-211).
- `src/Functional/module.cmake` declares no `INTERNAL_DEPS` (D-015: standard-library-only).
- Consumers: `include/Void/Resilience/AsyncPolicy.hpp` uses `Void::Retry::ExponentialBackoff`,
`JitterMode` (lines ~6, 486, 533) — must stay source-compatible.
- Tests: `tests/standalone/Functional/Retry.cpp` (14), `RetryJitter.cpp` (4).
- Requirements: roadmap row M-FUNCTIONAL-03 (`docs/roadmap/modules/Functional.md` "Pure retry and
callable ownership", updated in `7f95f89`); decisions D-029, D-038; contracts C-02, C-04.
## 2. Objective and deliverables
Roadmap acceptance: "Extract pure retry decisions and retain named blocking adapter; fake-time
tests prove exact attempt counts, deadlines, jitter bounds and no zero-attempt success."
Deliver:
1. NEW `include/Void/Functional/RetryState.hpp` — pure, standard-library-only decision engine.
2. EDIT `include/Void/Functional/Retry.hpp` — include `RetryState.hpp`, relocate `JitterMode`
definition into it (same name/namespace), add `SteadyNow`, `ThreadSleep`,
`BlockingRetryOptions`, `retry_blocking`. All 1.x symbols keep identical behavior.
3. NEW tests `tests/standalone/Functional/RetryState.cpp`, `tests/standalone/Functional/RetryBlocking.cpp`.
## 3. Scope and non-goals
In: the above. Out: Time/Async adapters (`Async::retry_async` is M-TIME-03), changing any 1.x
retry behavior (including the zero-attempt defect — pin it with a characterization test),
Resilience changes, any build-file edit.
## 4. Files to inspect
`include/Void/Functional/Retry.hpp` (all), `include/Void/Resilience/AsyncPolicy.hpp` (Retry uses),
`tests/standalone/Functional/{Retry,RetryJitter}.cpp` (test style: `VOID_TEST`/assert macros,
file stem = suite name), `src/Testing/Runner.cpp:209-225` (`--filter` is a regex over
`suite.name`), `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` §M-FUNCTIONAL-03 and
`W11-PLAN-REV1-OUTPUT.md` F8/P3 (design source).
## 5. Write ownership and coordination
Write scope: `include/Void/Functional/RetryState.hpp` (NEW), `include/Void/Functional/Retry.hpp`,
`tests/standalone/Functional/RetryState.cpp` (NEW), `tests/standalone/Functional/RetryBlocking.cpp` (NEW).
Forbidden: every other path (build files, other modules, docs). Another worker (M-TIME-03) runs
concurrently in a different worktree and will later include `RetryState.hpp`; keep the interface
exactly as specified. No git commit/branch/stash/reset; root integrates your diff.
## 6. Implementation or investigation approach
1. Create `RetryState.hpp` (namespace `Void::Retry`, includes only `<chrono> <cstdint> <expected>
<optional> <random> <variant> <concepts> <limits> <cmath> <type_traits>` as needed; NO `<thread>`,
NO `Void/...` include). Move `enum class JitterMode { Full, Equal };` here verbatim; remove it
from `Retry.hpp` and `#include "Void/Functional/RetryState.hpp"` (match existing include style).
2. Implement the interface in §7 with the fixed semantics below.
3. Add the blocking adapter to `Retry.hpp` after the 1.x API, without touching 1.x bodies.
4. Write the tests (§10). Build/run per §11 (configure/build in your worktree; build dir under
`/tmp/void-w11-fn3*`).
Fixed semantics (mandatory):
- `create` validates via `validate`; deadline = `min(saturating_add(start, budget), admission_deadline)`
when budget is a duration; with `no_deadline` deadline is `admission_deadline` (may be none).
- `begin(now, stop)`: stop → `{stop, reason=stop_requested}`; `now >= deadline` →
`deadline_exceeded`; else `{attempt}` and `attempts_started` becomes 1.
- `next(now, outcome, stop)` checks in order: permanent → `not_retryable`; `attempts_started ==
max_attempts` → `attempts_exhausted`; stop → `stop_requested`; else
`at = saturating_add(now, jitter(backoff_delay(spec.backoff, attempts_started - 1)))`;
`at >= deadline` → `deadline_exceeded`; else `{wait_until, at}`. `next` never returns `attempt`.
- `resume(now, stop)`: re-checks stop and deadline, then `{attempt}` and increments `attempts_started`.
- `succeed()` → `{stop, succeeded}`.
- `backoff_delay(b, k)` = `initial * multiplier^k` saturated at `cap` before any integer conversion
(compute in `long double`/`double`, clamp, then convert); never overflows; unjittered.
- Full jitter: uniform integer ns in `[0, d]`; Equal: `d/2 + uniform[0, d - d/2]`.
- Validation errors: `zero_attempts` (max_attempts == 0), `negative_duration` (initial/cap/budget
< 0), `zero_budget` (budget duration == 0), `nonfinite_multiplier`, `multiplier_below_one`,
`cap_below_initial`.
- Default engine is seeded from `std::random_device` (F8): use `detail::seeded_engine<URBG>()`.
- `retry_blocking`: invalid spec → `RetryError{config=err, attempts=0}` without calling `fn`;
waits are `decision.at - options.now()` passed to `options.sleep(wait, options.stop)`; a `false`
return (stopped) ends with `stop_requested` and no further attempt; the adapter never calls
`sleep_until`. `last_error` holds the most recent `E` (empty iff no attempt ran). Value type may
be move-only.
## 7. Interfaces and data contracts
```cpp
namespace Void::Retry { // RetryState.hpp (NEW)
using SteadyTimePoint = std::chrono::steady_clock::time_point;
enum class JitterMode { Full, Equal }; // EXISTING, relocated verbatim
struct NoDeadline { constexpr bool operator==(const NoDeadline&) const noexcept = default; };
inline constexpr NoDeadline no_deadline{};
struct BackoffSpec { std::chrono::nanoseconds initial{std::chrono::milliseconds{100}};
std::chrono::nanoseconds cap{std::chrono::seconds{30}}; double multiplier{2.0};
std::optional<JitterMode> jitter{}; };
struct RetrySpec { std::uint32_t max_attempts{3}; // total, including the first
std::variant<std::chrono::nanoseconds, NoDeadline> budget{std::chrono::seconds{30}};
BackoffSpec backoff{}; };
enum class RetryConfigError : std::uint8_t { zero_attempts, negative_duration, zero_budget,
nonfinite_multiplier, multiplier_below_one, cap_below_initial };
enum class RetryAction : std::uint8_t { attempt, wait_until, stop };
enum class RetryStopReason : std::uint8_t { none, succeeded, attempts_exhausted, deadline_exceeded,
not_retryable, stop_requested };
enum class AttemptOutcome : std::uint8_t { retryable_failure, permanent_failure };
struct RetryDecision { RetryAction action{RetryAction::stop}; SteadyTimePoint at{};
RetryStopReason reason{RetryStopReason::none}; std::uint32_t attempts_started{0}; };
[[nodiscard]] std::expected<void, RetryConfigError> validate(const RetrySpec&) noexcept;
[[nodiscard]] std::chrono::nanoseconds backoff_delay(const BackoffSpec&, std::uint32_t retry_index) noexcept;
[[nodiscard]] constexpr SteadyTimePoint saturating_add(SteadyTimePoint, std::chrono::nanoseconds) noexcept;
namespace detail { template <class G> G seeded_engine(); } // random_device seed if constructible
template <std::uniform_random_bit_generator URBG = std::mt19937_64>
class RetryState { public:
[[nodiscard]] static std::expected<RetryState, RetryConfigError> create(const RetrySpec&,
SteadyTimePoint start, URBG urbg = detail::seeded_engine<URBG>(),
std::optional<SteadyTimePoint> admission_deadline = std::nullopt);
[[nodiscard]] RetryDecision begin(SteadyTimePoint now, bool stop_requested = false) noexcept;
[[nodiscard]] RetryDecision next(SteadyTimePoint now, AttemptOutcome, bool stop_requested = false) noexcept;
[[nodiscard]] RetryDecision resume(SteadyTimePoint now, bool stop_requested = false) noexcept;
[[nodiscard]] RetryDecision succeed() noexcept;
[[nodiscard]] std::uint32_t attempts_started() const noexcept;
[[nodiscard]] std::optional<SteadyTimePoint> deadline() const noexcept; };
template <class E> struct RetryError { RetryStopReason reason{}; std::uint32_t attempts{0};
std::optional<E> last_error{}; std::optional<RetryConfigError> config{}; };
struct RetryEveryError { template <class E> constexpr AttemptOutcome operator()(const E&) const noexcept
{ return AttemptOutcome::retryable_failure; } };
}
namespace Void::Retry { // Retry.hpp additions (NEW)
struct SteadyNow { SteadyTimePoint operator()() const noexcept { return std::chrono::steady_clock::now(); } };
struct ThreadSleep { bool operator()(std::chrono::nanoseconds wait, std::stop_token) const; }; // condition_variable_any + stop; false if stopped
template <class NowFn = SteadyNow, class SleepFn = ThreadSleep, class Classify = RetryEveryError,
class URBG = std::mt19937_64>
struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{};
URBG urbg = detail::seeded_engine<URBG>(); std::stop_token stop{};
std::optional<SteadyTimePoint> deadline{}; };
template <class F, class NowFn = SteadyNow, class SleepFn = ThreadSleep,
class Classify = RetryEveryError, class URBG = std::mt19937_64> // F() -> std::expected<T,E>
[[nodiscard]] auto retry_blocking(const RetrySpec&, F&& fn,
BlockingRetryOptions<NowFn, SleepFn, Classify, URBG> options = {})
-> std::expected<T, RetryError<E>>; // T,E deduced from F's result
}
```
`ThreadSleep` may live inline in `Retry.hpp` (which already includes `<thread>`). Unchanged 1.x:
`NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`, `Jittered`, `JitterMode`, `Policy`,
`Detail::backoff_sleep`, `retry`, `retry_or_throw`, `retry_while`.
## 8. Dependencies and integration
Upstream: M-FUNCTIONAL-02 (done). Downstream: M-TIME-03 `Async::retry_async` consumes `RetryState`,
`RetrySpec`, `RetryError`, `RetryEveryError`, `AttemptOutcome` exactly as above (gate G1). Root
integrates and commits.
## 9. Edge cases security and performance
Saturating arithmetic near `time_point::max()`; multiplier 1e300 and `initial` near max; NaN/inf
multiplier; negative durations; `max_attempts = UINT32_MAX` does not overflow counters; jitter on
`d = 0`; deadline exactly equal to `at` counts as exceeded; no allocation in `RetryState`.
## 10. Acceptance criteria
1. `RetryState.cpp` tests: `retry_state_rejects_invalid_specs` (one check per `RetryConfigError`),
`retry_state_exact_three_attempts_default`, `retry_state_deadline_at_admission_prevents_first_attempt`,
`retry_state_backoff_overshooting_deadline_stops`, `retry_state_no_deadline_explicit_marker`,
`retry_state_backoff_saturates_without_overflow`, `retry_state_full_equal_jitter_bounds_and_seed_reproducibility`
(seeded `mt19937_64{42}`; bounds + same-seed equality, not exact values),
`retry_state_default_engine_jitter_in_bounds`, `retry_state_stop_prevents_next_attempt`,
`retry_state_permanent_failure_stops`, `retry_state_saturating_add_near_max` — all pass.
2. `RetryBlocking.cpp` tests (fake clock struct local to the test, no Time include, zero real sleeps):
`retry_blocking_fake_clock_exact_waits_and_attempts`, `retry_blocking_zero_attempts_config_error_no_call`,
`retry_blocking_expired_deadline_no_call_no_success`, `retry_blocking_last_error_and_attempt_count`,
`retry_blocking_stop_during_sleep_no_extra_attempt`, `retry_blocking_permanent_failure_single_attempt`,
`retry_blocking_move_only_value`, `legacy_retry_zero_attempts_behavior_pinned` (characterizes the
1.x defect; comment says it is recorded for Wave C) — all pass.
3. Existing `Retry`, `RetryJitter`, `AsyncPolicy` tests pass unchanged.
4. `RetryState.hpp` contains no `<thread>` and no `Void/` include; `src/Functional/module.cmake` unchanged.
5. `-DVOID_WARNINGS_AS_ERRORS=ON` clean.
## 11. Verification commands and evidence
Run from your worktree root (`$PWD`). `dev` must run with the sandbox disabled (the nix fetcher
lock fails inside it). Expected: build exit 0, filtered tests all pass, ctest 2/2.
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3 -G Ninja -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3 --parallel 8 && /tmp/void-w11-fn3/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\." && ctest --test-dir /tmp/void-w11-fn3 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-res -G Ninja -DVOID_ENABLED_MODULES="ResilienceAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-res --parallel 8 && /tmp/void-w11-fn3-res/tests/VoidTests --filter "^(AsyncPolicy|Retry|RetryJitter|RetryState|RetryBlocking)\."'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-asan --parallel 8 && /tmp/void-w11-fn3-asan/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\."'
rg -n "#include <thread>|Void/" include/Void/Functional/RetryState.hpp # expect no output
```
If a cmake option name differs (e.g. sanitizer flags), discover it in `CMakeLists.txt`/`cmake/Capabilities.cmake`
and report the exact command used.
## 12. Constraints and stop conditions
Do not edit outside write scope, weaken assertions, disable warnings, or change 1.x behavior. Stop
and report BLOCKED if: the interface cannot compile as specified; a 1.x test needs changing; a
build failure originates outside your files; the sanitizer option names cannot be found.
## 13. Authorization and decisions
Root decisions D-034, D-038 under user decisions D-027/D-029/D-031. Implementation of the listed
files only; no commits, pushes or other side effects.
## 14. Return format
Return task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per
acceptance criterion; commands with cwd/results (test counts); checks not run; residual risks;
integration notes (worktree path). Do not spawn children.
+29
View File
@@ -0,0 +1,29 @@
# Task Spec: `M-NET-01..05` — P2 Network Hardening, Native HTTP/1.1 Codec, Connection Pool, Safe Static Open & RFC 6455 WebSockets
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`, building on `VL-004`/`VL-005` in `66baae7` + `9920bfd`).
- **Roadmap authority**: `docs/roadmap/modules/Net.md` (`M-NET-01`..`M-NET-05`), `ARCHITECTURE.md` C-02..C-06, C-11, C-13.
- **Error domain**: `Void::Result::kNetErrorDomain = 26` (`NetErrorCode` in `include/Void/Net/Http.hpp`).
## Scope & Deliverables
1. **Native Incremental HTTP/1.1 Codec (`include/Void/Net/HttpCodec.hpp`, `src/Net/HttpCodec.cpp`)**:
- `HttpCodecLimits` (defaults: `max_start_line_bytes = 8 KiB`, `max_header_bytes = 32 KiB`, `max_headers = 100`, `max_body_bytes = 8 MiB`, `max_chunk_ext_bytes = 1 KiB`, `max_trailer_bytes = 8 KiB`).
- `HttpRequestParser` and `HttpResponseParser`: byte-by-byte / arbitrary-split incremental RFC 9110/9112 state machines.
- Strict CRLF framing, header field-name token validation, rejection of duplicate/conflicting `Content-Length`, rejection of `Transfer-Encoding` + `Content-Length` smuggling ambiguity, handling of `1xx` informational responses, `HEAD`/`204`/`304` no-body responses, chunked transfer encoding with chunk extensions and trailers, close-delimited response bodies (`finish_eof()`), and explicit `connection_reusable()` check.
2. **Bounded HTTP/1.1 Connection Pool (`include/Void/Net/Pool.hpp`, `src/Net/Pool.cpp`)**:
- `PoolLimits` (defaults: `max_total_connections = 256`, `max_per_origin = 8`, `max_idle_connections = 128`, `idle_timeout = 30s`).
- `PoolKey` keyed by `{scheme, host, port, proxy_identity, tls_policy_generation}` (so changing proxy or trust generation never reuses stale connections).
- `ConnectionPool` using injectable `Void::Time::MonotonicClock` for deterministic idle eviction, returning RAII `ConnectionLease` handles that only return clean, reusable connections to the pool (`mark_reusable(true)`); abandoned/unmarked/dirty/expired leases close cleanly.
3. **Descriptor-Pinned Static File Opening (`include/Void/Net/Server.hpp`, `src/Net/Server.cpp`)**:
- `OpenedStaticFile` (move-only RAII descriptor + `content_type` + `size`, `read_all()`, `native_handle()`).
- `StaticFileResolver::open_safe(std::string_view request_path)` walking components beneath a retained root directory fd (`O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC`), rejecting symlinks/traversal/non-regular files without pathname TOCTOU.
4. **Redirect Compliance in `HttpClient` (`src/Net/Http.cpp`)**:
- Follow only `301`, `302`, `303`, `307`, `308`; `303` converts non-HEAD to `GET` and strips body + `Content-Length`/`Content-Type`; `307`/`308` preserve method/body; resolve relative `Location` references against current URL; reject HTTPS->HTTP downgrade unless `allow_insecure_redirects`; strip `Authorization`, `Cookie`, `Proxy-Authorization`, `X-Api-Key` on cross-origin hops; enforce single absolute steady deadline across redirect hops.
5. **Native RFC 6455 WebSocket Wire Framing & Loopback Transport (`include/Void/Net/WebSocket.hpp`, `src/Net/WebSocket.cpp`, `include/Void/Net/HttpServer.hpp`, `src/Net/HttpServer.cpp`)**:
- `compute_websocket_accept(key)` (RFC 6455 SHA-1 + Base64), `validate_websocket_upgrade_request()` (version 13, `Upgrade: websocket`, `Connection: Upgrade`, 16-byte base64 key, optional origin/subprotocol policy).
- `WebSocketOpcode`, `WebSocketLimits` (`max_message_bytes = 1 MiB`, `max_output_messages = 64`, `max_output_bytes = 4 MiB`), `WebSocketFrame`, `encode_websocket_frame()`, `WebSocketFrameDecoder` enforcing client masking / server non-masking, fragmentation, control-frame rules (<= 125 bytes, FIN=1), strict RFC 3629 UTF-8 validation for text frames & close reasons, ping/pong, and single close handshake.
- `HttpServer::add_websocket_route(pattern, WebSocketSessions&, WebSocketUpgradeOptions)` upgrading incoming HTTP/1.1 requests into live RFC 6455 connections integrated with `WebSocketSessions`, plus loopback `WebSocketClient` for full client/server wire verification.
## Verification
- Standalone `Net;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`): split-byte smuggling & chunked/trailer/1xx/HEAD codec corpus, pool eviction & key isolation, `open_safe` symlink-swap rejection, redirect `303`/`307`/relative/cross-origin tests, RFC 6455 wire & loopback `WebSocketClient`/`HttpServer` ping/pong/fragmented/UTF-8/close/shutdown tests.
- `ctest` `NetOnly` installed consumer, full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
@@ -0,0 +1,27 @@
# Task Spec: `M-SHORTURL-01..04` — Frozen V1, Additive V2 Local/Durable/Remote Providers & V1 Adapter
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
- **Roadmap authority**: `docs/roadmap/modules/ShortUrl.md` (`M-SHORTURL-01`..`M-SHORTURL-04`), `ARCHITECTURE.md` C-02..C-05, C-09, C-13.
- **Error domain**: `Void::Result::kShortUrlErrorDomain = 28`.
## Scope & Deliverables
1. **Frozen `V1` Contract (`include/Void/ShortUrl/ShortUrl.hpp`, `docs/short-url.md`)**:
- Zero changes to `Void::ShortUrl::V1` layout, enum ordinals, virtual table order, or `docs/short-url.md`.
- Keep `ShortUrl` module's internal dependencies lightweight (`Service Time`), with zero `Storage`, `Net`, or `Security` dependencies.
2. **Additive `Void::ShortUrl::V2` Core & Local Provider (`include/Void/ShortUrl/V2.hpp`)**:
- `V2ErrorCode` mapped via `kShortUrlErrorDomain = 28` (`InvalidUrl`, `InvalidKey`, `InvalidExpiry`, `Conflict`, `NotFound`, `Expired`, `Revoked`, `Unsupported`, `RateLimited`, `QuotaExceeded`, `IdentityExpired`, `StorageError`, `UnknownOutcome`, `ProviderError`, `Timeout`, `Unavailable`).
- `CreateLink`, `ShortenOptions` (`operation_id`, `idempotency_ttl = 24h`), `Link`, `LinkRecord`, `LinkState::{Active, Revoked}`, `LocalProviderLimits` (`max_url_bytes = 8192`, `max_key_bytes = 64`, `generated_key_length = 16`, `max_collision_retries = 8`, `max_retained_identities = 10000`, `max_entries = 100000`, `max_concurrent_ops = 128`).
- Strict target URL validation (absolute `http`/`https`, no userinfo, no control chars, <= 8 KiB, optional host deny predicate) and custom key validation (1..64 `[A-Za-z0-9_-]`, case-sensitive, reserved route rejection).
- Abstract `LinkRepositoryPort` + `RandomBytesPort`, explicitly nondurable `InMemoryLinkRepository` (for unit/semantics tests), rejection-sampled base62 key generation, atomic conditional insert + idempotency record, civil expiry via injected `Void::Time::CivilClock`, tombstone `revoke()` (never reusing revoked keys), `V1Adapter` implementing `V1::IShortener` without modifying `V1`.
3. **Durable Storage Provider (`src/ShortUrlStorage/module.cmake`, `include/Void/ShortUrlStorage/StorageRepository.hpp`, `src/ShortUrlStorage/StorageRepository.cpp`)**:
- Separate module (`INTERNAL_DEPS ShortUrl Storage Security`) keeping `ShortUrl` free of `Storage`/`libsodium`.
- `StorageLinkRepository` backed by `Void::Storage::Engine` conditional `WriteBatch` (versioned records, atomic link + idempotency commit, tombstone persistence, byte quota enforcement, full recovery across engine reopen) + `SecurityRandomBytesPort` backed by `Void::Security::random_bytes`.
4. **Remote Provider SPI (`src/ShortUrlRemote/module.cmake`, `include/Void/ShortUrlRemote/RemoteProvider.hpp`, `src/ShortUrlRemote/RemoteProvider.cpp`)**:
- Separate module (`INTERNAL_DEPS ShortUrl Net Data`) keeping `ShortUrl` free of `Net`/Boost/OpenSSL.
- `RemoteCapabilities`, `RemoteProviderOptions` (explicit origin, secure `HttpClient`, max 1 MiB response, 10s deadline), `RemoteProvider` checking capability flags before network mutation, preserving `Retry-After` and classifying transport failures after send as `UnknownOutcome` without blind replay, plus loopback fixture tests.
5. **Installed Consumers**:
- `tests/package/ShortUrlOnly/` (`ShortUrl` with zero external packages) + `ShortUrlProviders` in `tests/package/InstalledComponents.cmake`.
## Verification
- Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`), `ctest` (`ShortUrlOnly`, `ShortUrlProviders`), full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
@@ -0,0 +1,28 @@
# Task Spec: `M-TESTINGMOCK-01..04` — Deterministic Sessions, Action-Outside-Lock, Move-Only Forwarding & Matcher Combinators
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
- **Roadmap authority**: `docs/roadmap/modules/TestingMock.md` (`M-TESTINGMOCK-01`..`M-TESTINGMOCK-04`), `ARCHITECTURE.md` C-02..C-05.
- **Error domain**: `Void::Result::kTestingMockErrorDomain = 27`.
## Scope & Deliverables
1. **Preserve 1.x API & Existing Tests**:
- Existing `Mock<Derived>`, `MockBase`, `MockFunction<R(Args...)>`, `Matcher<T>`, `Eq`, `_`, `Lt`, `Le`, `Gt`, `Ge`, `Range`, `Pred`, `StartsWith`, `Contains`, and all existing tests under `tests/standalone/TestingMock/` continue compiling and passing unchanged.
2. **Matcher Combinators (`include/Void/TestingMock/Matcher.hpp`)**:
- Add `Ne`, `EndsWith`, `Not`, `AllOf`, `AnyOf`, `IsNull`, `NotNull`, with bounded description/nesting depth (`kMaxMatcherDepth = 32`).
3. **Explicit Session, Sequences, Limits & Tokens (`include/Void/TestingMock/Session.hpp`)**:
- `Concurrency::{SingleThread, ConcurrentActions}`.
- `MockLimits{max_expectations = 1024, max_matchers = 64, max_events = 4096, max_diagnostic_bytes = 4 MiB, max_arg_render_bytes = 4 KiB}` (zero means zero capacity, never unlimited).
- `Sequence`: explicit per-group call ordering independent of global registration order.
- `Verification`: structured report (`ok()`, `unmet`, `excess`, `unmatched`, `prohibited`, `matcher_errors`, `threading_errors`, `events_truncated`, `total_events`, `format()`), idempotent across repeated calls.
- `MockSession`: `freeze(Concurrency)` (mutating a frozen session returns `ErrorKind::invalid_argument` / `InvalidState`), `verify_and_close()` (drains/joins active calls; returns `WouldDeadlock` if called from inside an active action), bounded event log with truncation tracking, RAII `RegistrationToken` stopping admission and waiting for admitted calls on unregister.
4. **Hardened `Expectation` & `SessionMockFunction` (`include/Void/TestingMock/Expectation.hpp`, `include/Void/TestingMock/MockFunction.hpp`)**:
- Action-outside-lock reservation protocol: snapshot immutable candidates under short lock -> evaluate matchers outside lock (catching matcher exceptions as `MatcherFailure`) -> reacquire lock to reserve matching unsaturated expectation & sequence slot -> release lock -> execute action -> decrement in-flight counter & record completion.
- Same-thread reentrant calls succeed in `SingleThread`; cross-thread concurrent entry in `SingleThread` reports deterministic threading violation; `ConcurrentActions` permits concurrent action execution safely.
- Perfect argument forwarding (`Args&&...`) to actions; `returns_once(U&&)` for move-only return types (`std::unique_ptr`), `invokes_once(F&&)` for one-shot move-only callables, `at_least(n)`, `at_most(n)`, `between(min, max)`, `never()` (checked before ordinary candidates), `in_sequence(Sequence&)`.
- Non-default-constructible return type on unmatched call records failure and throws TestingMock's invocation-abort exception (never `R{}` fallback).
5. **Installed Consumer (`tests/package/TestingMockOnly/`)**:
- Register `TestingMockOnly` in `tests/package/InstalledComponents.cmake` with `_no_external_deps`.
## Verification
- Standalone `TestingMock;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`), `ctest` `TestingMockOnly`, Debug `ASan+UBSan`, Debug `TSan` (concurrent action reservation & dynamic unregister races).
+118
View File
@@ -0,0 +1,118 @@
# 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})`.
After a `{}` sleep, ALWAYS call `resume(now, options.stop.stop_requested())` — it re-checks stop itself,
which covers the TimerQueue choice where a late stop yields `{}`. Any sleep error ends the retry without
calling `resume()` (amended after W11-REVIEW-B1b: resuming after `stopped`/`overloaded` would start
attempts with no wait). 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.
+166
View File
@@ -0,0 +1,166 @@
# M-TIME-03 — Injected-deadline domains: Async TimerQueue and clock saturation (step B1)
Task ID: M-TIME-03
Role: opus-implementer
Status: READY
## 1. Context and baseline
- Wave 11 package step B1 (TimerQueue part). The `Async::retry_async` part of M-TIME-03 is a
separate later step (B1b) after M-FUNCTIONAL-03 integrates (gate G1); it is OUT of this assignment.
- Repo: VoidLibrary, branch `feat/roadmap-p2-wave11`, HEAD `7f95f89`. You work in an isolated git
worktree of `7f95f89`; 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:
- `include/Void/Time/Clock.hpp`: `MonotonicClock{ using time_point = steady_clock::time_point; now() }`
(:19-26), `ManualClock` starts at epoch 0 and is atomic (~:69-130), `remaining_until` (~:188-208).
`src/Time/module.cmake` has no deps.
- `include/Void/Async/Detail/Types.hpp`: `AdmissionError{overloaded, stopped, deadline_expired,
invalid_argument, self_join}` (:15-21), `AsyncErrorCode` incl. NEW `closed = 9` (→cancelled, added
in `7f95f89`), `OperationOptions{stop_token stop; optional<MonotonicClock::time_point> deadline}`
(:45-48), `is_deadline_expired(options, clock = System)` (:50-56), `make_async_error`.
- `include/Void/Async/Operation.hpp` (`OperationState`, `ResumeTicket`, backend refs, terminal
state machine), `Executor.hpp` (`Executor::post_completion`, `ManualExecutor`, `ScheduleStatusAwaiter`
checks deadline only in `await_ready/await_resume` ~:304-359), `Task.hpp` (`Coro::Task`),
`TaskScope.hpp`. No timer primitive exists in `include/Void/Async`.
- `src/Async/module.cmake`: `INTERNAL_DEPS Functional Time LogState` (unchanged by this task).
- 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
(one terminal result, injected clocks); decisions D-038 (F12), D-W11-01, D-W11-14.
## 2. Objective and deliverables
1. NEW `include/Void/Async/Timer.hpp`: `TimerQueue`, `TimerHandle`, `TimerEvent`, `TimerCallback`,
`TimerQueueOptions` (header-only, like the rest of Async).
2. EDIT `include/Void/Time/Clock.hpp`: NEW `saturating_add`, `deadline_after` helpers.
3. NEW tests `tests/standalone/Async/TimerQueue.cpp`, `tests/standalone/Async/DeadlineDomains.cpp`
(schedule_on/scope admission part only), `tests/standalone/Time/ClockSaturation.cpp`.
## 3. Scope and non-goals
In: the above. Out: `Async/Retry.hpp`/`retry_async` and `AsyncRetry.cpp` (step B1b), any change to
existing Async/Time symbols or their default-argument clocks, Runtime-managed timer polling
(D-W11-14), build files.
## 4. Files to inspect
`include/Void/Async/{Operation,Executor,Task,TaskScope}.hpp`, `include/Void/Async/Detail/Types.hpp`,
`include/Void/Time/Clock.hpp`, `tests/standalone/Async/{OperationScope,Executor}.cpp` (test style and
ManualExecutor/ManualClock usage), `src/IO/EpollDriver.cpp:739-834` (how IO settles deadline expiry via
an injected clock on poll — pattern to mirror), `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`
§M-TIME-03 and `W11-PLAN-REV1-OUTPUT.md` F12 (design source).
## 5. Write ownership and coordination
Write scope: `include/Void/Async/Timer.hpp` (NEW), `include/Void/Time/Clock.hpp`,
`tests/standalone/Async/TimerQueue.cpp` (NEW), `tests/standalone/Async/DeadlineDomains.cpp` (NEW),
`tests/standalone/Time/ClockSaturation.cpp` (NEW).
Forbidden: everything else, notably `Executor.hpp`, `Operation.hpp`, `TaskScope.hpp`,
`Detail/Types.hpp`, Functional headers (M-FUNCTIONAL-03 is concurrently adding
`Functional/RetryState.hpp` in another worktree), build files, docs. No git commit/branch/stash/reset.
## 6. Implementation or investigation approach
1. Add Clock helpers (overflow-safe; `saturating_add` clamps to `time_point::max()`/`min()`;
`deadline_after(clock, d)` = `saturating_add(clock.now(), d)`; negative `d` allowed and saturates low).
2. Implement `TimerQueue` as a stable min-heap of `(deadline, seq)` entries holding
`shared_ptr<detail::TimerEntry>`; cancelled entries become tombstones; compact when tombstones
exceed `max_timers` so heap size never exceeds `2 × max_timers`.
3. `poll_expired()` reads `clock().now()` once, pops all due live entries in `(deadline, seq)` order
under the lock, transitions each entry pending→fired atomically, then invokes callbacks OUTSIDE
the lock. Nothing fires without an explicit `poll_expired()` call; no background thread.
4. `sleep_until`/`sleep_for` awaitables: register a timer and a stop callback; settle through
`OperationState` (or an equivalent single-terminal-result guard) so exactly one of
{expired → `{}`, stop → `cancelled`, `options.deadline` earlier → `timeout`, `close` → `stopped`}
wins; the continuation is always resumed via `executor().post_completion(handle)`, never inline
from a stop callback or from `poll_expired` itself. Stop/deadline checks before admission return
immediately (still via the awaitable's result, no suspension needed).
5. `close()`: marks closed; every pending entry's callback runs once with `TimerEvent::closed`
(sleepers settle `stopped`); later `schedule_at`/`sleep_*` return `stopped`. Destructor = close.
The executor must outlive the queue (document).
6. Tests per §10; build/run per §11.
## 7. Interfaces and data contracts
```cpp
namespace Void::Time { // Clock.hpp additions (NEW)
[[nodiscard]] MonotonicClock::time_point saturating_add(MonotonicClock::time_point, std::chrono::nanoseconds) noexcept;
[[nodiscard]] MonotonicClock::time_point deadline_after(const MonotonicClock&, std::chrono::nanoseconds) noexcept;
}
namespace Void::Async { // Timer.hpp (NEW)
struct TimerQueueOptions { std::size_t max_timers{1024}; }; // 0 → invalid_argument
enum class TimerEvent : std::uint8_t { expired, closed };
using TimerCallback = std::move_only_function<void(TimerEvent) noexcept>;
class TimerHandle { // move-only; holds shared_ptr<detail::TimerEntry>
public: TimerHandle() noexcept = default;
bool cancel() noexcept; // true ⇒ callback never runs; safe after queue destroyed
[[nodiscard]] bool valid() const noexcept; };
class TimerQueue { // non-copyable, non-movable
public:
using time_point = Void::Time::MonotonicClock::time_point;
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
create(Executor& completion_executor, const Void::Time::MonotonicClock& clock, TimerQueueOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_until(time_point when, OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_for(std::chrono::nanoseconds, OperationOptions = {});
[[nodiscard]] std::expected<TimerHandle, AdmissionError> schedule_at(time_point when, TimerCallback on_event);
[[nodiscard]] std::size_t poll_expired(); // returns callbacks fired
[[nodiscard]] std::optional<time_point> next_deadline() const;
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept; // 0 if due; uses injected now
[[nodiscard]] std::size_t active_timers() const noexcept;
void close() noexcept;
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept;
[[nodiscard]] Executor& executor() noexcept;
~TimerQueue(); // = close()
};
}
```
Result errors use `make_async_error`: `overloaded` (at `max_timers` live timers), `stopped` (after
close), `cancelled` (stop token), `timeout` (`options.deadline` reached first), `invalid_argument`.
`schedule_at` returns `AdmissionError::{overloaded, stopped, invalid_argument}`. Callback exactly-once
rule: runs exactly once with `expired` or `closed`, or never if `cancel()` returned true. If
`std::move_only_function` is unavailable in the toolchain, report it (do not substitute silently).
## 8. Dependencies and integration
Upstream: M-TIME-02, M-ASYNC-02/03 (done). Downstream consumers (later steps): `AsyncChannel`
deadlines (M-ASYNC-04, gate G2), `retry_async` (B1b), `IO::PumpOptions::timers` (S-IO-04). Keep the
interface exactly as written. Root integrates and commits.
## 9. Edge cases security and performance
Stop vs poll vs close races (TSan), equal deadlines FIFO by seq, `when` in the past (fires on next
poll), ManualClock starting at epoch 0 and at a far-future point, never compare manual-domain
deadlines with the host clock, cancel during callback dispatch, callback that schedules a new timer
(must not deadlock: callbacks run outside the lock), destruction with pending sleepers, tombstone
growth bounded, no busy loops, no allocation per poll beyond the due batch.
## 10. Acceptance criteria
1. `TimerQueue.cpp`: `timer_manual_advance_and_poll_fires_exactly_once`,
`timer_equal_deadlines_fire_in_submission_order`, `timer_not_fired_without_explicit_poll`,
`timer_manual_epoch_deadline_not_compared_with_host_clock`, `timer_manual_clock_far_future_initial_point`,
`timer_stop_before_admission_and_pending_cancelled_once`, `timer_stop_vs_poll_race_single_result_tsan`,
`timer_capacity_overloaded_and_tombstone_bounded`, `timer_schedule_at_cancel_vs_fire_exclusive`,
`timer_close_settles_pending_stopped`, `timer_wait_duration_uses_injected_now`,
`timer_sleep_for_saturates`, `timer_handle_cancel_after_queue_destroyed_safe`,
`timer_callback_schedules_new_timer_no_deadlock` — all pass.
2. `DeadlineDomains.cpp`: `deadline_domain_schedule_on_and_scope_admission_injected_clock` and
`deadline_domain_timer_and_operation_deadline_same_manual_clock` (an `OperationOptions.deadline` in
the ManualClock domain expires a `sleep_until` once only after advance + poll) — pass.
3. `ClockSaturation.cpp`: `clock_saturating_add_and_deadline_after_bounds` — passes.
4. Existing `Clock`, `Stopwatch`, `OperationScope`, `Executor`, `Coro` tests pass unchanged.
5. `-Werror` clean; Debug TSan run of the new suites reports 0 races; ASan+UBSan 0 errors.
## 11. Verification commands and evidence
Cwd = your worktree root. Run `dev` with the sandbox disabled (dangerouslyDisableSandbox) — nix
fetcher lock fails inside it. Confirm the new suites appear in output (tests needing unselected
modules are silently skipped).
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3 --parallel 8 && /tmp/void-w11-time3/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains|ClockSaturation|Clock|Stopwatch|OperationScope|Executor|Coro)\." && ctest --test-dir /tmp/void-w11-time3 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-tsan --parallel 8 && /tmp/void-w11-time3-tsan/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains)\."'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-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-time3-asan --parallel 8 && /tmp/void-w11-time3-asan/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains|ClockSaturation)\."'
```
## 12. Constraints and stop conditions
No edits outside write scope; no weakened assertions or disabled warnings; no changes to existing
Async/Time semantics. Stop and report BLOCKED if the contract needs an edit to a forbidden file (e.g.
`Operation.hpp`), if `std::move_only_function` is unavailable, or a failure originates outside your files.
## 13. Authorization and decisions
Root decisions D-034, D-038 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 (test counts, TSan/ASan outcome); checks not run; residual
risks; integration notes (worktree path). Do not spawn children.
@@ -0,0 +1,39 @@
# S-DISCOVERY-01..04 — Discovery Subsystem (Catalog, Leases, Watches, Selectors, Optional RPC Adapter)
## Scope
Implement the P1–P3 native `Void::Discovery` subsystem per `docs/roadmap/subsystems/Discovery.md` and `docs/roadmap/DEPENDENCIES.md`, plus the optional `Void::DiscoveryRpc` endpoint adapter living strictly above `RPC` and `Discovery`:
1. **`S-DISCOVERY-01` — Boundary, Error Domain, and Immutable Value Contracts**:
- Module `src/Discovery/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero network, storage, or consensus dependencies.
- Error domain `kDiscoveryErrorDomain = 30` with `DiscoveryErrorCode` covering validation, conflict, cap exhaustion, expiry, stale/unavailable freshness, cancellation, and self-join diagnosis.
- Strict endpoint/attribute validation before publication (valid scheme/host/port, `weight > 0`, `max_attributes_per_record = 16`, `max_metadata_bytes_per_record = 4096`, `max_services = 1024`, `max_endpoints_per_service = 256`, `max_total_records = 10000`).
2. **`S-DISCOVERY-02` — Pure Catalog, Atomic Static Snapshots, and Local RAII Registrations**:
- Pure `Catalog` construction creating zero hidden threads.
- Atomic candidate `replace_static()` rejecting invalid/conflicting candidates while preserving the active revision; explicit `provider_generation` bump resets revision domain and emits `ResyncRequired`.
- Local move-only RAII `Registration` handles with explicit `LeasePolicy` (default 30s TTL / 10s renew interval via injected `MonotonicClock`; zero TTL rejected as `InvalidArgument`; unleased explicit mode valid until release; static entries never expire).
- Duplicate `(service, instance)` returns `Conflict` without stealing existing handles.
- Deterministic `resolve()` sorted by `instance`, filtering logically expired records before cleanup runs, respecting `ResolvePolicy::allow_stale` and `Freshness`.
3. **`S-DISCOVERY-03` — Bounded Watches, Resync, Client Selectors, and Managed Renewal**:
- Bounded `watch()` (`max_watches = 1024`, `max_events_per_watch = 64`, shared `16 MiB` event budget) emitting `InitialSnapshot`, serialized per-watch `Delta`, and explicit `ResyncRequired` + full latest `Snapshot` on overflow or provider-generation reset.
- Callbacks run outside catalog and watch locks; `cancel()` stops new admission (including self-cancel inside a callback); `join()` drains admitted callbacks and diagnoses synchronous self-join (`SelfJoin`) instead of deadlocking.
- `Catalog::shutdown_and_join()` removes local entries, cancels watches, and joins admitted callbacks; destructor only requests stop.
- `WeightedRoundRobinSelector`, stable HRW `AffinitySelector`, and deterministic `ManagedLeaseRenewer`.
4. **`S-DISCOVERY-04` — Optional RPC Integration (`DiscoveryRpc`)**:
- Separate module `src/DiscoveryRpc/module.cmake` (`INTERNAL_DEPS Discovery RPC`) so `RPC` remains completely independent of `Discovery`.
- `EndpointResolverClient` resolves endpoints from `Discovery::Catalog`, selects via client selector, preserves configured `expected_tls_name` / identity across IP/address refreshes (rejecting TLS scheme/identity downgrade), and executes unary calls via `Void::RPC::Client`.
## File Ownership
- `include/Void/Discovery/{Types,Catalog}.hpp`
- `src/Discovery/{module.cmake,Catalog.cpp}`
- `include/Void/DiscoveryRpc/EndpointAdapter.hpp`
- `src/DiscoveryRpc/{module.cmake,EndpointAdapter.cpp}`
- `tests/standalone/Discovery/Catalog.cpp`
- `tests/standalone/DiscoveryRpc/EndpointAdapter.cpp`
- `tests/package/DiscoveryOnly/{CMakeLists.txt,main.cpp}`
- `tests/package/InstalledComponents.cmake`
## Acceptance & Verification
- Standalone `Discovery;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `DiscoveryOnly` consumer with `_no_external_deps`.
- `DiscoveryRpc` identity-preserving refresh + RPC round-trip tests; `RpcOnly` remains Discovery-free.
- Deterministic fake-clock lease expiry/renewal, atomic bad/good config replacement, duplicate registration conflict, watch overflow -> `ResyncRequired`, self-cancel/self-join, and selector determinism.
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
+318
View File
@@ -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.
+134
View File
@@ -0,0 +1,134 @@
# S-IO-04 — Embedded pumping (`Driver::run`, `pump_until`), joined-shutdown conformance
Task ID: S-IO-04
Role: sonnet-implementer
Status: READY
## 1. Context and baseline
- Wave 11 package step A4 (gate G4: S-IO-03 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 ⊘); the branch adds RetryState, TimerQueue,
retry_async and S-IO-03 (IoFile 33 tests).
- Observed source after S-IO-03 (see `docs/agent-workflow/tasks/S-IO-03.md` and its implementer notes):
- `include/Void/IO/Driver.hpp`: `poll_once(max_wait)` returns `IoErrorCode::busy` for three causes
(reentrant call on this backend, concurrent poller, shutdown taking over poll ownership) without
touching fds; after shutdown completes it returns 0 immediately. Public inline wrappers
`begin_shutdown()`, `shutdown(Async::OperationOptions)` → `DriverShutdownReport`, `quiescent()`,
`shutdown_complete()`; `request_stop()` == `begin_shutdown()`. Shutdown dispatches resume tickets on the
thread that called `shutdown()`, after releasing poll ownership; the executor must outlive the Driver.
- Mock backend: `poll_once` ignores `max_wait` (never blocks); requests held by a `MockController`
token keep `pending_operations > 0` even when the report says `complete == true`.
- `include/Void/Async/Timer.hpp`: `TimerQueue::{poll_expired, wait_duration(max_wait), next_deadline}`.
- `include/Void/Async/TaskScope.hpp`: `join_pumping` drains the executor but never polls IO.
- SystemAsync `ProcessManager` borrows a `Driver` (`include/Void/System/AsyncProcess.hpp`,
`src/SystemAsync/AsyncProcess.cpp`). Net does not use IO (Net adapter deferred, D-W11-07).
- Requirements: roadmap row S-IO-04 ("Embedded pumping, joined shutdown, SystemAsync conformance (Net
adapter deferred) | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net
dependency"); C-03..C-06; decisions D-038, D-040 (N3 loop rules), D-042 (S9 split).
## 2. Objective and deliverables
1. EDIT `include/Void/IO/Driver.hpp`: NEW inline `Driver::run(std::stop_token, std::chrono::nanoseconds max_wait = 5ms)`.
2. NEW `include/Void/IO/Pump.hpp`: `PumpOptions`, `pump_until`.
3. NEW tests `tests/standalone/IO/IoShutdown.cpp`, `tests/standalone/IO/IoPump.cpp`,
`tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`.
## 3. Scope and non-goals
Out: any change to `src/IO/*`, `include/Void/IO/{Types,File}.hpp`, `include/Void/IO/Detail/*`, Async
headers, SystemAsync sources, Runtime, Net adapter, build files. If a defect in the S-IO-03 primitives is
found, STOP and report it with a reproducer (root owns the fix).
## 4. Files to inspect
`include/Void/IO/{Driver,Types,File,Stream}.hpp`, `include/Void/IO/Detail/Backend.hpp` (read-only),
`include/Void/Async/{Timer,Executor,TaskScope}.hpp`, `include/Void/System/AsyncProcess.hpp`,
`tests/standalone/IO/{IoDriver,IoFile}.cpp`, `tests/standalone/SystemAsync/*.cpp`,
`docs/agent-workflow/tasks/W11-CONTRACT-R2.md` N3, `W11-PLAN-OUTPUT.md` §S-IO-04.
## 5. Write ownership and coordination
Write scope: `include/Void/IO/Driver.hpp` (only the NEW `run` declaration/definition), `include/Void/IO/Pump.hpp` (NEW),
`tests/standalone/IO/IoShutdown.cpp` (NEW), `tests/standalone/IO/IoPump.cpp` (NEW),
`tests/standalone/SystemAsync/SystemAsyncShutdown.cpp` (NEW).
Forbidden: every other path. Other implementers work concurrently in other worktrees (Async EventBus/
Observable; Runtime). No git operations except the authorized fast-forward.
## 6. Implementation or investigation approach
MANDATORY:
- `run(stop, max_wait)`: loop until `stop.stop_requested()` or `shutdown_complete()`; each iteration calls
`poll_once(max_wait)`; on `busy` wait up to `max_wait` in ≤1 ms stop-aware slices and retry; on a mock
backend (or any turn that did no work and returned immediately) wait up to `max_wait` stop-aware so the
loop never busy-spins; propagate any other error; return the accumulated work count. Never closes,
frees or joins anything.
- `pump_until(driver, manual, done, options)`: loop: `done()` → return count; `options.operation.stop`
requested → `cancelled`; `options.operation.deadline` reached per `driver.clock()` → `timeout`;
`max_turns` exceeded → `IoErrorCode::exhausted`; otherwise one turn = `poll_once(wait)` with
`wait = timers ? timers->wait_duration(max_wait) : max_wait` (0 when work is runnable), then
`timers->poll_expired()` if set, then drain `manual`; `busy` handled as in `run`; exits when
`shutdown_complete()` and `done()` still false → returns the current count (caller decides). Never frees
work; all waits re-read the injected clock.
- Shutdown conformance tests use the public S-IO-03 API only: an expired `shutdown(options)` returns
`complete=false` and retains fds/buffers/workers; a repeat call completes after release; concurrent
`run()` loop + `shutdown()` is TSan-clean and the run loop exits on `shutdown_complete()`.
- Layering: no `Void/Runtime`, `Void/Net`, `Void/System` include in `include/Void/IO` or `src/IO`
(SystemAsync test lives under `tests/standalone/SystemAsync/`).
## 7. Interfaces and data contracts
```cpp
namespace Void::IO {
// Driver.hpp (NEW member, inline)
[[nodiscard]] Void::Result::Result<std::size_t> Driver::run(std::stop_token stop,
std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5});
// Pump.hpp (NEW)
struct PumpOptions { std::chrono::nanoseconds max_wait{0}; std::size_t max_turns{1u << 20};
Async::OperationOptions operation{}; Async::TimerQueue* timers{nullptr}; };
template <class Done> requires std::predicate<Done&>
[[nodiscard]] Void::Result::Result<std::size_t> pump_until(Driver&, Async::ManualExecutor&, Done&& done,
PumpOptions = {});
}
```
Errors: `IoErrorCode::{cancelled, timeout, exhausted}` via `make_io_error`; `busy` is never returned by
`run`/`pump_until`. Unchanged: every existing Driver member.
## 8. Dependencies and integration
Upstream: S-IO-03, M-TIME-03 (TimerQueue). Downstream: S-RUNTIME-03 `shutdown_pumping` uses `pump_until`
(gate G5); the Runtime reactor follows the same `busy`/mock wait rules. Root integrates and commits.
## 9. Edge cases security and performance
Spurious `busy` during shutdown handoff; mock never blocks; `max_wait == 0`; stop already requested;
deadline already expired; timers with nothing due; `done()` true initially; executor work that posts more
work; no allocation per turn; no busy loops (assert bounded iteration counts with a fake/injected clock).
## 10. Acceptance criteria
- `IoShutdown.cpp`: `io_shutdown_expired_budget_incomplete_retains_stalled_file_worker`,
`io_shutdown_pending_socket_read_retains_buffer_until_delivery`, `io_shutdown_repeated_idempotent_after_complete`,
`io_shutdown_concurrent_with_run_loop_tsan`, `io_run_stops_on_token_and_on_shutdown`,
`io_begin_shutdown_rejects_new_admission`, `io_run_busy_and_mock_wait_does_not_spin`.
- `IoPump.cpp`: `io_pump_until_scope_join_mock`, `io_pump_until_deadline_injected_clock`,
`io_pump_until_max_turns_exhausted`, `io_pump_until_drives_timer_queue`, `io_pump_until_stop_cancelled`,
`io_pump_until_exits_after_shutdown_complete`.
- `SystemAsyncShutdown.cpp`: `systemasync_driver_shutdown_pending_pipe_read_retains_and_delivers_once`.
- Existing `IoDriver`, `IoFile`, `SystemAsync` tests pass; TSan 0 races; ASan+UBSan 0 errors; `-Werror`
syntax checks clean; layering `rg` empty; `git diff --stat -- src/IO/module.cmake` empty.
- Test caveats: keep each test well under 1,000 assertions (X-QA-02; count in loops, assert once) and keep
each test declaration on ONE line (X-QA-03).
## 11. Verification commands and evidence
Cwd = worktree root; `dev` with the sandbox disabled. Confirm new suites appear in the output.
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io4 -G Ninja -DVOID_ENABLED_MODULES="IO;SystemAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io4 --parallel 8 && /tmp/void-w11-io4/tests/VoidTests --filter "^(IoShutdown|IoPump|IoFile|IoDriver|SystemAsyncShutdown|SystemAsync)\." && ctest --test-dir /tmp/void-w11-io4 --output-on-failure --timeout 120'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io4-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;SystemAsync;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-io4-tsan --parallel 8 && /tmp/void-w11-io4-tsan/tests/VoidTests --filter "^(IoShutdown|IoPump|SystemAsyncShutdown|IoFile)\."'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io4-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;SystemAsync;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-io4-asan --parallel 8 && /tmp/void-w11-io4-asan/tests/VoidTests --filter "^(IoShutdown|IoPump|SystemAsyncShutdown)\."'
dev cpp-gcc -c bash -lc 'for f in IO/IoShutdown IO/IoPump SystemAsync/SystemAsyncShutdown; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/$f.cpp || exit 1; done'
rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO # expect no output
```
## 12. Constraints and stop conditions
No edits outside write scope; no weakened assertions. Stop and report BLOCKED with a reproducer if an
S-IO-03 primitive misbehaves (deadlock, spin, wrong report), if SystemAsync needs a source 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,41 @@
# S-MESSAGING-01..04 — Messaging Subsystem (Delivery Model, Ephemeral Queue, Durable Storage Queue, Outbox/Inbox, RPC Adapter)
## Scope
Implement the P1–P3 native `Void::Messaging` subsystem, `Void::MessagingStorage` durable adapter + outbox/inbox helper, and `Void::MessagingRpc` remote adapter per `docs/roadmap/subsystems/Messaging.md` and `docs/roadmap/DEPENDENCIES.md`:
1. **`S-MESSAGING-01..02` — Delivery Model, Receipts, State Machine, and Bounded Ephemeral Queue**:
- Module `src/Messaging/module.cmake` (`INTERNAL_DEPS Core Functional Binary Time Async`) with zero `Storage`, `Net`, or `RPC` dependency.
- Error domain `kMessagingErrorDomain = 32` (`MessagingErrorCode`).
- Explicit `PublishDurability::{Memory, Durable}`: `InMemoryQueue` strictly rejects `PublishDurability::Durable` (`UnsupportedDurability`) and `PublishReceipt` records exact durability so nondurable channels never claim durable success.
- Native state machine `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`.
- FIFO per-queue competing consumers and `ConsumerMode::SingleActive` (blocking group head on retry until ack).
- Visibility timeout (default 30s, explicit extension up to 5m via injected `MonotonicClock`), stale-receipt fencing (`StaleReceipt`), idempotent repeat ack, retry bound (default 5 attempts, full jitter 1s..60s via injectable RNG), corrupt-payload quarantine, and bounded caps (768 KiB message, 8 KiB / 32 headers, 1024 queues, 32 groups/queue, 64 in-flight/group, 1024 waiting receives, 64 MiB transient payload budget).
- Clean `close_and_join()` stopping admission, waking/cancelling waiting receives, and draining active deliveries.
2. **`S-MESSAGING-03` — Durable Storage Queue (`MessagingStorage`)**:
- Module `src/MessagingStorage/module.cmake` (`INTERNAL_DEPS Messaging Storage`).
- `StorageQueue` persists payload, sequence, group state, delivery generation/attempt, DLQ records, and bounded 24h / 100k publish idempotency ledger via `Void::Storage::Engine` conditional batches (`Durability::Sync`).
- At idempotency capacity, rejects new publish (`IdempotencyCapacityExceeded`) instead of silently evicting live contracts.
- On restart/reopen, promotes all prior `InFlight` records to `Pending` with bumped generation so stale worker receipts fail with `StaleReceipt`, preserving attempt counters across restarts.
- Atomic DLQ move (DLQ insert + source group removal in one `Storage::Batch`); when DLQ or persistent quota is full, keeps the message durable, drops zero data, blocks affected admission, and exposes `stuck_dlq_count()`.
- Explicit `RetentionPolicy::BlockAtQuota` default (unread work never silently expired) vs opt-in `DropOldestLossy`, pausing expiry when civil clock health fails; `UnknownOutcome` surfaced on uncertain storage commit.
3. **`S-MESSAGING-04` — Outbox/Inbox Local-Batch Helper and Remote RPC Adapter (`MessagingRpc`)**:
- `OutboxInbox` helper in `MessagingStorage` enabling single-batch local business mutation + outbox insert and single-batch local effect + inbox dedup insert, with explicit documentation that external effects remain outside the local batch boundary.
- Separate module `src/MessagingRpc/module.cmake` (`INTERNAL_DEPS Messaging RPC`) exposing `RpcQueueServer` and `RpcQueueClient` for remote `publish`, `receive`, `ack`, `nack`, and `query_receipt` over Wire v1 unary RPC.
## File Ownership
- `include/Void/Messaging/{Types,Queue}.hpp`
- `src/Messaging/{module.cmake,Queue.cpp}`
- `include/Void/MessagingStorage/{StorageQueue,OutboxInbox}.hpp`
- `src/MessagingStorage/{module.cmake,StorageQueue.cpp}`
- `include/Void/MessagingRpc/RpcAdapter.hpp`
- `src/MessagingRpc/{module.cmake,RpcAdapter.cpp}`
- `tests/standalone/Messaging/Messaging.cpp`
- `tests/standalone/MessagingStorage/StorageQueue.cpp`
- `tests/standalone/MessagingRpc/RpcAdapter.cpp`
- `tests/package/MessagingOnly/{CMakeLists.txt,main.cpp}`
- `tests/package/InstalledComponents.cmake`
## Acceptance & Verification
- Standalone `Messaging;MessagingStorage;MessagingRpc;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `MessagingOnly` consumer with `_no_external_deps`.
- Deterministic tests for ephemeral/durable separation, competing vs single-active ordering, visibility expiry & stale receipt fencing, idempotent ack/publish, restart recovery preserving attempts, poison -> atomic DLQ move, DLQ/quota/idempotency cap pressure, clock-health pause, outbox/inbox single-batch atomicity, and remote RPC round-trip.
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
+30
View File
@@ -0,0 +1,30 @@
# Task Spec: `S-RPC-01..03` — NEW `Void::RPC` Subsystem (Wire v1 Binary Codec & Unary HTTP/1.1 Transport)
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
- **Roadmap authority**: `docs/roadmap/subsystems/RPC.md` (`S-RPC-01`..`S-RPC-03`), `ARCHITECTURE.md` C-02..C-07, C-11..C-13.
- **Error domain**: `Void::Result::kRpcErrorDomain = 29`.
## Scope & Deliverables
1. **Module Boundary (`src/RPC/module.cmake`)**:
- `void_add_module(RPC INTERNAL_DEPS Core Functional Binary Data Time Async Net)`.
- Zero dependency on `Coordination`, `Discovery`, `Replication`, `Security`, or platform hosts.
2. **Types & Limits (`include/Void/RPC/Types.hpp`)**:
- `RpcStatusCode` (`Ok`, `Cancelled`, `InvalidArgument`, `DeadlineExceeded`, `NotFound`, `PermissionDenied`, `Unauthenticated`, `ResourceExhausted`, `FailedPrecondition`, `Unimplemented`, `Unavailable`, `Internal`, `DataLoss`, `UnknownOutcome`, `ProtocolError`, `IncompatibleVersion`).
- `MethodId{service, method}`, `PrincipalView` (immutable authenticated principal attributes), `MetadataEntry`, `MethodDescriptor{id, service_name, method_name, schema_version, replay_safe}`.
- `RpcLimits`: `max_header_bytes = 16 KiB`, `max_metadata_entries = 64`, `max_payload_bytes = 4 MiB`, `max_client_calls = 1024`, `max_server_executing = 256`, `max_server_queued_bytes = 64 MiB`, `max_server_timeout = 30s`.
3. **Wire v1 Binary Envelope Codec (`include/Void/RPC/Codec.hpp`, `src/RPC/Codec.cpp`)**:
- Explicit network byte order via `Void::Binary::Writer`/`Reader`:
- 4-byte magic `VRPC`, `u16 major (1)`, `u16 minor (0)`, `u32 header_length`, `u32 total_length`, `u8 frame_kind`, `u8 flags`, `u16 reserved (0)`, 128-bit `call_id` (`Uuid`), `u64 service_id`, `u32 method_id`, `u32 schema_version`, `u32 remaining_timeout_ms`, `u16 status_code`, `u16 metadata_count`, length-delimited metadata pairs, payload bytes.
- Strict bounds/overflow checks BEFORE allocating metadata/payload; rejects bad magic, unsupported major, non-zero reserved field, unknown required flags, truncated/extra bytes, oversized header/metadata/payload; skips unknown optional minor trailing header extensions cleanly.
4. **Unary HTTP/1.1 Server & Client (`include/Void/RPC/Rpc.hpp`, `src/RPC/Rpc.cpp`)**:
- `CallContext` (`call_id`, `principal`, local steady `deadline`, `remaining_timeout()`, `metadata`, `stop`).
- `AuthHook` (`authenticate(headers, metadata) -> Result<PrincipalView>` and `authorize(MethodDescriptor, PrincipalView) -> Result<void>`) executed outside dispatch locks before handler admission.
- `Server`: binds methods returning move-only RAII `Registration` (destructor/explicit `unregister_and_drain()` stops admission and waits for in-flight calls), mounts `/void-rpc/v1/call` on `Void::Net::HttpServer`, validates wire v1 envelope, schema version, auth/authz, concurrency/payload budgets, clamps relative timeout to `limits.max_server_timeout`, executes handlers outside locks, and translates handler errors/exceptions into sanitized `RpcStatus`.
- `Client`: encodes wire v1 unary request envelope, sends HTTP/1.1 POST to `/void-rpc/v1/call` via `Void::Net::HttpClient`, propagates remaining relative timeout and `std::stop_token`, separates HTTP transport failures from RPC domain status, enforces client concurrency & payload limits, never implicitly retries non-`replay_safe` methods.
5. **Installed Consumer (`tests/package/RpcOnly/`)**:
- Register `RpcOnly` in `tests/package/InstalledComponents.cmake` proving `Void::RPC` links cleanly without `LibArchive`, `PkgConfig`, or `SQLite3`.
## Verification
- Standalone `RPC;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`): wire v1 round-trip, overflow/truncation/unknown-major/reserved-flag rejection, loopback unary calls, schema mismatch, auth/authz denial, deadline clamping, handler exception sanitization, unregister drain under concurrent load.
- `ctest` (`RpcOnly`), full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
@@ -0,0 +1,224 @@
# S-RUNTIME-02/03 — Host start, readiness, failed-start cleanup, structured shutdown, joined teardown
Task ID: S-RUNTIME-02-03
Role: opus-implementer
Status: READY
## 1. Context and baseline
- Wave 11 package steps B3+B4 combined (same files, shared teardown core). Dispatched after M-ASYNC-04
(ThreadExecutor), S-IO-03 and S-IO-04 (`pump_until`) are committed (gates G3, G5). 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:
- `include/Void/Runtime/Host.hpp`: inert `Host` (movable, `~Host() = default`, header-only; `HostState`
has no moved-from value; `started_worker_count()` always 0; `memory_budget()` dereferences
`owned_budget_` which is null after a move — pre-existing hazard), `EmbeddedResources` (borrowed
executor/io/clock), `ShutdownReport`, `HostBuilder`. `include/Void/Runtime/Options.hpp`:
`RuntimeLimits`, `Options` (`file_workers`, `cpu_workers`, `total_timeout`, `drain_grace`,
`export_flush_timeout`, …), `validate_options` (rejects `total_timeout <= 0`), `RuntimeErrorCode` incl.
root-added `self_join = 8`, `shutdown_incomplete = 9` (both → `ErrorKind::conflict`).
`include/Void/Runtime/ResourceGraph.hpp`: `ResourceKind` incl. `service`, `exporter`; `LifecyclePlan`
with `startup_order`. Existing tests `tests/standalone/Runtime/RuntimeHost.cpp` pin `started_worker_count()
== 0` after create and inert `add_resource` nodes.
- Available after upstream steps: `Async::ThreadExecutor` (`create/start/close/join/idle/admitted/stats`,
`before_worker_start` hook, `is_executor_thread`), `Async::TaskScope` (`stop_on_first_error` option),
`Async::TimerQueue`; `IO::Driver` (`start_file_workers`, `run_file_work`, `poll_once` → `busy` rules,
`shutdown(options)` → `DriverShutdownReport`, `shutdown_complete`, `quiescent`, `is_io_worker_thread()`,
`BackendOptions::before_file_worker_start`, mock `poll_once` ignores `max_wait`), `IO::pump_until`.
- System signal gate: `Void::Process::SignalWatcher` (`include/Void/System/SignalWatcher.hpp`; create before
worker threads, destroy on the creating thread; off-thread destruction closes the fd but skips the mask
restore, `src/System/SignalWatcher.cpp:27-37`). Runtime has NO System dependency (D-W11-04).
- Requirements: roadmap rows S-RUNTIME-02 ("Explicit start, readiness and reverse failed-start cleanup |
Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained") and
S-RUNTIME-03 ("Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting
| Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work
reports incomplete without freeing resources"); `docs/roadmap/subsystems/Runtime.md` (updated in W11);
C-03..C-06, C-09; decisions D-038, D-040, D-042.
- MANDATORY design sources (precedence R2 > REV1 > PLAN): `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`
§S-RUNTIME-02 and §S-RUNTIME-03; `W11-PLAN-REV1-OUTPUT.md` F3, F4, F5, F6, F11 and P3 (business scope,
mock reactor spin, budget accounting test); `W11-CONTRACT-R2.md` N1, N2, N3, P3-1, P3-2, P3-3, P3-7, P3-8.
## 2. Objective and deliverables
1. NEW `include/Void/Runtime/Lifecycle.hpp`: `StartStep`, `SignalGate`, `HostContext`, `Component`,
`StartOptions`, `ShutdownPhase`.
2. NEW `include/Void/Runtime/Detail/HostCore.hpp`: all lifecycle state and teardown (Runtime stays header-only).
3. EDIT `include/Void/Runtime/Host.hpp`: start/readiness/shutdown API, appended `ShutdownReport` fields,
`HostBuilder::add_component`, moved-from rules.
4. NEW tests `tests/standalone/Runtime/{RuntimeStart,RuntimeSignals,RuntimeShutdown}.cpp`.
## 3. Scope and non-goals
Out: Runtime→System edge or production signal bridge (S-RUNTIME-04), managed resize/reload, host-managed
TimerQueue polling (D-W11-14), any IO/Async/System source change, build files.
## 4. Files to inspect
`include/Void/Runtime/*.hpp`, `src/Runtime/module.cmake`, `tests/standalone/Runtime/RuntimeHost.cpp`,
`tests/package/RuntimeOnly/*`, `tests/package/InstalledComponents.cmake` (RuntimeOnly runs with
`-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE`), `include/Void/Async/{ThreadExecutor,TaskScope,Executor,Timer}.hpp`,
`include/Void/IO/{Driver,Pump,Types}.hpp`, `include/Void/Memory/BudgetResource.hpp`,
`include/Void/System/SignalWatcher.hpp`, and the design sources in §1.
## 5. Write ownership and coordination
Write scope: `include/Void/Runtime/Host.hpp`, `include/Void/Runtime/Lifecycle.hpp` (NEW),
`include/Void/Runtime/Detail/HostCore.hpp` (NEW), `tests/standalone/Runtime/RuntimeStart.cpp` (NEW),
`tests/standalone/Runtime/RuntimeSignals.cpp` (NEW), `tests/standalone/Runtime/RuntimeShutdown.cpp` (NEW),
`tests/package/RuntimeOnly/main.cpp` (optional smoke only).
Forbidden: every other path, including `Options.hpp`, `ResourceGraph.hpp`, IO/Async/System files and
`RuntimeHost.cpp` (stop and report if a change there is needed, P3-8). No git operations except the
authorized fast-forward.
## 6. Implementation or investigation approach
MANDATORY start (S-RUNTIME-02):
- `start(StartOptions)` once: `constructed → starting → running | failed_start`; records the owner thread.
Steps in order, each pushing a cleanup action: (1) `signal_gate->install()` (track `gate_installed_`;
borrowed gate must outlive the Host); (2) memory budget; (3) owned `ThreadExecutor{workers = cpu_workers,
max_admitted = limits.max_cpu_tasks}` create + `start()` (forward `before_thread_start(cpu_executor, i)`
into `before_worker_start`); (4) `IO::Driver::create` with `io.limits.file_workers = Options::file_workers`
(Runtime is authoritative) and the memory budget as its pmr resource; (5) `start_file_workers()` (forward
hook into `BackendOptions::before_file_worker_start`); (6) Runtime-owned reactor `std::thread` (catch
`std::system_error`; `before_thread_start(reactor, 0)` hook; thread-local `tl_reactor` marker) looping
`poll_once(5ms)`; on `busy`, or on a mock backend / a turn that did no work, wait up to 5 ms stop-aware
(never spin); exits on reactor stop or `shutdown_complete()`; (7) components in `plan_.startup_order`, `start`
called outside Host locks; (8) readiness: executor `try_post` probe plus one reactor turn within
`readiness_timeout` → `running`, `is_ready() == true`. `before_step(step)` hook errors inject failure
between steps; thread hooks inject failure within threaded steps.
- Failure at any point: pop cleanups in reverse on the starting thread, bounded by `cleanup_timeout`
(injected clock); state `failed_start`; return the error wrapped with context preserving the root
`Status`. If cleanup does not finish in budget, resources are retained and the next `shutdown_blocking`
or `~HostCore` continues. No thread or descriptor may remain after a completed cleanup.
- Embedded mode (`create_embedded`): steps 3–6 are skipped (borrowed executor/driver/clock); no threads.
- `started_worker_count()` reports real CPU + reactor + file threads.
- Business work: `spawn(Task, OperationOptions)` into a business `TaskScope` with
`TaskScopeOptions{.max_tasks = limits.max_cpu_tasks, .stop_on_first_error = false}`.
MANDATORY shutdown (S-RUNTIME-03; REV1 F3/F4 phase list, R2 N1–N3):
- Phases: 1 closing_admission, 2 draining (drain deadline fixed at first entry = min(total, start +
drain_grace)), 3 cancelling, 4 joining_business, 5 stopping_components (non-exporters, dependents first),
6 flushing_exporters (flush deadline fixed at first entry; expiry requests stop on exporter operations,
sets `export_flush_expired`, keeps waiting), 7 releasing_components (drop every component `shared_ptr`, so
exporters are destroyed here), 8 stopping_io (request reactor stop and JOIN the reactor, then
`driver->shutdown(remaining)` from the shutdown thread; retain if incomplete), 9 stopping_workers (wait for
`ThreadExecutor::idle()` within budget, then `join()`), 10 releasing (budgets, descriptors; signal gate
`uninstall(on_owner_thread)` at most once), 11 stopped. Assert ordering
`exporter_stopped < exporter_destroyed < executor_joined`.
- Every entry point (`shutdown_blocking`, `poll_shutdown`, `shutdown_pumping`) computes its own budget
`min(options.deadline, deadline_after(clock, total_timeout))`. In waiting phases 2, 4, 5, 6, 8, 9 a
call-deadline expiry stops the sequence and returns `complete=false`, state `shutdown_incomplete`, phase
recorded, all resources retained; the next call resumes at that phase. Drain expiry moves on to phase 3 and
sets `drain_grace_expired`.
- Component `stop()` tasks are launched through `post_completion` (never normal-lane admission), so a full
queue cannot block them. Concurrent callers get the same final report; exactly one teardown.
- `shutdown_blocking` on a Runtime worker/reactor/IO worker → `RuntimeErrorCode::self_join`;
`shutdown_blocking` when the executor has no background workers (embedded) → `invalid_argument`;
`shutdown_pumping` in managed mode → `invalid_argument`. Off-owner shutdown completes every phase except
the gate release (`owner_release_pending = true`); a later owner-thread call or `~HostCore` calls
`uninstall(this_thread == owner)`.
- Embedded `shutdown_pumping(manual, options, timers)` drains business scope and components using
`IO::pump_until(*io, manual, done, PumpOptions{.operation = call_budget, .timers = timers})`; borrowed
executor, driver, clock and memory are NEVER shut down, closed or joined.
- `~HostCore` (teardown lives here so default move-assign is safe): managed — loop shutdown with no
deadline cap until `complete` ("destruction blocks until complete"); embedded with a borrowed
`ManualExecutor` (dynamic_cast) — loop `shutdown_pumping(manual)` until complete; embedded otherwise and
incomplete — stderr diagnostic + `std::terminate`. On an OWNED Runtime worker/reactor/IO worker thread —
stderr diagnostic + `std::terminate` (detection via owned executor `is_executor_thread()`, `tl_reactor`,
`IO::is_io_worker_thread()`; never for a borrowed executor).
- Moved-from Host: `valid() == false`; `state()` returns `stopped`; `is_running/is_ready` false;
`started_worker_count()` 0; `executor()/io()` nullptr; `owner_thread()/last_shutdown_report()` nullopt;
`start/shutdown_*/poll_shutdown` → `invalid_state`; `spawn` → `AdmissionError::stopped`; reference accessors
(`options`, `lifecycle_plan`, `embedded_resources`, `memory_budget`) have precondition `valid()` (document,
assert in debug). `HostCore` holds no pointers into `Host` members. Owned BudgetResource/executor/driver live
until `~HostCore`.
## 7. Interfaces and data contracts
```cpp
namespace Void::Runtime {
enum class StartStep : std::uint8_t { signal_gate, memory_budget, cpu_executor, io_driver, file_workers, reactor, components, readiness };
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
stopping_components, flushing_exporters, releasing_components, stopping_io, stopping_workers, releasing, stopped };
class SignalGate { public: virtual ~SignalGate() = default;
[[nodiscard]] virtual Void::Result::Result<void> install() = 0;
virtual void uninstall(bool on_owner_thread) noexcept = 0; };
class HostContext { public: Async::Executor& executor(); IO::Driver* io(); const Void::Time::MonotonicClock& clock();
Void::Memory::BudgetResource& memory_budget(); std::stop_token business_stop() const; };
class Component { public: virtual ~Component() = default;
[[nodiscard]] virtual Void::Result::Result<void> start(HostContext&) = 0;
[[nodiscard]] virtual Coro::Task<Void::Result::Result<void>> stop(Async::OperationOptions) = 0; };
struct StartOptions { SignalGate* signal_gate{nullptr};
std::function<Void::Result::Result<void>(StartStep)> before_step{};
std::function<Void::Result::Result<void>(StartStep, std::size_t thread_index)> before_thread_start{};
std::function<void(ShutdownPhase)> on_phase{};
std::chrono::milliseconds readiness_timeout{5000}; std::chrono::milliseconds cleanup_timeout{5000}; };
}
// Host (EDIT): [[nodiscard]] Result<void> start(StartOptions = {}); bool is_ready() const noexcept; bool valid() const noexcept;
// Async::Executor* executor() noexcept; IO::Driver* io() noexcept; std::optional<std::thread::id> owner_thread() const noexcept;
// std::expected<Async::JoinHandle, Async::AdmissionError> spawn(Coro::Task<void>&&, Async::OperationOptions = {});
// void begin_shutdown() noexcept; Result<ShutdownReport> poll_shutdown(Async::OperationOptions = {});
// Result<ShutdownReport> shutdown_blocking(Async::OperationOptions = {});
// Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions = {}, Async::TimerQueue* timers = nullptr);
// std::optional<ShutdownReport> last_shutdown_report() const; std::size_t cpu_admitted() const noexcept;
// lifecycle state in std::unique_ptr<detail::HostCore>.
// ShutdownReport (EXISTING fields kept) + appended: ShutdownPhase phase; std::size_t pending_business_tasks,
// pending_cpu_admitted, pending_io_operations, retained_buffer_bytes; bool drain_grace_expired,
// export_flush_expired, owner_release_pending; bool complete (if not already present).
// HostBuilder (EDIT): [[nodiscard]] Result<void> add_component(std::string id, ResourceKind,
// std::shared_ptr<Component>, std::vector<std::string> deps = {}, bool critical = true);
```
Use existing `Result`/`make_runtime_error` spellings. Existing 1.x Host/HostBuilder API and `RuntimeHost` tests unchanged.
## 8. Dependencies and integration
Upstream: M-ASYNC-04, S-IO-03, S-IO-04, M-TIME-03 (all in your base). Downstream: P-NETWORKED-02 /
P-RELOADABLE-02 (later waves). Root integrates and commits.
## 9. Edge cases security and performance
Failure at every step and inside threaded steps (index 0 and last); thread-creation exceptions; pending
SIGUSR2 must be drained before uninstall (otherwise default action kills VoidTests); `/proc/self/task` and
`/proc/self/fd` deltas measured within a single test, Host telemetry primary; ManualClock + blocking waits
re-read the injected clock in short slices; deterministic tests use `poll_shutdown` or expired deadlines
rather than sleeps; full normal queue during shutdown; exporter waiting on a held mock read; RuntimeOnly
consumer has Threads lookup disabled (libc with integrated pthreads assumed, as IO already does).
## 10. Acceptance criteria
- `RuntimeStart.cpp`: `runtime_start_spawns_workers_only_on_start_ready`, `runtime_start_twice_invalid_state`,
`runtime_failed_start_each_step_reverse_cleanup_no_threads_no_fds`, `runtime_failed_start_thread_fault_each_threaded_step_reverse_cleanup`,
`runtime_failed_start_component_cleanup_timeout_retains_then_completes`, `runtime_component_start_failure_unwinds_reverse`,
`runtime_signal_gate_before_threads_uninstall_on_owner`, `runtime_signal_gate_uninstalled_at_most_once`,
`runtime_embedded_start_no_threads`, `runtime_move_after_start_keeps_resources_valid`, `runtime_moved_from_host_safe_defaults`.
- `RuntimeSignals.cpp` (includes `Void/System/SignalWatcher.hpp`; silently skipped without System; test-local
SignalGate adapter over `Process::SignalWatcher`, SIGUSR2): `runtime_system_gate_mask_inherited_by_workers`,
`runtime_system_gate_mask_restored_on_owner_after_failed_start_and_teardown`,
`runtime_signal_during_start_stays_pending_and_is_drained`, `runtime_offowner_destroy_closes_gate_fd_mask_not_restored`
(restores the owner mask and drains SIGUSR2 before finishing).
- `RuntimeShutdown.cpp`: `runtime_shutdown_concurrent_callers_single_teardown_tsan`,
`runtime_shutdown_full_normal_queue_still_delivers_completion`,
`runtime_shutdown_inflight_export_retains_io_workers_through_flush_expiry_then_completes` (ordering log),
`runtime_shutdown_stalled_business_task_incomplete_retains`, `runtime_shutdown_child_spawn_during_close_rejected`,
`runtime_shutdown_budget_expired_caller_deadline_incomplete_then_resumes`,
`runtime_shutdown_budget_bytes_retained_while_incomplete_zero_after_complete`,
`runtime_shutdown_on_worker_self_join`, `runtime_shutdown_non_owner_defers_gate_release`,
`runtime_shutdown_embedded_pumping`, `runtime_embedded_shutdown_never_shuts_borrowed_driver_or_executor`,
`runtime_embedded_shutdown_blocking_invalid_argument`, `runtime_managed_shutdown_pumping_invalid_argument`,
`runtime_destructor_joins_after_start`, `runtime_destructor_blocks_until_complete_after_incomplete_shutdown`.
- Existing `RuntimeHost` tests pass; `RuntimeOnly` consumer passes (ctest); TSan 0 races; ASan+UBSan 0 errors;
`-Werror` syntax checks clean. Keep each test well under 1,000 assertions (X-QA-02) and each test declaration
on ONE line (X-QA-03).
## 11. Verification commands and evidence
Cwd = worktree root; `dev` with the sandbox disabled. Confirm new suites appear in the output.
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt -G Ninja -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt --parallel 8 && /tmp/void-w11-rt/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt --output-on-failure --timeout 180'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-nosys -G Ninja -DVOID_ENABLED_MODULES="Runtime;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt-nosys --parallel 8 && /tmp/void-w11-rt-nosys/tests/VoidTests --filter "^(RuntimeStart|RuntimeShutdown|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt-nosys --output-on-failure --timeout 180'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_ENABLE_TSAN=ON && cmake --build /tmp/void-w11-rt-tsan --parallel 8 && /tmp/void-w11-rt-tsan/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown)\."'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON && cmake --build /tmp/void-w11-rt-asan --parallel 8 && /tmp/void-w11-rt-asan/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeShutdown|RuntimeHost)\."'
dev cpp-gcc -c bash -lc 'for f in RuntimeStart RuntimeSignals RuntimeShutdown; do g++ -std=c++26 -freflection -fsyntax-only -Iinclude -Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers tests/standalone/Runtime/$f.cpp || exit 1; done'
```
## 12. Constraints and stop conditions
No edits outside write scope; no weakened assertions; no Runtime→System edge; no Threads link. Stop and report
BLOCKED if an IO/Async primitive misbehaves (give a reproducer), a forbidden file must change, RuntimeHost tests
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,40 @@
# S-SCHEDULER-01..04 — Scheduler Subsystem (Timers, Calendar, Durable Storage Store, Operator Controls)
## Scope
Implement the P1–P3 native `Void::Scheduler` subsystem and `Void::SchedulerStorage` durable adapter per `docs/roadmap/subsystems/Scheduler.md` and `docs/roadmap/DEPENDENCIES.md`:
1. **`S-SCHEDULER-01` — In-Memory Heap, Recurrence, Overlap, Cancellation & Shutdown**:
- Module `src/Scheduler/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero `Storage` dependency.
- Error domain `kSchedulerErrorDomain = 31` (`SchedulerErrorCode`).
- Monotonic min-heap ordered by `(due_time, sequence)` using injected `MonotonicClock` and `CivilClock`, pure construction (no hidden background threads), and `Async::OperationOptions` for deadlines/cancellation.
- One-shot, fixed-delay (advances from durable completion), and fixed-rate (advances from intended schedule time) schedules; `OverlapPolicy` (`Forbid`, `QueueOne`, `AllowBounded`); `RetryPolicy` (default 5 attempts, exponential backoff 1s..5m, x2, injectable full-jitter RNG); callbacks run outside scheduler/store locks.
- `close_and_join()` stops materialization/dispatch, signals active handlers, joins within deadline, and returns `ShutdownReport` preserving running records on timeout.
2. **`S-SCHEDULER-02` — Calendar Grammar, Explicit Timezones/DST, and Bounded Misfire**:
- 5-field cron-like grammar (`minute hour day month weekday` with `*`, lists, ranges, steps; both day-of-month and weekday constraints apply).
- Explicit `TimezoneRegistry` supporting `"UTC"`, fixed offsets (`+HH:MM`/`-HH:MM`), and explicit DST transition rules (`DstGapPolicy::Skip`/`NextValid`, `DstFoldPolicy::First`/`Second`/`Twice` with persisted `fold_index`). Unknown timezone fails with `UnsupportedTimezone` (never silent UTC fallback).
- `MisfirePolicy` (`Skip`, `CoalesceLatest`, `CatchUpBounded` capped at `100` slots/job/pass while preserving remaining cursor state even across millions of missed slots).
3. **`S-SCHEDULER-03` — Durable Persistence Port and `SchedulerStorage` Adapter**:
- `JobStore` port + `InMemoryJobStore` (in `Scheduler`) and `StorageJobStore` (in `src/SchedulerStorage/module.cmake`, `INTERNAL_DEPS Scheduler Storage`) backed by `Void::Storage::Engine` conditional batches (`Durability::Sync`, 1 MiB batch cap).
- Exclusive ownership lock rejecting second concurrent scheduler owner (`OwnershipLocked`).
- Atomic occurrence materialization + cursor advance with unique `(job, revision, civil_slot, fold)` dedup key preventing duplicate materialization on wall-clock rollback.
- Atomic `Pending -> Running` claim checking job tombstone and revision invalidation watermark in the same conditional batch; `Running -> Completed` / `Pending` / `Dead` transitions; `UnknownOutcome` surfaced faithfully on unknown storage write outcome.
- Startup crash recovery returning `Running` occurrences to `Pending` with the exact same `OccurrenceId` (explicit at-least-once semantics).
4. **`S-SCHEDULER-04` — Revision Updates, Tombstone Removal, Retention Caps, and Operator Inspection**:
- `update_job()` bumps revision and atomically writes old-revision invalidation watermark so unstarted old occurrences are cancelled without racing active claims; failed updates leave prior policy intact.
- `remove_job()` writes tombstone, stops admission, and requests stop for active handlers.
- Retention count cap pauses materialization without advancing cursors or deleting unacknowledged work; dead occurrences require explicit `acknowledge_dead()` before pruning; bounded `prune_completed()` / `reclaim_invalidated()` and inspection APIs.
## File Ownership
- `include/Void/Scheduler/{Types,Calendar,Store,Scheduler}.hpp`
- `src/Scheduler/{module.cmake,Calendar.cpp,Scheduler.cpp}`
- `include/Void/SchedulerStorage/StorageJobStore.hpp`
- `src/SchedulerStorage/{module.cmake,StorageJobStore.cpp}`
- `tests/standalone/Scheduler/Scheduler.cpp`
- `tests/standalone/SchedulerStorage/StorageJobStore.cpp`
- `tests/package/SchedulerOnly/{CMakeLists.txt,main.cpp}`
- `tests/package/InstalledComponents.cmake`
## Acceptance & Verification
- Standalone `Scheduler;SchedulerStorage;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `SchedulerOnly` consumer with `_no_external_deps`.
- Deterministic fake-clock ordering, overlap, retry/dead-letter, DST gap/fold/unknown-tz, millions-of-missed-slots coalesce/catch-up cap, crash/reopen recovery preserving `OccurrenceId`, revision watermark race, unknown outcome, and retention-cap cursor preservation tests.
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
@@ -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,906 @@
# W11-PLAN output (opus-planner, 2026-11-29)
Verbatim planner return for [W11-PLAN](W11-PLAN.md). Advisory input; root decisions are recorded in `DECISIONS.md`.
# W11-PLAN: execution-path backfill plan (opus-planner)
**Status: DONE.** The plan is ready for opus-reviewer PREFLIGHT. It is not approved, and I don't approve it myself. Nothing was written to the repository.
## Summary
- All eight tasks can be done without a forbidden dependency edge. **No `INTERNAL_DEPS` change is needed.**
- The roadmap rows leave out four real dependencies:
- The library has no thread-backed `Async::Executor`, so S-RUNTIME-02 depends on M-ASYNC-04.
- The IO `Driver` has no file workers and no run loop, so S-RUNTIME-02 depends on S-IO-03 and S-RUNTIME-03 depends on S-IO-04.
- Async has no timer primitive. M-TIME-03 adds one, and M-ASYNC-04's timed channel waits then depend on M-TIME-03.
- **Existing IO defect.** The epoll backend can release one operation's backend reference twice. A cross-thread `shutdown_and_join` can also finish an operation and close its fd while another thread's `poll_once` is inside `::read`/`::write` on it. Both fixes are assigned to S-IO-03 (opus).
- **Signal gate exists.** It is `Void::Process::SignalWatcher` in System. The plan uses it through a new Runtime port (`SignalGate`), so Runtime does not gain a System dependency.
- **S-RPC-04: defer.** It is file-disjoint, but it is not a good ride-along (reasons below).
- **Partition:** two packages by role. Package A is sonnet with the sol rows; package B is opus with the astra rows. A small root "contracts pre-commit" adds the new enumerators first, and five gates sequence the hand-offs between packages.
---
## 0. Cross-cutting evidence
- **Builds and consumers**
- The selected-module list expands to its dependencies (`CMakeLists.txt:45-71`).
- A test whose includes need an unselected header is skipped silently (`tests/CMakeLists.txt:12-41`). Every command below therefore enables all modules a new test includes.
- `--filter` is a regex search over the test name or `suite.name`, where the suite is the file stem (`src/Testing/Runner.cpp:209-225`). Filters below use `^(Stem1|Stem2)\.`.
- Warnings are `-Wall -Wextra -Wpedantic -Werror -Wno-missing-field-initializers` (`cmake/Module.cmake:178`). Appending members to aggregates is therefore safe. Every enum switch must be completed; the only switches over the extended enums are the `make_*_error` mappers (`Async/Detail/Types.hpp:65-91,103-134`, `IO/Types.hpp:46-77`, `Runtime/Options.hpp:39-60`).
- The installed consumers IOOnly and RuntimeOnly run with `-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE` (`tests/package/InstalledComponents.cmake:74-80,109-117`). Adding `Threads::Threads` to IO or Runtime would break them, so the plan doesn't (D-W11-08). IO already calls `pthread_sigmask` without it (`EpollDriver.cpp:47`).
- **Executors**
- The only executor in the library is `ManualExecutor` (`Async/Executor.hpp:120-254`).
- Thread-backed executors exist only inside one test file (`tests/standalone/Async/OperationScope.cpp:25,135`).
- `ManualExecutor` releases its slot before resuming (`Executor.hpp:226-228`), so its bound excludes running work. Its `post()` bypasses the bound (`:128-135`).
- **IO**
- No thread, no run loop, no file API (`IO/Driver.hpp:59-105`). The embedder drives it with `poll_once` (`EpollDriver.cpp:1843-1847`).
- `IoLimits::file_workers` and `max_file_queue` (`IO/Types.hpp:106-107`) and `IoErrorCode::incomplete_shutdown` (`:32`) are declared but unused in `src/IO`.
- **Epoll defects (D1)**
- `complete_op_and_collect_tickets` releases the backend reference unconditionally (`EpollDriver.cpp:448`).
- The cancel path does not skip operations that already finished (`:1332-1351`).
- `drive_read`/`drive_write` call `::read` on `op->read_ptr` outside `mu_`, without marking the operation as executing (`:1462-1474`). `in_execution` is used only by the mock (`:653-671`).
- Cross-thread `EpollBackend::shutdown_and_join` finishes unretired operations and closes their fds (`:1179-1238`, close at `:1221`).
- Result: a stop arriving just after completion can double-release the reference, and shutdown racing a concurrent poller risks use-after-free or fd reuse. No test covers this; `io_epoll_cross_thread_wake_poll_and_stop_tsan` (`tests/standalone/IO/IoDriver.cpp:458-508`) stops the poller before teardown.
- **Host**
- Movable and returned by value, with `~Host() = default` (`Runtime/Host.hpp:88-94`).
- Header-only (`src/Runtime/` holds only `module.cmake`).
- `started_workers_` is always 0 (`:173`).
- **Retry consumers:** ResilienceAsync uses `Void::Retry::ExponentialBackoff` and `JitterMode` (`Resilience/AsyncPolicy.hpp:6,486,533`), so these must stay source-compatible. Its `wait_with_stop` really sleeps in 5 ms slices while reading the injected clock (`:553-575`). That is out of scope and nothing here builds on it.
---
## 1. Per-task plans
### M-FUNCTIONAL-03: pure retry decisions and a named blocking adapter (sol → sonnet)
**Baseline**
- `Functional/Retry.hpp` holds:
- backoff types in milliseconds (`:18-68`)
- `Jittered`, which uses a `thread_local mt19937_64` seeded from `random_device`, so results are not reproducible (`:76-95`)
- `Policy{max_attempts=3, max_elapsed=0 meaning unlimited}` (`:100-110`)
- `backoff_sleep`, hard-wired to `steady_clock::now()` and `sleep_for` (`:117-142`)
- `retry`/`retry_while`, which start from a default-constructed result (`:156,197`). With `max_attempts == 0` they return a default-constructed `expected`, i.e. a success, without ever calling `fn` (`:150-170,190-211`).
- `src/Functional/module.cmake` declares no dependencies.
- Existing tests: `Retry.cpp` (14 tests) and `RetryJitter.cpp` (4 tests).
**Gap:** no pure decision engine, no injected time or URBG, no validation or saturation, no explicit `no_deadline`, zero attempts can succeed, and the blocking path is unnamed.
**Minimal scope**
- A standard-library-only `RetryState`.
- A `retry_blocking` that takes injected `now` and `sleep` callables. Using callables means no Time dependency (D-W11-02).
- Every 1.x symbol keeps its behavior.
**NEW: `include/Void/Functional/RetryState.hpp`** (no `<thread>`, no Void includes). The 1.x `JitterMode` definition moves here, keeping its name and namespace.
```cpp
namespace Void::Retry {
using SteadyTimePoint = std::chrono::steady_clock::time_point;
enum class JitterMode { Full, Equal }; // EXISTING, relocated
struct NoDeadline { constexpr bool operator==(const NoDeadline&) const noexcept = default; };
inline constexpr NoDeadline no_deadline{};
struct BackoffSpec { std::chrono::nanoseconds initial{std::chrono::milliseconds{100}};
std::chrono::nanoseconds cap{std::chrono::seconds{30}};
double multiplier{2.0}; std::optional<JitterMode> jitter{}; };
struct RetrySpec { std::uint32_t max_attempts{3}; // total incl. first
std::variant<std::chrono::nanoseconds, NoDeadline> budget{std::chrono::seconds{30}};
BackoffSpec backoff{}; };
enum class RetryConfigError : std::uint8_t { zero_attempts, negative_duration, zero_budget,
nonfinite_multiplier, multiplier_below_one, cap_below_initial };
enum class RetryAction : std::uint8_t { attempt, wait_until, stop };
enum class RetryStopReason : std::uint8_t { none, succeeded, attempts_exhausted, deadline_exceeded,
not_retryable, stop_requested };
enum class AttemptOutcome : std::uint8_t { retryable_failure, permanent_failure };
struct RetryDecision { RetryAction action{RetryAction::stop}; SteadyTimePoint at{};
RetryStopReason reason{RetryStopReason::none}; std::uint32_t attempts_started{0}; };
[[nodiscard]] std::expected<void, RetryConfigError> validate(const RetrySpec&) noexcept;
[[nodiscard]] std::chrono::nanoseconds backoff_delay(const BackoffSpec&, std::uint32_t retry_index) noexcept; // saturating, unjittered
[[nodiscard]] constexpr SteadyTimePoint saturating_add(SteadyTimePoint, std::chrono::nanoseconds) noexcept;
template <std::uniform_random_bit_generator URBG = std::mt19937_64>
class RetryState {
public:
[[nodiscard]] static std::expected<RetryState, RetryConfigError>
create(const RetrySpec&, SteadyTimePoint start, URBG urbg = URBG{},
std::optional<SteadyTimePoint> admission_deadline = std::nullopt); // deadline = min(start+budget, admission)
[[nodiscard]] RetryDecision begin(SteadyTimePoint now, bool stop_requested = false) noexcept;
[[nodiscard]] RetryDecision next(SteadyTimePoint now, AttemptOutcome, bool stop_requested = false) noexcept;
[[nodiscard]] RetryDecision resume(SteadyTimePoint now, bool stop_requested = false) noexcept;
[[nodiscard]] RetryDecision succeed() noexcept;
[[nodiscard]] std::uint32_t attempts_started() const noexcept;
[[nodiscard]] std::optional<SteadyTimePoint> deadline() const noexcept;
};
template <class E> struct RetryError { RetryStopReason reason{}; std::uint32_t attempts{0};
std::optional<E> last_error{}; // empty iff no attempt ran
std::optional<RetryConfigError> config{}; };
struct RetryEveryError { template <class E> constexpr AttemptOutcome operator()(const E&) const noexcept
{ return AttemptOutcome::retryable_failure; } };
}
```
**Fixed semantics**
- `begin` returns `stop` for a stop request or `now >= deadline`; otherwise `attempt`.
- `next` checks, in order:
1. permanent failure → `not_retryable`
2. `attempts == max` → `attempts_exhausted`
3. stop requested → `stop_requested`
4. Otherwise it computes `at = saturating_add(now, jitter(backoff_delay(k)))`. If `at >= deadline` it returns `deadline_exceeded`; else `wait_until(at)`.
- `next` never returns `attempt` directly. `resume` re-checks stop and deadline and then returns `attempt`.
- Full jitter draws uniformly from [0, d] ns. Equal jitter is d/2 plus a uniform draw from [0, d − d/2].
- Backoff saturates at `cap` before conversion. Negative or non-finite inputs and `multiplier < 1` fail `create`.
**EDIT: `include/Void/Functional/Retry.hpp`** (add the include and these declarations; leave every 1.x body untouched)
```cpp
struct SteadyNow { SteadyTimePoint operator()() const noexcept { return std::chrono::steady_clock::now(); } };
struct ThreadSleep{ bool operator()(std::chrono::nanoseconds wait, std::stop_token) const; }; // cv_any+stop; false if stopped
template <class NowFn = SteadyNow, class SleepFn = ThreadSleep, class Classify = RetryEveryError,
class URBG = std::mt19937_64>
struct BlockingRetryOptions { NowFn now{}; SleepFn sleep{}; Classify classify{}; URBG urbg{};
std::stop_token stop{}; std::optional<SteadyTimePoint> deadline{}; };
template <class F, class NowFn, class SleepFn, class Classify, class URBG> // F() -> std::expected<T,E>
[[nodiscard]] auto retry_blocking(const RetrySpec&, F&& fn, BlockingRetryOptions<NowFn,SleepFn,Classify,URBG> = {})
-> std::expected<T, RetryError<E>>;
```
- Waits are always `decision.at - options.now()`, measured in the injected domain. The adapter never calls `sleep_until(at)`.
**Unchanged 1.x:** `NoDelay`, `ConstantDelay`, `LinearBackoff`, `ExponentialBackoff`, `Jittered`, `JitterMode`, `Policy`, `Detail::backoff_sleep`, `retry`, `retry_or_throw`, `retry_while`. The zero-attempt defect stays as it is (D-W11-03).
**Tests**
- **NEW `tests/standalone/Functional/RetryState.cpp`:**
- `retry_state_rejects_invalid_specs` (one check per `RetryConfigError`)
- `retry_state_exact_three_attempts_default`
- `retry_state_deadline_at_admission_prevents_first_attempt`
- `retry_state_backoff_overshooting_deadline_stops`
- `retry_state_no_deadline_explicit_marker`
- `retry_state_backoff_saturates_without_overflow` (multiplier 1e300, initial near max)
- `retry_state_full_equal_jitter_bounds_and_seed_reproducibility` (bounds and same-seed equality only; no exact draws)
- `retry_state_stop_prevents_next_attempt`
- `retry_state_permanent_failure_stops`
- `retry_state_saturating_add_near_max`
- **NEW `tests/standalone/Functional/RetryBlocking.cpp`.** It uses a fake clock struct local to the test, with no Time include.
- `retry_blocking_fake_clock_exact_waits_and_attempts` (zero real sleeps; recorded waits equal the backoff)
- `retry_blocking_zero_attempts_config_error_no_call`
- `retry_blocking_expired_deadline_no_call_no_success`
- `retry_blocking_last_error_and_attempt_count`
- `retry_blocking_stop_during_sleep_no_extra_attempt`
- `retry_blocking_permanent_failure_single_attempt`
- `retry_blocking_move_only_value`
- `legacy_retry_zero_attempts_behavior_pinned`
- Existing `Retry`, `RetryJitter` and `AsyncPolicy` tests must keep passing.
**Commands**
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3 -G Ninja -DVOID_ENABLED_MODULES="Functional;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3 && /tmp/void-w11-fn3/tests/VoidTests --filter "^(RetryState|RetryBlocking|Retry|RetryJitter)\." && ctest --test-dir /tmp/void-w11-fn3 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-fn3-res -G Ninja -DVOID_ENABLED_MODULES="ResilienceAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-fn3-res && /tmp/void-w11-fn3-res/tests/VoidTests --filter "^AsyncPolicy\."'
rg -n "#include <thread>|Void/Time" include/Void/Functional/RetryState.hpp # expect no output
```
### M-TIME-03: injected-deadline domains with Async and blocking retry adapters (astra → opus)
**Baseline**
- Time: `ManualClock` starts at epoch 0 (`Time/Clock.hpp:69-130`); `remaining_until` is at `:188-208`; `src/Time/module.cmake` has no dependencies.
- Async: `is_deadline_expired(options, clock = System)` (`Async/Detail/Types.hpp:49-55`) and `OperationState::is_deadline_expired` (`Operation.hpp:160-165`) default to the host clock. `ScheduleStatusAwaiter` checks the deadline only in `await_ready`/`await_resume` and never wakes on expiry (`Executor.hpp:304-359`). `include/Void/Async` has no timer.
- IO already expires operations via the injected `clock_` on poll (`EpollDriver.cpp:739-834,1395-1443`), covered by `io_mock_stop_completion_races_and_clock_timeout`.
**Gap:** no awaitable timed wait that expires only through explicit polling, no Async retry adapter, and no conformance tests that manual-domain deadlines are never compared with the host clock.
**Minimal scope:**
- An Async `TimerQueue` (a stable min-heap ordered by `(deadline, seq)`).
- `Async::retry_async` built on `RetryState`.
- Time saturation helpers.
- Cross-adapter conformance tests.
**NEW: `include/Void/Async/Timer.hpp`**
```cpp
namespace Void::Async {
struct TimerQueueOptions { std::size_t max_timers{1024}; }; // 0 invalid
using TimerCallback = std::move_only_function<void() noexcept>;
class TimerHandle { public: bool cancel() noexcept; /* move-only; true => callback never runs */ };
class TimerQueue { // non-movable
public:
using time_point = Void::Time::MonotonicClock::time_point;
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
create(Executor& completion_executor, const Void::Time::MonotonicClock& clock, TimerQueueOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_until(time_point when, OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_for(std::chrono::nanoseconds, OperationOptions = {});
[[nodiscard]] std::expected<TimerHandle, AdmissionError> schedule_at(time_point when, TimerCallback on_expire);
[[nodiscard]] std::size_t poll_expired(); // fires due timers once, (deadline,seq) order, outside locks
[[nodiscard]] std::optional<time_point> next_deadline() const;
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept;
[[nodiscard]] std::size_t active_timers() const noexcept;
void close() noexcept; // pending -> stopped; new -> stopped
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept;
[[nodiscard]] Executor& executor() noexcept;
};
}
```
**Fixed semantics for `sleep_until`**
- Results: `{}` when `when` is reached and polled; `cancelled` on stop; `timeout` if `options.deadline` comes first; `overloaded` at `max_timers`; `stopped` after `close`.
- Stop or expiry settles through `OperationState`, and the continuation is dispatched through `post_completion`. A stop callback never resumes inline.
- Cancelled timers are tombstoned, and the heap is compacted so it never exceeds 2 × `max_timers`.
- Destroying the queue settles pending sleeps with `stopped`. The executor must outlive the queue.
**NEW: `include/Void/Async/Retry.hpp`** (needs gate G1, i.e. A1 integrated)
```cpp
template <class F, class Classify = Void::Retry::RetryEveryError, class URBG = std::mt19937_64>
[[nodiscard]] auto retry_async(Void::Retry::RetrySpec, F fn /* ()->expected<T,E> | Task<expected<T,E>> */,
TimerQueue& timers, OperationOptions = {}, Classify = {}, URBG = URBG{})
-> Coro::Task<std::expected<T, Void::Retry::RetryError<E>>>;
```
- "Now" comes from `timers.clock()`. The admission deadline is `options.deadline`.
- If an attempt succeeds after stop was requested, the success is returned. After stop, nothing is retried.
**EDIT: `include/Void/Time/Clock.hpp`** (NEW helpers)
```cpp
[[nodiscard]] MonotonicClock::time_point saturating_add(MonotonicClock::time_point, std::chrono::nanoseconds) noexcept;
[[nodiscard]] MonotonicClock::time_point deadline_after(const MonotonicClock&, std::chrono::nanoseconds) noexcept;
```
**Unchanged:** every existing Time and Async symbol, including the default-argument clock parameters.
**Tests**
- **NEW `tests/standalone/Async/TimerQueue.cpp`:**
- `timer_manual_advance_and_poll_fires_exactly_once`
- `timer_equal_deadlines_fire_in_submission_order`
- `timer_not_fired_without_explicit_poll`
- `timer_manual_epoch_deadline_not_compared_with_host_clock`
- `timer_manual_clock_far_future_initial_point`
- `timer_stop_before_admission_and_pending_cancelled_once`
- `timer_stop_vs_poll_race_single_result_tsan`
- `timer_capacity_overloaded_and_tombstone_bounded`
- `timer_schedule_at_cancel_vs_fire_exclusive`
- `timer_close_settles_pending_stopped`
- `timer_wait_duration_uses_injected_now`
- `timer_sleep_for_saturates`
- **NEW `tests/standalone/Async/AsyncRetry.cpp`:**
- `async_retry_manual_clock_attempts_only_after_advance_and_poll`
- `async_retry_total_deadline_expires_once`
- `async_retry_stop_during_backoff_no_further_attempt`
- `async_retry_success_after_stop_preserved`
- `async_retry_zero_attempts_no_call`
- `async_retry_task_returning_callable`
- **NEW `tests/standalone/Async/DeadlineDomains.cpp`:**
- `deadline_domain_blocking_retry_manual_clock` (`now = manual.now`; the sleep callable advances the manual clock)
- `deadline_domain_schedule_on_and_scope_admission_injected_clock`
- **NEW `tests/standalone/Time/ClockSaturation.cpp`:** `clock_saturating_add_and_deadline_after_bounds`.
**Commands**
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3 && /tmp/void-w11-time3/tests/VoidTests --filter "^(TimerQueue|AsyncRetry|DeadlineDomains|ClockSaturation|Clock|Stopwatch|OperationScope|Executor)\." && ctest --test-dir /tmp/void-w11-time3 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-tsan && /tmp/void-w11-time3-tsan/tests/VoidTests --filter "^(TimerQueue|AsyncRetry|DeadlineDomains)\."'
```
### M-ASYNC-04: bounded executors, cancellable channels, future pool adapter, ParallelFor (sol → sonnet)
**Baseline**
- `Executor` base: `try_post`, `post_completion` and the reservation API (`Executor.hpp:58-113`). `ManualExecutor`'s bound excludes running work (`:226-228`). No threaded executor exists.
- `Concurrency::ThreadPool` (`ThreadPool.hpp:20-187`):
- `max_queue == 0` means unbounded (`:33-38`).
- Its bound counts only the queue, because a task is popped before it runs (`:164-173`).
- `submit` throws after stop (`:85-89`).
- `try_submit` returns `nullopt` for both "full" and "stopped" (`:100-120`).
- It includes Log (`:2`).
- `Concurrency::Channel` (`Channel.hpp:13-116`): blocking only; `send(T)` consumes the value even when the channel is closed (`:24-35`); capacity 0 blocks forever (`:27-28`).
- `parallel_for` (`ParallelFor.hpp:12-26`) creates one future per index, so submission is unbounded. On the first throwing `fut.get()` it returns without joining the remaining tasks.
**Gap:** no bound that includes running work, no coroutine channel, no explicit future adapter, and chunk errors don't join.
**Minimal scope:** NEW `ThreadExecutor`, `FuturePool`, `AsyncChannel`, and a bounded `parallel_for` overload. Capacity-waiting (`async_wait_for_capacity`) and the 4 MiB channel byte budget are deferred (D-W11-13).
**NEW: `include/Void/Async/ThreadExecutor.hpp`**
```cpp
namespace Void::Async {
struct ThreadExecutorOptions { std::size_t workers{1}; std::size_t max_admitted{4096}; // queued+running; >=1
std::function<Void::Result::Result<void>(std::size_t)> before_worker_start{}; }; // fault-injection hook
struct ThreadExecutorStats { std::size_t queued, running, completion_queued; std::uint64_t rejected, legacy_posts, inline_after_join; };
class ThreadExecutor final : public Executor {
public:
[[nodiscard]] static Void::Result::Result<std::unique_ptr<ThreadExecutor>> create(ThreadExecutorOptions = {}); // no threads
[[nodiscard]] Void::Result::Result<void> start(); // once; partial failure joins started workers
void post(std::coroutine_handle<>) override; // never rejects; counted; may exceed bound (legacy)
[[nodiscard]] std::expected<void, AdmissionError> try_post(std::coroutine_handle<>) override; // overloaded if queued+running>=max
void post_completion(std::coroutine_handle<>) override; // reserved lane; drains after close(); prioritized
[[nodiscard]] bool supports_reservation() const noexcept override; // true
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override;
void commit_reserved(std::coroutine_handle<>) override; void release_reserved() noexcept override;
[[nodiscard]] bool has_background_workers() const noexcept override; // true
void close() noexcept; // normal admission -> stopped
[[nodiscard]] Void::Result::Result<void> join(); // close+drain+join; self_join on worker
[[nodiscard]] std::size_t admitted() const noexcept; [[nodiscard]] ThreadExecutorStats stats() const noexcept;
};
}
```
**Mandatory for `ThreadExecutor`**
- Every resume runs inside `detail::ExecutorThreadGuard`; that is what `is_executor_thread` and self-join detection rely on.
- A slot is released only after the resumed handle returns.
- After `join`, `post` and `post_completion` resume inline on the caller (documented and counted). A handle is never dropped.
**NEW: `include/Void/Async/FuturePool.hpp`**
```cpp
class FuturePool { public: explicit FuturePool(ThreadExecutor&) noexcept;
template <std::invocable F> [[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
try_submit(F&& f); }; // reserve-then-transfer: f not moved on rejection; exceptions -> future
```
**NEW: `include/Void/Async/AsyncChannel.hpp`**
```cpp
enum class ChannelError : std::uint8_t { closed, empty, full, cancelled, timed_out, overloaded, invalid_argument };
struct ChannelOptions { std::size_t capacity{1024}; std::size_t max_waiters{1024}; TimerQueue* timers{nullptr}; };
template <class T> struct SendFailure { ChannelError error; T value; };
template <class T> class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>> { public:
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>> create(Executor& resume, ChannelOptions = {});
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T);
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>> send(T, OperationOptions = {});
[[nodiscard]] std::expected<T, ChannelError> try_receive();
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>> receive(OperationOptions = {});
void close() noexcept; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool is_closed() const; };
[[nodiscard]] Void::Result::Error make_async_error(ChannelError, std::string message = {});
```
- A wait with a deadline but no `timers` returns `invalid_argument`.
- `close()` hands waiting senders `closed` together with their value. Receivers drain the buffer in FIFO order, then get `closed`.
- Resumption always goes through `post_completion`, outside locks.
- The deadline part depends on gate G2.
**EDIT: `include/Void/Async/ParallelFor.hpp`**
```cpp
struct ParallelForOptions { std::size_t grain{1}; std::size_t max_concurrency{0}; std::stop_token stop{}; bool stop_on_error{true}; };
struct ParallelForError { enum class Kind : std::uint8_t { invalid_argument, rejected, stopped, failed } kind;
std::size_t chunks_total{0}, chunks_started{0}, chunks_failed{0};
std::optional<std::size_t> first_failed_chunk{}; std::exception_ptr first_exception{}; };
template <std::integral I, std::invocable<I> F>
[[nodiscard]] std::expected<void, ParallelForError> parallel_for(I first, I last, F&& f, ThreadPool&, ParallelForOptions);
```
- `max_concurrency == 0` means the pool's thread count.
- Runner tasks are submitted with `try_submit`; if rejected, the caller thread runs chunks itself.
- No new chunk starts after a stop or (with `stop_on_error`) an error.
- All started runners are always joined. The reported error is the lowest-indexed failed chunk.
- D-W11-10: the 1.x overload should wait for all futures before rethrowing.
**Root pre-commit:** `AsyncErrorCode::closed = 9`, mapped to `ErrorKind::cancelled`.
**Unchanged:** `ManualExecutor`, `Concurrency::{ThreadPool, Channel}`, the existing `parallel_for` signatures, `spawn`, `schedule_on`.
**Tests (NEW, `tests/standalone/Async/`)**
- **`ThreadExecutor.cpp`:**
- `thread_executor_create_starts_no_threads`
- `thread_executor_bound_includes_running_work` (1 worker, max 2: blocker running plus 1 queued → `overloaded`; release → accepted)
- `thread_executor_reservation_with_task_scope_preserves_task`
- `thread_executor_completion_lane_bypasses_full_normal_lane`
- `thread_executor_close_rejects_normal_drains_completion`
- `thread_executor_join_self_join_on_worker`
- `thread_executor_partial_start_failure_joins_started`
- `thread_executor_legacy_post_spawn_schedule_on_compat`
- `thread_executor_stress_tsan`
- **`FuturePool.cpp`:**
- `future_pool_overloaded_does_not_consume_callable`
- `future_pool_stopped_after_close`
- `future_pool_exception_in_future`
- `future_pool_bound_includes_running`
- **`AsyncChannel.cpp`:**
- `channel_zero_capacity_invalid`
- `channel_try_send_full_returns_value`
- `channel_send_waits_resumes_on_receive`
- `channel_producer_stop_returns_value_cancelled_once`
- `channel_close_wakes_senders_with_value_and_drains_receivers`
- `channel_deadline_requires_timers`
- `channel_deadline_times_out_once_manual_clock_poll`
- `channel_waiter_bound_overloaded`
- `channel_move_only_values`
- `channel_mpmc_fifo_tsan`
- `channel_stop_vs_send_race_single_outcome_tsan`
- **`ParallelForBounded.cpp`:**
- `parallel_for_bounded_grain_and_concurrency_limit`
- `parallel_for_bounded_stop_joins_started_no_new_chunks`
- `parallel_for_bounded_errors_join_all_lowest_index_reported`
- `parallel_for_bounded_zero_grain_invalid`
- `parallel_for_bounded_rejected_pool_runs_inline`
- `legacy_parallel_for_exception_joins_all` (only if D-W11-10 is approved)
**Commands** (for each tag, `-Werror` on the default build, plus Debug TSan and ASan+UBSan build dirs)
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4 && /tmp/void-w11-async4/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor|ThreadPool|ThreadPoolBackpressure|Channel|OperationScope|Executor)\." && ctest --test-dir /tmp/void-w11-async4 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-tsan && /tmp/void-w11-async4-tsan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded)\."'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-async4-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-async4-asan && /tmp/void-w11-async4-asan/tests/VoidTests --filter "^(ThreadExecutor|FuturePool|AsyncChannel|ParallelForBounded|ParallelFor)\."'
```
### M-ASYNC-05: EventBus/Observable snapshot dispatch, joined subscriptions, injected scheduling (sol → sonnet)
**Baseline**
- `EventBus` (`EventBus.hpp:37-284`):
- Sync `publish` iterates the live vector without the lock (`:156-164`). A handler that subscribes or unsubscribes during dispatch therefore causes undefined behavior.
- Async mode starts a private thread in the constructor (`:43-48`).
- The snapshot copies `std::function`s, so `unsubscribe` cannot retract queued copies (`:167-169`).
- A handler exception escapes the worker loop, which terminates the process (`:248-269`).
- The task queue and handler list are unbounded (`:272-278`).
- `Subscription::reset` doesn't join (`:115-121`).
- `Observable` and `Signal` iterate the live vectors (`Observable.hpp:74-77,116-119`); reentrant use is undefined behavior, and there is no threading policy.
- Existing tests: `EventBus.cpp` (12), `EventBusAsync.cpp` (4), `Observable.cpp` (14).
**Gap:** per the row.
**Minimal scope:**
- Subscription state held in `shared_ptr`, with snapshot dispatch gated per entry.
- A new injected-executor mode.
- Joins per subscription and per bus.
- Bounded nested Observable notifications.
**NEW (EDIT `EventBus.hpp`)**
```cpp
namespace Void::EventBus {
enum class Mode { Sync, Async, Injected }; // NEW enumerator
struct BusOptions { std::size_t max_subscriptions{1024}; std::size_t max_admitted_dispatches{1024};
std::function<void(std::exception_ptr)> error_sink{}; }; // outside locks
class EventBus { // EXISTING API unchanged, plus:
explicit EventBus(Void::Async::Executor& executor, BusOptions = {}); // no private thread; internal TaskScope
template <class Event> [[nodiscard]] Void::Result::Result<Subscription> try_subscribe(std::function<void(const Event&)>);
template <class Event> [[nodiscard]] Void::Result::Result<void> try_publish(const Event&); // overloaded / closed
[[nodiscard]] Void::Result::Result<void> close_and_join();
[[nodiscard]] Void::Result::Result<void> close_and_join_pumping(Void::Async::ManualExecutor&);
[[nodiscard]] std::uint64_t callback_failures() const noexcept;
class Subscription { /* EXISTING */ public: [[nodiscard]] Void::Result::Result<void> close_and_join(); };
};
}
```
**Semantics (D-W11-06)**
- 1.x `unsubscribe` stops future publishes from including the handler. In `Mode::Async` it still delivers already-queued copies, as 1.x does.
- NEW `Subscription::close_and_join` also suppresses admitted deliveries that have not started. It then waits for in-flight callbacks and resets the handler (releasing captured state) before returning.
- Calling it from the subscription's own callback returns `self_join`. Self-unsubscribe is supported.
- Callbacks run outside locks. Injected and Async modes catch callback exceptions and route them to `error_sink`, counting them. Sync `publish` still propagates exceptions as in 1.x.
**NEW (EDIT `Observable.hpp`)**
- Documented policy: single-threaded, not thread-safe, safe for reentrancy.
- `inline constexpr std::size_t kMaxPendingNotifications = 1024;`
- `Observable::try_set(T) -> Result<void>` returns `overloaded` and leaves the value unchanged.
- `dropped_notifications()`.
- A nested `set` updates the value immediately and queues `(old, new)` copies, delivered in FIFO order after the current pass.
- Unsubscribe during a pass skips that listener for the rest of the pass. Subscribing during a pass doesn't add the listener to the current pass.
- A throwing listener: its exception propagates out of the outermost `set`/`emit`, after state is restored, and queued notifications are dropped and counted.
- `Signal::emit` uses the same snapshot rules.
**Tests (NEW)**
- **`tests/standalone/Async/EventBusJoin.cpp`:**
- `bus_injected_no_private_thread_manual_pumping`
- `bus_injected_subscription_limit_overloaded`
- `bus_injected_dispatch_limit_overloaded`
- `bus_close_and_join_waits_inflight_releases_capture_tsan` (sentinel `use_count == 1` after join)
- `bus_unsubscribe_during_dispatch_prevents_later_admission`
- `bus_self_unsubscribe_ok_self_join_rejected`
- `bus_callback_throw_to_error_sink_others_run`
- `bus_legacy_async_unsubscribe_keeps_queued_copy` (pins 1.x)
- `bus_sync_reentrant_subscribe_unsubscribe_asan`
- `bus_publish_after_close_closed`
- **`tests/standalone/Async/ObservableReentrancy.cpp`:**
- `observable_nested_set_fifo`
- `observable_unsubscribe_in_listener_skips_rest`
- `observable_subscribe_in_listener_not_current_pass`
- `observable_try_set_overloaded_when_pending_full`
- `observable_listener_throw_restores_state`
- `observable_self_unsubscribe_releases_capture`
- `signal_reentrant_connect_disconnect_during_emit`
**Commands:** same form as M-ASYNC-04 with `--filter "^(EventBusJoin|ObservableReentrancy|EventBus|EventBusAsync|Observable)\."`, plus TSan and ASan dirs `/tmp/void-w11-async5{,-tsan,-asan}`.
### S-IO-03: bounded positional file workers, serialization, sync, active-cancel (astra → opus)
**Baseline:** see §0, including the D1 defects; there is no pread, pwrite or fsync anywhere in `src/IO`. `validate_limits` ignores the file fields (`IO/Types.hpp:110-122`).
**Gap:** the whole file path, plus a shutdown that joins workers safely.
**Minimal scope:**
- A file worker pool in a NEW translation unit, shared by the mock and epoll backends through `BaseBackend`.
- An injectable syscall shim.
- Explicit worker start.
- The D1 correctness fixes.
**NEW: `include/Void/IO/File.hpp`**
```cpp
namespace Void::IO {
struct FileOpenOptions { bool read{true}, write{false}, create{false}, truncate{false}, exclusive{false}; std::uint32_t mode{0600}; };
enum class SyncMode : std::uint8_t { data, full };
struct FileSyscallResult { std::int64_t value{0}; int error{0}; };
class FileSyscalls { public: virtual ~FileSyscalls() = default;
[[nodiscard]] virtual FileSyscallResult pread(int, std::span<std::byte>, std::uint64_t) noexcept;
[[nodiscard]] virtual FileSyscallResult pwrite(int, std::span<const std::byte>, std::uint64_t) noexcept;
[[nodiscard]] virtual FileSyscallResult sync(int, SyncMode) noexcept;
[[nodiscard]] virtual FileSyscallResult close(int) noexcept;
[[nodiscard]] static FileSyscalls& native() noexcept; };
class File { public: /* move-only */ [[nodiscard]] bool valid() const noexcept; [[nodiscard]] DescriptorId id() const noexcept;
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(std::uint64_t, BufferLease&, Async::OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at_owned(std::uint64_t, const BufferLease&, Async::OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(SyncMode = SyncMode::full, Async::OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(Async::OperationOptions = {}); };
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> read_exact_at(File&, std::uint64_t, std::span<std::byte>, Async::OperationOptions = {});
[[nodiscard]] Coro::Task<std::expected<std::size_t, ComposedTransferError>> write_all_at(File&, std::uint64_t, std::span<const std::byte>, Async::OperationOptions = {});
}
```
**EDITs**
- `Driver.hpp` gains:
- `Result<File> open_file(const std::filesystem::path&, FileOpenOptions = {})`
- `Result<File> adopt_file_fd(int)`
- `Result<void> start_file_workers()` (explicit, once; D-W11-11)
- `Result<std::size_t> run_file_work(std::size_t max_requests = 1)` (manual stepping when no workers are running)
- `Types.hpp`:
- `BackendOptions::file_syscalls{nullptr}` (appended; borrowed)
- `DriverTelemetry` gains `queued_file_requests`, `active_file_requests`, `file_workers_running` (appended)
- `validate_limits` rejects `max_file_queue == 0`
- Root pre-commit: `IoErrorCode::sync_failed = 12`, mapped to `ErrorKind::io`
- `Detail/Backend.hpp` gains file submit virtuals.
- `EpollDriver.cpp` integrates the pool and the shutdown changes.
- NEW `src/IO/FileWorkers.{hpp,cpp}`; the `.hpp` is private and not globbed.
**Fixed semantics**
- **Admission:** a stopped or expired request, or a closed driver, is rejected before it is queued. `max_file_queue` counts queued requests; `max_operations` counts queued and active. Either limit returns `overloaded`. A zero-length request returns `{0, false}`. Offset plus length overflowing gives `invalid_argument`.
- **Ordering:** writes and syncs on one file run in admission order, at most one active at a time. Reads may run concurrently. Each request is exactly one syscall, with EINTR retried. A short transfer returns the bytes actually moved; a 0-byte read of a nonzero length means EOF.
- **Queued stop or expiry:** the request is removed and completes `cancelled` or `timeout`. Writes and syncs carry `DomainOutcomeKind::not_committed`. Expiry is checked by the driver clock in `poll_once` and again at worker dequeue.
- **Active stop or expiry:** recorded as intent only. The span or lease and the telemetry stay retained, and the result is the syscall's actual outcome. A sync that succeeds after a stop is a success. A sync that fails returns `sync_failed` with the native errno and `DomainOutcomeKind::unknown`.
- **`shutdown_and_join`** keeps its 1.x signature with extended behavior:
1. Close admission.
2. Cancel queued socket and file operations.
3. Wait for in-flight syscalls and for any concurrent `poll_once` turn (poll-owner exclusion).
4. Join the workers.
5. Only then close the fds, epoll and eventfd.
Called from a worker, or from inside poll dispatch, it returns `Async::make_async_error(AdmissionError::self_join)`.
- **D1 fixes (mandatory):**
- Release the backend reference only if this call retired the operation.
- The cancel and expire paths skip retired operations.
- Epoll marks an operation `in_execution` under `mu_` before its syscall.
**Tests: NEW `tests/standalone/IO/IoFile.cpp`**
- `io_file_native_roundtrip_isolated_tmpdir`
- `io_file_short_write_preserves_progress_write_all_at`
- `io_file_writes_syncs_serialized_admission_order`
- `io_file_reads_concurrent_explicit_offsets`
- `io_file_queue_and_ops_quota_overloaded`
- `io_file_queued_cancel_not_committed_zero_effects`
- `io_file_queued_deadline_expires_once_manual_clock_poll`
- `io_file_active_timeout_retains_buffer_until_syscall_returns`
- `io_file_sync_success_after_stop_is_success`
- `io_file_sync_failure_after_stop_sync_failed_unknown_errno`
- `io_file_manual_stepping_without_workers`
- `io_file_shutdown_joins_stalled_worker_then_delivers`
- `io_file_shutdown_from_worker_self_join`
- `io_epoll_shutdown_concurrent_with_poller_no_uaf_tsan`
- `io_stop_after_completion_releases_backend_ref_once`
**Commands**
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3 -G Ninja -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3 && /tmp/void-w11-io3/tests/VoidTests --filter "^(IoFile|IoDriver)\." && ctest --test-dir /tmp/void-w11-io3 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="IO;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-tsan && /tmp/void-w11-io3-tsan/tests/VoidTests --filter "^(IoFile|IoDriver)\."'
# also an ASan+UBSan dir with the same filter, plus downstream IO users unfiltered:
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-io3-users -G Ninja -DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-io3-users && /tmp/void-w11-io3-users/tests/VoidTests && ctest --test-dir /tmp/void-w11-io3-users --output-on-failure --timeout 120'
```
### S-IO-04: embedded pumping, joined shutdown, optional adapters (sol → sonnet)
**Baseline**
- The only driving entry points are `poll_once`, `wake` and `request_stop` (`Driver.hpp:91-96`).
- Embedded pumping today is hand-written loops (`IoDriver.cpp:490-499`). `TaskScope::join_pumping` drains the executor but never polls IO (`TaskScope.hpp:645-654`).
- System adapter already exists: SystemAsync `ProcessManager` borrows a `Driver` (`System/AsyncProcess.hpp:61`, `src/SystemAsync/AsyncProcess.cpp:434`).
- Net does not use IO at all (rg finds no `Void/IO` in `include/Void/Net` or `src/Net`).
**Minimal scope:** a bounded or repeatable `shutdown`, a `run` loop, a `pump_until` helper, and a SystemAsync conformance test. The Net adapter is deferred (D-W11-07).
**NEW**
```cpp
namespace Void::IO {
struct DriverShutdownReport { bool complete{false}; std::size_t pending_operations{0}, active_file_requests{0},
open_descriptors{0}, retained_buffer_bytes{0}; }; // Types.hpp
void Driver::begin_shutdown() noexcept; // idempotent, never frees
[[nodiscard]] Void::Result::Result<DriverShutdownReport> Driver::shutdown(Async::OperationOptions); // bounded; repeatable
[[nodiscard]] Void::Result::Result<std::size_t> Driver::run(std::stop_token, std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5});
[[nodiscard]] bool Driver::quiescent() const noexcept;
struct PumpOptions { std::chrono::nanoseconds max_wait{0}; std::size_t max_turns{1u << 20};
Async::OperationOptions operation{}; Async::TimerQueue* timers{nullptr}; }; // NEW Pump.hpp
template <class Done> requires std::predicate<Done&>
[[nodiscard]] Void::Result::Result<std::size_t> pump_until(Driver&, Async::ManualExecutor&, Done&&, PumpOptions = {});
}
```
**Fixed semantics**
- `shutdown` evaluates its deadline and stop in `driver.clock()`.
- When it expires it returns `complete = false` and retains everything: no fd is closed, no buffer is released, and the workers stay alive.
- It never runs a poll turn while another thread is inside `poll_once`.
- A misuse case such as self-join is returned as an error.
- `pump_until` returns `timeout`, `cancelled` or `exhausted` and never frees work.
**Tests (NEW)**
- **`tests/standalone/IO/IoShutdown.cpp`:**
- `io_shutdown_expired_budget_incomplete_retains_stalled_file_worker`
- `io_shutdown_pending_socket_read_retains_buffer_until_delivery`
- `io_shutdown_repeated_idempotent_after_complete`
- `io_shutdown_concurrent_with_run_loop_tsan`
- `io_run_stops_on_token_and_on_shutdown`
- `io_begin_shutdown_rejects_new_admission`
- **`tests/standalone/IO/IoPump.cpp`:**
- `io_pump_until_scope_join_mock`
- `io_pump_until_deadline_injected_clock`
- `io_pump_until_max_turns_exhausted`
- `io_pump_until_drives_timer_queue`
- **`tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`:** `systemasync_driver_shutdown_pending_pipe_read_retains_and_delivers_once`.
**Commands:** `-DVOID_ENABLED_MODULES="IO;SystemAsync;Testing"`, `--filter "^(IoShutdown|IoPump|IoFile|IoDriver|SystemAsyncShutdown|SystemAsync)\."`, with a `-Werror` dir and a TSan dir (`/tmp/void-w11-io4{,-tsan}`), plus `ctest` (IOOnly and SystemAsyncOnly).
### S-RUNTIME-02: explicit start, readiness, reverse failed-start cleanup (astra → opus)
**Baseline:**
- `Host` is inert (`Host.hpp:85-178`).
- Options: `Options.hpp:89-96`. `Options::file_workers` duplicates `IoLimits::file_workers` (`:91` vs `IO/Types.hpp:106`). Note the existing exemption quirk for 4096 timers (`:149`).
- `ResourceKind` includes `service` and `exporter` (`ResourceGraph.hpp:23-31`).
- Pinned by tests: `started_worker_count() == 0` after `create` (`RuntimeHost.cpp:77-79`), and inert `add_resource` nodes (`:134-138`).
**Gap:** everything about start. The executor and file-worker prerequisites come from the hidden edges in the summary.
**NEW: `include/Void/Runtime/Lifecycle.hpp`** (plus `Detail/HostCore.hpp`; stays header-only, D-W11-09)
```cpp
namespace Void::Runtime {
enum class StartStep : std::uint8_t { signal_gate, memory_budget, cpu_executor, io_driver, file_workers, reactor, components, readiness };
class SignalGate { public: virtual ~SignalGate() = default;
[[nodiscard]] virtual Void::Result::Result<void> install() = 0; // owner thread, before any Runtime thread
virtual void uninstall() noexcept = 0; }; // same thread, after all Runtime threads joined
class HostContext { public: Async::Executor& executor(); IO::Driver* io(); const Void::Time::MonotonicClock& clock();
Void::Memory::BudgetResource& memory_budget(); std::stop_token business_stop() const; };
class Component { public: virtual ~Component() = default;
[[nodiscard]] virtual Void::Result::Result<void> start(HostContext&) = 0; // outside Host locks
[[nodiscard]] virtual Coro::Task<Void::Result::Result<void>> stop(Async::OperationOptions) = 0; };
struct StartOptions { SignalGate* signal_gate{nullptr};
std::function<Void::Result::Result<void>(StartStep)> before_step{};
std::function<void(ShutdownPhase)> on_phase{}; // used by S-RUNTIME-03
std::chrono::milliseconds readiness_timeout{5000}; };
}
// Host (EDIT): all lifecycle state in std::unique_ptr<detail::HostCore>; Host stays movable.
[[nodiscard]] Void::Result::Result<void> start(StartOptions = {}); // once: constructed->starting->running|failed_start
[[nodiscard]] bool is_ready() const noexcept; [[nodiscard]] Async::Executor* executor() noexcept;
[[nodiscard]] IO::Driver* io() noexcept; [[nodiscard]] std::optional<std::thread::id> owner_thread() const noexcept;
[[nodiscard]] std::expected<Async::JoinHandle, Async::AdmissionError> spawn(Coro::Task<void>&&, Async::OperationOptions = {});
~Host(); // non-default: reverse teardown on allowed thread
// HostBuilder (EDIT):
[[nodiscard]] Void::Result::Result<void> add_component(std::string id, ResourceKind, std::shared_ptr<Component>,
std::vector<std::string> deps = {}, bool critical = true);
```
**Root pre-commit:** `RuntimeErrorCode::self_join = 8` (→ `conflict`) and `shutdown_incomplete = 9` (→ `timeout`).
**Fixed start algorithm.** Each step pushes a cleanup action. On failure, the cleanups are popped in reverse on the starting thread, the state becomes `failed_start`, and the error is returned wrapped with context, preserving the root `Status`.
1. Validate `constructed`; record the owner thread.
2. `signal_gate->install()`.
3. Memory budget.
4. `ThreadExecutor{cpu_workers, max_admitted = limits.max_cpu_tasks}` → `start()`.
5. `IO::Driver::create`, with `io.limits.file_workers = Options::file_workers` (Runtime is authoritative).
6. `start_file_workers()`.
7. A Runtime-owned reactor thread looping `poll_once(5ms)`.
8. Components in `plan_.startup_order`.
9. Readiness: an executor `try_post` probe plus one reactor turn → `running`.
Embedded mode skips steps 4–7 (no threads). `started_worker_count()` reports the real CPU, reactor and file threads.
**Tests (NEW)**
- **`tests/standalone/Runtime/RuntimeStart.cpp`:**
- `runtime_start_spawns_workers_only_on_start_ready`
- `runtime_start_twice_invalid_state`
- `runtime_failed_start_each_step_reverse_cleanup_no_threads_no_fds` (loop over `StartStep`; `/proc/self/task` and `/proc/self/fd` deltas are 0; a fresh Host then starts)
- `runtime_component_start_failure_unwinds_reverse`
- `runtime_signal_gate_before_threads_uninstall_on_owner` (fake gate)
- `runtime_embedded_start_no_threads`
- `runtime_move_after_start_keeps_resources_valid`
- **`tests/standalone/Runtime/RuntimeSignals.cpp`.** It includes `Void/System/SignalWatcher.hpp`, so it runs only when System is enabled. It uses a test-local adapter around `Process::SignalWatcher` and SIGUSR2.
- `runtime_system_gate_mask_inherited_by_workers`
- `runtime_system_gate_mask_restored_on_owner_after_failed_start_and_teardown`
- `runtime_signal_during_start_stays_pending_and_is_drained`
**Commands**
```sh
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt2 -G Ninja -DVOID_ENABLED_MODULES="Runtime;System;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-rt2 && /tmp/void-w11-rt2/tests/VoidTests --filter "^(RuntimeStart|RuntimeSignals|RuntimeHost)\." && ctest --test-dir /tmp/void-w11-rt2 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-rt2-nosys -G Ninja -DVOID_ENABLED_MODULES="Runtime;Testing" -DVOID_WARNINGS_AS_ERRORS=ON 2>&1 | grep "Skipping.*RuntimeSignals" && cmake --build /tmp/void-w11-rt2-nosys && ctest --test-dir /tmp/void-w11-rt2-nosys --output-on-failure --timeout 60'
# plus Debug TSan and ASan+UBSan dirs with "^(RuntimeStart|RuntimeSignals)\."
```
### S-RUNTIME-03: structured shutdown, repeated join, exporter-before-executor ordering, budget accounting (astra → opus)
**NEW**
```cpp
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
stopping_components, flushing_exporters, stopping_io, stopping_workers, releasing, stopped };
// ShutdownReport (EXISTING fields kept) + appended: phase, pending_business_tasks, pending_cpu_admitted,
// pending_io_operations, retained_buffer_bytes, drain_grace_expired, export_flush_expired, owner_release_pending
void Host::begin_shutdown() noexcept;
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::poll_shutdown(); // non-blocking step
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_blocking(Async::OperationOptions = {}); // repeatable
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions = {});
[[nodiscard]] std::optional<ShutdownReport> Host::last_shutdown_report() const;
```
**Fixed semantics**
- **Total deadline:** fixed at the first `begin_shutdown`, as `min(caller deadline, deadline_after(clock, total_timeout))`.
- **Phase deadlines:** drain = `min(total, phase start + drain_grace)`; flush = `min(total, phase start + export_flush_timeout)`.
- **Phase order:**
1. Close business scope admission.
2. Drain.
3. Request stop on the business scope.
4. Join it.
5. Stop non-exporter components (dependents first).
6. Stop exporters with the flush deadline. On expiry, request stop and set `export_flush_expired`, but keep IO, the reactor and the workers alive.
7. `driver->shutdown(remaining)`; if incomplete, retain it.
8. Stop and join the reactor, then `ThreadExecutor::join()`.
9. Drop component references, so exporters are destroyed before the executor is torn down.
10. Release budgets and fds. Signal-gate uninstall happens on the owner thread only; otherwise `owner_release_pending` is set and the next owner-thread call or `~Host` performs it.
- **Mandatory mechanics:**
- Component `stop` tasks are launched through `post_completion`, never through normal-lane admission, so a full queue cannot block them.
- Expiry of the total budget returns `complete = false` and state `shutdown_incomplete`, retaining all resources. The next call continues from there.
- Concurrent callers get the same final report, and there is exactly one teardown.
- Calling `shutdown_blocking` on a Runtime worker returns `RuntimeErrorCode::self_join`.
- Calling it from a non-owner thread completes every phase except the signal-gate release, as above.
**Tests: NEW `tests/standalone/Runtime/RuntimeShutdown.cpp`**
- `runtime_shutdown_concurrent_callers_single_teardown_tsan`
- `runtime_shutdown_full_normal_queue_still_delivers_completion`
- `runtime_shutdown_inflight_export_retains_io_workers_through_flush_expiry_then_completes` (exporter waits on a held mock read; total budget expires → incomplete, active ops 1, retained bytes > 0, threads alive; release → join again → complete; ordering log: `exporter_stopped < exporter_destroyed < executor_joined`)
- `runtime_shutdown_stalled_business_task_incomplete_retains`
- `runtime_shutdown_child_spawn_during_close_rejected`
- `runtime_shutdown_budget_min_caller_policy_manual_clock` (`poll_shutdown`)
- `runtime_shutdown_on_worker_self_join`
- `runtime_shutdown_non_owner_defers_gate_release`
- `runtime_shutdown_embedded_pumping`
- `runtime_destructor_joins_after_start`
**Commands:** as S-RUNTIME-02, with `"^(RuntimeShutdown|RuntimeStart|RuntimeSignals|RuntimeHost)\."`, in `-Werror`, TSan and ASan dirs, plus `ctest` (RuntimeOnly).
---
## 2. Dependency graph and INTERNAL_DEPS check
```
M-FUNCTIONAL-02✓ → M-FUNCTIONAL-03 ──(G1: RetryState)──→ M-TIME-03[Retry.hpp part]
M-TIME-02✓ → M-TIME-03[Timer.hpp part] ──(G2: TimerQueue)──→ M-ASYNC-04[AsyncChannel deadlines]
M-ASYNC-03✓ → M-ASYNC-04 → M-ASYNC-05
M-ASYNC-04 ──(G3, hidden: ThreadExecutor)──→ S-RUNTIME-02
S-IO-02✓ → S-IO-03 ──(G4, same files)──→ S-IO-04 (M-TIME-03 → S-IO-04 soft: PumpOptions::timers)
S-IO-03 ──(hidden: start_file_workers, safe shutdown)──→ S-RUNTIME-02
S-RUNTIME-01✓ → S-RUNTIME-02 → S-RUNTIME-03 ←(G5, hidden: Driver::shutdown(options))── S-IO-04
{M-ASYNC-05, S-IO-04, S-RUNTIME-03} → P-NETWORKED-02 / P-RELOADABLE-02 gates
```
**Critical path:** M-TIME-03 (Timer) → S-IO-03 → S-RUNTIME-02 → S-RUNTIME-03, with S-IO-04 needed before S-RUNTIME-03.
| Module | Change | Rule check against DEPENDENCIES.md |
| --- | --- | --- |
| Functional | none (stays empty) | Rule 1 and D-015: standard library only. `RetryState.hpp` includes no Void header. |
| Time | none | Rule 1. The helpers are `std::chrono` only. No Time→Functional edge (D-W11-02). |
| Async | none (Functional Time LogState) | Rule 2: no Log backend, no Runtime. New headers include only Async, Functional and Time. |
| IO | none internal; no Threads (D-W11-08) | Rule 2: IO depends on Async; no System, Runtime or Net. |
| Runtime | none (…Async IO) | Composes Async/IO/Time/Memory. No System edge; uses the `SignalGate` port. |
| SystemAsync, tests only | none | "System may use IO". System appears in `RuntimeSignals.cpp` as a test include only; the file is skipped without System. |
## 3. Ownership partition
**Root-owned, before dispatch (W11-0 contracts pre-commit; single writer):**
- `include/Void/Async/Detail/Types.hpp`: `AsyncErrorCode::closed = 9` plus its mapping case.
- `include/Void/IO/Types.hpp`: the enum part only, `IoErrorCode::sync_failed = 12` plus its case.
- `include/Void/Runtime/Options.hpp`: `RuntimeErrorCode::self_join = 8` and `shutdown_incomplete = 9` plus their cases.
**Root-owned throughout:**
- `docs/agent-workflow/**` (task specs, TASKS, STATE, DECISIONS, VERIFICATION)
- `CMakeLists.txt`, `cmake/*`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake` (no change planned)
- `include/Void/Functional/Error.hpp` (no change planned; no new domains)
- All integration, commits and merges
**Package A: sonnet-implementer (sol rows), run in order**
| Step | Task | Owned paths |
| --- | --- | --- |
| A1 | M-FUNCTIONAL-03 | `include/Void/Functional/RetryState.hpp` (NEW), `include/Void/Functional/Retry.hpp`, `tests/standalone/Functional/RetryState.cpp`, `tests/standalone/Functional/RetryBlocking.cpp` |
| A2 | M-ASYNC-04 | `include/Void/Async/ThreadExecutor.hpp`, `include/Void/Async/FuturePool.hpp`, `include/Void/Async/AsyncChannel.hpp` (all NEW), `include/Void/Async/ParallelFor.hpp`, `tests/standalone/Async/{ThreadExecutor,FuturePool,AsyncChannel,ParallelForBounded}.cpp`. Channel deadline waits wait for G2. |
| A3 | M-ASYNC-05 | `include/Void/Async/EventBus.hpp`, `include/Void/Async/Observable.hpp`, `tests/standalone/Async/{EventBusJoin,ObservableReentrancy}.cpp` |
| A4 | S-IO-04 (after G4: IO ownership passes from B to A) | `include/Void/IO/{Types,Driver,Pump(NEW)}.hpp`, `include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.{hpp,cpp}`, `tests/standalone/IO/{IoShutdown,IoPump}.cpp`, `tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`. Not owned: `src/SystemAsync/*` (stop and report). |
**Package B: opus-implementer (astra rows), run in order**
| Step | Task | Owned paths |
| --- | --- | --- |
| B1 | M-TIME-03 | `include/Void/Async/Timer.hpp` (NEW), `include/Void/Async/Retry.hpp` (NEW, after G1), `include/Void/Time/Clock.hpp`, `tests/standalone/Async/{TimerQueue,AsyncRetry,DeadlineDomains}.cpp`, `tests/standalone/Time/ClockSaturation.cpp` |
| B2 | S-IO-03 | `include/Void/IO/File.hpp` (NEW), `include/Void/IO/{Types,Driver}.hpp`, `include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `src/IO/FileWorkers.{hpp,cpp}` (NEW), `tests/standalone/IO/IoFile.cpp` |
| B3 | S-RUNTIME-02 (after G3 + B2) | `include/Void/Runtime/{Host,Lifecycle(NEW)}.hpp`, `include/Void/Runtime/Detail/HostCore.hpp` (NEW), `tests/standalone/Runtime/{RuntimeStart,RuntimeSignals}.cpp`, `tests/package/RuntimeOnly/main.cpp` (optional smoke) |
| B4 | S-RUNTIME-03 (after G5) | same Runtime files, plus `tests/standalone/Runtime/RuntimeShutdown.cpp` |
**Gate sequence (root integrates at each):**
- G1: A1 merged, then B1 writes `Retry.hpp`.
- G2: B1's `Timer.hpp` merged, then A2 adds channel deadlines.
- G3: A2 merged, then B3.
- G4: B2 merged, then A4.
- G5: A4 merged, then B4.
No path is owned by both packages at the same time. No worker touches `Executor.hpp`, `Operation.hpp`, `TaskScope.hpp`, `ThreadPool.hpp` or `Channel.hpp`.
## 4. System signal gate (S-RUNTIME-02)
It exists:
- `Void::Process::SignalWatcher` (`include/Void/System/SignalWatcher.hpp:16-43`). Its contract (`:13-15`): construct it before worker threads; destroy it on the creating thread.
- `create` blocks the mask with `pthread_sigmask` and opens a `signalfd` with `SFD_CLOEXEC|SFD_NONBLOCK` (`src/System/SignalWatcher.cpp:74-90`).
- `~Impl` closes the fd and restores the mask only when `pthread_equal(owner, self)` (`:27-37`). Off-thread destruction silently skips the restore.
- It has been unchanged since before baseline (`3851aeb`).
Runtime has no System edge. The S-RUNTIME-01 spec excludes it, and the Runtime area plan doesn't list it, although DEPENDENCIES.md does not forbid it.
Minimal in-wave work:
- The `SignalGate` port: installed as start step 1, uninstalled last on the owner thread, with deferred owner release if shutdown runs elsewhere.
- A test-local adapter over `SignalWatcher` inside `RuntimeSignals.cpp`.
- No System source changes.
- A production bridge module (for example a NEW `RuntimeSystem` with deps Runtime+System, following the SystemAsync pattern) is deferred to S-RUNTIME-04 (D-W11-04).
## 5. S-RPC-04 verdict: do not ride along; defer to the P3 wave
**What is in place:**
- S-RPC-03 is VERIFIED (`docs/agent-workflow/TASKS.md:129`).
- The Net WebSocket pieces are present: codec and client (`Net/WebSocket.hpp:127-185`), server sessions (`Net/Server.hpp:205-300`), `add_websocket_route` (`Net/HttpServer.hpp:93-99`), and subprotocol negotiation (`WebSocket.hpp:37-45,127-130`).
- It is file-disjoint from this wave (`include/Void/RPC`, `src/RPC`, `tests/standalone/RPC`).
**Why it should wait:**
1. `WebSocketLimits::max_output_messages` and `max_output_bytes` (`WebSocket.hpp:32-33`) are never read in `src/Net`. Server sends are a synchronous `send_all` under a per-connection mutex (`src/Net/HttpServer.cpp:930-946`). So "no memory growth under stalled consumers", and a reserved control lane for CANCEL/TERMINAL, can't be guaranteed at the transport layer without a Net change or an explicit acceptance of blocking-send semantics.
2. The client is synchronous (`WebSocket.hpp:166-170`). The planned `Task<Result<DuplexCall>>` API would naturally sit on M-ASYNC-04's `AsyncChannel`, which makes it dependent on this wave's output.
3. It is an astra row and would compete with the opus critical path.
4. It is P3, against D-027 ordering.
**Prerequisite for later:** a small Net task to enforce output budgets or a bounded non-blocking send queue, or a recorded decision to accept blocking sends.
## 6. Risks
- **D1 (high):** the existing epoll double reference release and the shutdown-versus-poller use-after-free / fd-reuse risk. It is fixed in S-IO-03 and needs TSan and ASan evidence.
- **SIGUSR2 is fatal if left pending.** A blocked SIGUSR2 that is still pending when the mask is restored takes its default action and kills the VoidTests process. The signal tests must drain the signal via `poll()` before uninstalling.
- **`/proc` counting:** thread and fd deltas can be disturbed by background threads from earlier tests. Measure deltas within a single test (tests run sequentially by default, `Runner.cpp:734-740`), with Host telemetry as the primary check.
- **ThreadExecutor join while coroutines are still suspended elsewhere** falls back to inline resume. Runtime must reach driver quiescence before executor join; the S-RUNTIME-03 phase order enforces this.
- **ManualClock with blocking waits:** `shutdown_blocking` and IO `shutdown` must re-evaluate the injected clock in short slices. Deterministic tests use `poll_shutdown` or expired deadlines rather than sleeps.
- **Internal TaskScopes in destructors:** a `TaskScope` destructor pumps or blocks (`TaskScope.hpp:562-575`). EventBus (Injected mode) and Host must join their internal scopes before destruction.
- **Behavior changes in 1.x:** Observable and Sync EventBus reentrancy used to be undefined behavior and now get defined semantics. Async-mode handler exceptions change from terminate to catch-and-count (needs D-W11-06 approval).
- **Scope size:** B3 and B4 are the largest items and carry the highest schedule risk.
- **Out of scope:** `Concurrency::Channel` with capacity 0 deadlocks (`Channel.hpp:17,27-28`), and Resilience `wait_with_stop` mixes real sleeps with the injected clock (`AsyncPolicy.hpp:553-575`).
## 7. Open decisions (recommendation for each)
| ID | Decision | Recommendation |
| --- | --- | --- |
| D-W11-01 | Where TimerQueue is owned | Async header `Async/Timer.hpp`, delivered by M-TIME-03 (astra) |
| D-W11-02 | Clock/sleeper adapter placement | Callables injected into Functional; no Time→Functional edge and no Time retry header (resolves the Functional.md wording) |
| D-W11-03 | Zero-attempt success in legacy `retry` | Keep unchanged (D-029), pin it with a test, and record it for the Wave C migration |
| D-W11-04 | How the signal gate is wired | `SignalGate` port, no Runtime→System edge; production bridge deferred to S-RUNTIME-04 |
| D-W11-05 | S-IO-03 (opus) then S-IO-04 (sonnet) in shared IO files | Accept serial hand-off at G4, with the risky shutdown and poll fixes placed in S-IO-03. No other role deviation. |
| D-W11-06 | EventBus semantics | Legacy `unsubscribe` keeps delivering queued copies in Async mode; NEW `close_and_join` gates and joins; Async-mode handler exceptions go to `error_sink` (no terminate) |
| D-W11-07 | Net adapter for IO | Defer. The System adapter is the existing SystemAsync, validated by the new shutdown test. |
| D-W11-08 | `Threads::Threads` for IO and Runtime | Don't add it. Adding it would require changing IOOnly/RuntimeOnly flags in `InstalledComponents.cmake`. |
| D-W11-09 | Runtime build shape | Stay header-only (`Detail/HostCore.hpp`), so packaging is unchanged |
| D-W11-10 | Legacy `parallel_for` on exceptions | Join all futures before rethrowing; this fixes a lifetime hazard without changing the API |
| D-W11-11 | When file workers start | Explicit `start_file_workers()`, so existing Driver users don't get hidden threads |
| D-W11-12 | S-RPC-04 | Defer to the P3 wave, after a Net output-bounds task |
| D-W11-13 | `async_wait_for_capacity` and the channel byte budget | Defer; neither is in the row acceptance |
| D-W11-14 | Host-managed TimerQueue | Defer to S-RUNTIME-04 |
| D-W11-15 | New enumerators | Root pre-commit before dispatch: `AsyncErrorCode::closed`, `IoErrorCode::sync_failed`, `RuntimeErrorCode::{self_join, shutdown_incomplete}` |
**Roadmap inconsistencies, all resolvable:**
- The S-RUNTIME-02 and S-RUNTIME-03 rows omit their M-ASYNC-04 and S-IO-03/04 prerequisites; add the edges.
- The area plan's awaited `Coro::Task` shutdown on the host's own executor would conflict with stopping that executor; the plan uses blocking and polling shutdown APIs instead.
- Runtime and IO each define a `file_workers` setting; Runtime is authoritative.
- The IO plan describes a "driver thread" but the code has none; S-IO-04 adds `run()`, and Runtime owns the reactor thread.
None of these contradicts D-001..D-036 or needs a forbidden edge.
## 8. Checks not run
- No builds or tests were run, and no probe was compiled. Every command above is proposed and unverified.
- Graph and Serena tools weren't used, so no `check_index_coverage` either. All claims come from direct file reads and `rg`.
- Not inspected in depth: the SystemAsync `ProcessManager` shutdown path, IPC and Storage test names (their commands run unfiltered), and `docs/roadmap/PERFORMANCE.md`.
- Two C++ points are assumed, not compile-checked: that the `move_only_function` used by `TimerQueue` is available, and that `std::uniform_int_distribution` is consistent across toolchains (the tests assert bounds, not exact values).
**Files most relevant to this plan:**
- `/home/faumaray/Projects/VoidLibrary/src/IO/EpollDriver.cpp`
- `/home/faumaray/Projects/VoidLibrary/include/Void/Async/Executor.hpp`
- `/home/faumaray/Projects/VoidLibrary/include/Void/Async/TaskScope.hpp`
- `/home/faumaray/Projects/VoidLibrary/include/Void/Runtime/Host.hpp`
- `/home/faumaray/Projects/VoidLibrary/include/Void/Functional/Retry.hpp`
- `/home/faumaray/Projects/VoidLibrary/include/Void/System/SignalWatcher.hpp`
- `/home/faumaray/Projects/VoidLibrary/src/System/SignalWatcher.cpp`
- `/home/faumaray/Projects/VoidLibrary/tests/package/InstalledComponents.cmake`
- `/home/faumaray/Projects/VoidLibrary/src/Net/HttpServer.cpp`
@@ -0,0 +1,349 @@
# W11-PLAN-REV1 contract addendum (opus-planner, 2026-11-29)
Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`.
# W11-PLAN-REV1: contract addendum (deltas only)
**Status: DONE.** I accepted every root resolution, with three clarifications recorded at the end:
- F5: the off-owner signal adapter should close its fd. That matches 1.x and avoids a descriptor leak.
- F1(a): the injected `FileSyscalls` shim is the one exception to "workers never run user code".
- Observable: queuing nested updates for copyable types is a 1.x ordering change that MIGRATION must record.
Nothing was written to the repository. The reviewer's findings aren't persisted separately: `W11-PREFLIGHT.md` is the review brief. I worked from your F1–F13 and P3 summary. Gates G1–G5 stay; G6 is new; the B2 and A4 file sets change (table at the end).
---
## F1 (P1) S-IO-03 teardown thread rule (owner B2)
**Invariants**
- **(a)** A file worker performs one syscall (native or `FileSyscalls` shim) and nothing else. It then pushes `{request, result}` onto `FileWorkerShared::completions` under the shared mutex and calls the waker.
- Resume tickets are produced only by a poll turn, which drains `completions` through the existing `complete_op_and_collect_tickets` / `dispatch_tickets` path.
- `run_file_work()` executes one syscall on the caller's thread and only queues its result.
- **(b)** Workers hold only `std::shared_ptr<detail::FileWorkerShared>` (queues, mutex/condvar, completion queue, and a waker given as function pointer plus context). They never hold `shared_ptr<DriverBackend>`.
- The waker's raw backend pointer stays valid because workers are joined before the backend can be destroyed: `Driver::~Driver` and `shutdown_and_join` both join first.
- **(c)** `~EpollBackend`, `~MockBackend` and `~FileWorkers` never block. `~FileWorkers` finding a joinable thread prints a diagnostic to stderr and calls `std::terminate`.
- Today `~EpollBackend` blocks (`EpollDriver.cpp:953-955` calls `shutdown_and_join`); that call is removed.
- `Driver::~Driver` (`:1737-1742`) becomes the blocking teardown: `backend_->teardown_blocking()`.
- **(d)** Two thread-local markers detect misuse:
- `tl_io_worker_owner` (a non-null pool pointer on worker threads)
- `tl_polling_backend` (set while a thread runs that backend's `poll_once` turn)
`~Driver` with either marker matching prints a one-line stderr diagnostic and calls `std::terminate`.
- NEW, declared in `Driver.hpp` and defined in `FileWorkers.cpp`:
```cpp
[[nodiscard]] bool Void::IO::is_io_worker_thread() noexcept; // true on any Driver's file-worker thread
```
**(e) Tests (`IoFile.cpp`)**
- `io_driver_destroyed_from_coroutine_resumed_after_poll_dispatch_same_thread`: with `ManualExecutor`, `poll_once` dispatches a ticket and `exec.drain()` on the same thread resumes a coroutine that resets the `unique_ptr<Driver>`. Teardown must complete with no terminate.
- `io_worker_thread_marker_only_on_file_workers`: a gated shim records `is_io_worker_thread()` as true inside `pread`; it is false on the main thread, inside the poll turn and inside executor drain. The terminate path is documented only; no death test, because the Runner has no fork-based death support (`src/Testing/Subprocess.cpp:142` only execs helpers).
## F2 epoll/eventfd lifetime (B2)
- The epoll fd and eventfd still close in `~EpollBackend`, as in 1.x (`:956-963`).
- Shutdown closes only operation and descriptor fds, and only after it holds poll ownership.
- `wake()` loads `std::atomic<bool> wake_closed_` (acquire) and returns if set. It is set (release) when shutdown completes.
- Lock vs atomic: atomic is enough, and TSan-clean. `wake_fd_` is written only in the constructor (`:1255-1265`) and in `~EpollBackend`.
- All `wake()` callers hold a shared owner: `Driver::backend_`, the `CancelForwarder` weak→lock at `:589-596`, and `StreamState::lock_backend` at `Backend.hpp:89-96`.
- Workers are joined first.
- So the destructor's write happens after every `wake()` call, through the `shared_ptr` control block's acq_rel ordering.
- `poll_once` checks `shut_down_` (acquire) on entry and returns `0` before touching any fd. That keeps the 1.x return value (`:1057-1059` returns `work_done`).
## F3 / F4 Runtime shutdown phases and budgets (B4)
```cpp
enum class ShutdownPhase : std::uint8_t { not_started, closing_admission, draining, cancelling, joining_business,
stopping_components, flushing_exporters, releasing_components, stopping_io, stopping_workers, releasing, stopped };
```
**Phase order**
| # | Phase | What happens |
| --- | --- | --- |
| 1 | `closing_admission` | business scope closes admission |
| 2 | `draining` | wait for the business scope to drain (deadline fixed at first entry) |
| 3 | `cancelling` | request stop on the business scope |
| 4 | `joining_business` | wait for the business scope to finish |
| 5 | `stopping_components` | non-exporter components stop |
| 6 | `flushing_exporters` | exporters stop (flush deadline fixed at first entry) |
| 7 | `releasing_components` | drop every component `shared_ptr`, so exporters are destroyed here |
| 8 | `stopping_io` | owned driver shuts down |
| 9 | `stopping_workers` | wait for the owned executor to go idle within budget, then join the reactor and executor |
| 10 | `releasing` | budgets and fds; signal gate on the owner thread |
| 11 | `stopped` | |
- The ordering assertion `exporter_stopped < exporter_destroyed < executor_joined` stays.
- **Per-call budget:** every `shutdown_blocking`, `poll_shutdown` and `shutdown_pumping` call uses `call_deadline = min(options.deadline, deadline_after(clock, total_timeout))` for the work that remains.
- **Phase deadlines:** the drain and flush deadlines are fixed when their phase is first entered and stay expired afterwards.
- Drain expiry moves on to phase 3 and sets `drain_grace_expired`.
- Flush expiry requests stop on the exporter operations, sets `export_flush_expired`, and keeps waiting.
- **Incomplete:** if `call_deadline` expires in a waiting phase (4, 5, 6, 8 or 9), the sequence stops and returns `complete=false`, with the phase and state recorded as `shutdown_incomplete`. The next call resumes at that phase.
- NEW `[[nodiscard]] bool Async::ThreadExecutor::idle() const noexcept;` (both queues empty and nothing running), used by phase 9 so the executor join is never unbounded.
## F5 Host ownership (B3, with the B4 parts)
- All lifecycle state and teardown live in `detail::HostCore`, owned by `std::unique_ptr`. `~HostCore`:
- if the host is started and not stopped, calls `shutdown_blocking({})` (unbounded);
- then `gate->uninstall(this_thread == owner)`.
Default move-assign is therefore safe.
- **Moved-from Host** (`HostState` has no moved-from value, `Host.hpp:19-29`):
- NEW `[[nodiscard]] bool valid() const noexcept;`
- `state()` returns `stopped`; `is_running()` and `is_ready()` return false; `started_worker_count()` returns 0.
- `executor()` and `io()` return `nullptr`; `owner_thread()` and `last_shutdown_report()` return `nullopt`.
- `start`, `shutdown_*` and `poll_shutdown` return `RuntimeErrorCode::invalid_state`; `spawn` returns `AdmissionError::stopped`.
- `clock()` stays safe through its System-clock fallback (`:147-151`).
- `memory_budget()` has the precondition `valid()`. This is a pre-existing hazard: the 1.x code dereferences a null `owned_budget_` after a move (`:153-156`).
- `~HostCore` running on a Runtime worker, the reactor or an IO worker prints a stderr diagnostic and calls `std::terminate`. Detection uses:
- `executor->is_executor_thread()` (`Executor.hpp:86-96`)
- a Runtime `tl_reactor` marker
- `IO::is_io_worker_thread()`
- **SignalGate shape:**
```cpp
class SignalGate { public: virtual ~SignalGate() = default;
[[nodiscard]] virtual Void::Result::Result<void> install() = 0;
virtual void uninstall(bool on_owner_thread) noexcept = 0; }; // replaces uninstall()
```
- `shutdown_*` called off the owner thread leaves the gate installed (`owner_release_pending=true`). A later owner-thread call, or `~HostCore`, calls `uninstall(this_thread == owner)`.
- The System test adapter destroys its `SignalWatcher` in both cases. 1.x closes the fd on any thread (`SignalWatcher.cpp:29-31`) but restores the mask only on the owner (`:32-36`). Off-owner teardown therefore cannot restore the owner's mask; document this.
- Test: `runtime_offowner_destroy_closes_gate_fd_mask_not_restored`, which checks the `/proc/self/fd` delta is 0 and that the owner's mask is still blocked.
## F6 Teardown follows ResourceOwnership (B4)
- An embedded or borrowed executor, driver, clock or memory resource is never shut down, closed or joined by the Host. Phases 8 and 9 are skipped for borrowed resources.
- Signature:
```cpp
[[nodiscard]] Void::Result::Result<ShutdownReport> Host::shutdown_pumping(
Async::ManualExecutor&, Async::OperationOptions = {}, Async::TimerQueue* timers = nullptr);
```
It drives progress with `IO::pump_until(*io, manual, done, PumpOptions{.operation = call_budget, .timers = timers})`, so gate G5 stays.
- Test: `runtime_embedded_shutdown_never_shuts_borrowed_driver_or_executor`. After shutdown the borrowed driver still accepts `create_mock_stream` and the executor still accepts `try_post`.
## F7 AsyncChannel arbitration (A2)
- One `std::mutex` covers the buffer and both waiter lists.
- Waiter nodes live in the awaiter, inside the coroutine frame. Each holds `enum class WaiterState { linked, claimed, cancelled, timed_out, closed }`. A send waiter holds `std::optional<T> value`; a receive waiter holds `std::optional<T> slot`.
- Pairing a sender with a receiver happens under the lock, in one critical section: unlink and claim the waiter, then move the value. A value is therefore always in exactly one place: the sender node, the buffer or the receiver slot. It is never in limbo.
- Stop callbacks and timer callbacks take the same lock.
- If the waiter is still `linked`, it is unlinked and set to `cancelled` or `timed_out`. A sender keeps its value and gets it back.
- If it is already `claimed`, the callback does nothing. A sender gets success; a receiver gets the value that is already in its slot.
- Every resume is dispatched through `post_completion` after unlock. Each sender gets success or its value back exactly once.
- Tests:
- `channel_receiver_stop_after_claim_delivers_value_no_loss`
- `channel_sender_stop_vs_receive_race_exactly_once_tsan`: 10,000 iterations; the multiset of values sent equals values received plus values returned.
- `channel_timer_close_settles_waiter_cancelled` (see F12)
## F8 Default URBG (A1, B1)
House convention: `Retry.hpp:89` seeds with `std::random_device`.
```cpp
namespace Void::Retry::detail { template <class G> G seeded_engine()
{ if constexpr (std::is_constructible_v<G, std::random_device::result_type>) return G{std::random_device{}()}; else return G{}; } }
// RetryState::create(spec, start, URBG urbg = detail::seeded_engine<URBG>(), std::optional<SteadyTimePoint> = {})
// BlockingRetryOptions::urbg default member init = detail::seeded_engine<URBG>(); retry_async param default likewise
```
- Tests pass seeded `std::mt19937_64{42}` everywhere except `retry_state_default_engine_jitter_in_bounds`, which checks bounds only.
## F9 Revised D-W11-05: B2 owns the shutdown core, A4 owns thin wrappers
**B2 internal primitive in `detail::DriverBackend` (`Backend.hpp`):**
```cpp
virtual void begin_shutdown() noexcept = 0; // idempotent: close admission, cancel queued, stop active
[[nodiscard]] virtual Void::Result::Result<DriverShutdownReport> advance_shutdown(
std::optional<Void::Time::MonotonicClock::time_point> deadline, std::stop_token stop) = 0;
[[nodiscard]] virtual bool shutdown_complete() const noexcept = 0;
[[nodiscard]] virtual bool quiescent() const noexcept = 0; // no owned ops/requests/in-flight syscalls
virtual void teardown_blocking() noexcept = 0; // Driver::~Driver only
```
- B2 also owns `DriverShutdownReport` in `Types.hpp`, using the plan's fields.
- 1.x `shutdown_and_join()` becomes `advance_shutdown(nullopt, {})` mapped to `Result<void>`.
- `advance_shutdown` details:
- Waits for the injected-clock deadline in ≤1 ms real slices, re-reading the clock each time.
- Calls `wake()` to interrupt the current poller.
- Runs its own poll turns only while it holds poll ownership.
- Returns `self_join` if called on this backend's worker or inside its poll turn.
- **Poll-owner exclusion** uses a dedicated `std::mutex poll_mu_`. `poll_once` tries the lock and returns `std::unexpected(make_io_error(IoErrorCode::busy, ...))` if it can't get it, without touching any fd.
- I chose `busy` over `0` for three reasons: `busy` already means "concurrent op not allowed" (`EpollDriver.cpp:533-540`); the only library caller in a loop ignores the result (`IPC/Session.cpp:1128`); and a silent `0` would let a second `run()` loop spin.
- Test: `io_concurrent_poll_once_second_caller_busy_no_fd_touch_tsan`.
**A4 public wrappers** (inline in `Driver.hpp`; A4 touches no `.cpp`):
```cpp
void begin_shutdown() noexcept; // -> backend_->begin_shutdown()
[[nodiscard]] Void::Result::Result<DriverShutdownReport> shutdown(Async::OperationOptions); // -> advance_shutdown(o.deadline, o.stop)
[[nodiscard]] Void::Result::Result<std::size_t> run(std::stop_token, std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5});
[[nodiscard]] bool quiescent() const noexcept;
```
A4 also delivers `Pump.hpp`/`pump_until`, the SystemAsync conformance test, and tests.
## F10 Roadmap and doc edits (root, before dispatch)
**`docs/roadmap/modules/Functional.md`**
- **:95-96**: "NEW `RetryState` exposes `begin(now)`, `next(now, outcome)` and `resume(now)`: `next` returns `stop` or `wait_until(absolute time)`; `begin`/`resume` return `attempt` or `stop`. Callers map their error to `AttemptOutcome` with a supplied classifier."
- **:99**: append "; the default engine is seeded from `std::random_device`."
- **:104-106**: "Retain 1.x `retry`/`retry_while` unchanged, including the zero-attempt default-result defect (recorded for Wave C). NEW `retry_blocking` takes injected `now`/`sleep` callables, so Functional stays standard-library-only and no Time-dependent retry header exists. Async supplies `Async::retry_async` over `TimerQueue`."
**`docs/roadmap/subsystems/Runtime.md`**
- **:48-51**: "`Result<void> start(StartOptions); Async::Executor* executor(); IO::Driver* io(); Result<ShutdownReport> shutdown_blocking(Async::OperationOptions); Result<ShutdownReport> poll_shutdown(); Result<ShutdownReport> shutdown_pumping(Async::ManualExecutor&, Async::OperationOptions);` An awaited shutdown Task on the host's own executor is not offered, because it would self-join."
- **:73**: "install the injected `SignalGate` (Runtime has no System dependency; System-backed adapter optional) on the owner thread"
- **:77**: append "; off-owner teardown calls `uninstall(false)`, which cannot restore the owner's mask."
- **:114-117**: "6. After cleanup/export callbacks and backend references retire, drop component/exporter references, then stop owned IO, the reactor and CPU/file workers, and release budgets, descriptors and the signal gate in reverse creation order. Borrowed executor, driver, clock and memory are never shut down or joined by the Host."
- **:119**: "Each shutdown call observes min(caller deadline, now + total_timeout (30 s)) for remaining work. Drain-grace and flush deadlines are fixed at first entry to their phase. An incomplete phase stops the sequence and the next call resumes there."
- **:124-126**: "Destruction blocks to join only off Runtime threads. Destruction on a Runtime worker, reactor or IO file-worker thread is a programmer error that terminates after a diagnostic."
- **:159**: deps become "P2 / S-RUNTIME-01, M-ASYNC-04, S-IO-03; signal gate (injected port)".
- **:160**: deps become "P2 / S-RUNTIME-02, S-IO-04".
**`docs/roadmap/subsystems/IO.md`**
- **:77-79**: "The Driver owns no thread. One thread at a time runs a `poll_once` turn (the poll owner) and owns interest updates and generations; a concurrent caller gets `busy` without touching descriptors. Producers wake the owner through eventfd. Runtime or the embedder supplies the thread (`Driver::run`, `pump_until`)."
- **:92**: "Files use a bounded blocking worker pool started explicitly by `start_file_workers()` or stepped by `run_file_work()`. Workers run only the syscall or injected shim and queue its result; completions are delivered only by a poll turn."
- **:118-120**: "Driver shutdown closes admission, cancels queued requests, stops active ones, waits for the poll owner and in-flight syscalls, drains completions, joins workers, then closes operation descriptors. Epoll and wake descriptors close in the backend destructor. Blocking teardown runs in `Driver::~Driver`; destruction on a file worker or inside a poll turn is a programmer error."
- **:121-122**: "`File::close_and_join` returns `incomplete_shutdown` on expiry and retains the fd and buffers. A dropped File closes its fd after its last in-flight request drains."
- **:154**: "optional System/Net adapters" becomes "SystemAsync conformance; Net adapter deferred (Net has no IO use)".
**`docs/roadmap/MIGRATION.md:61` (Async/IO row, append to the evidence cell)**
"Recorded W11 changes:
- `Driver::shutdown_and_join` blocks for in-flight syscalls and joins file workers.
- `validate_limits` rejects `max_file_queue == 0`.
- Sync EventBus and Observable/Signal dispatch over snapshots; subscription changes take effect next pass.
- Nested Observable/Signal updates for copyable types are queued FIFO.
- Legacy `parallel_for` waits for all tasks before rethrowing.
- Async-mode EventBus handler exceptions are counted instead of terminating.
- Legacy `retry` zero-attempt result is kept until Wave C."
**DECISIONS:** amend D-W11-05 per F9, and add F1, F2 and F5 as root decisions.
## F11 Within-step failure coverage
- **IO (B2):** `BackendOptions::before_file_worker_start` (NEW, appended):
```cpp
std::function<Void::Result::Result<void>(std::size_t)> before_file_worker_start{};
```
- `start_file_workers` treats a hook error exactly like a caught `std::system_error`: it joins the workers already started, returns `os_error` (with the system code when one exists), and allows a retry.
- Test: `io_file_workers_partial_start_failure_joins_started`.
- **ThreadExecutor (A2):** `start()` catches `std::system_error` from `std::thread` through the same path as `before_worker_start`.
- **Runtime (B3):**
```cpp
struct StartOptions { /*...*/
std::function<Void::Result::Result<void>(StartStep, std::size_t thread_index)> before_thread_start{};
std::chrono::milliseconds cleanup_timeout{5000}; };
```
- `before_thread_start` is forwarded to the executor and IO hooks and to the reactor's `std::thread` creation, which also catches `std::system_error`.
- Failed-start component cleanup waits at most `cleanup_timeout` (injected clock). If it runs out, the state is `failed_start`, resources are retained, and the next `shutdown_blocking` or `~HostCore` continues the cleanup.
- Tests:
- `runtime_failed_start_thread_fault_each_threaded_step_reverse_cleanup` (cpu_executor, file_workers and reactor, at index 0 and at the last index)
- `runtime_failed_start_component_cleanup_timeout_retains_then_completes`
- `thread_executor_system_error_path_shared_with_hook`
## F12 Shared-core lifetimes
- **EventBus (A3):**
- Injected-mode dispatch frames capture `std::shared_ptr<detail::BusCore>`.
- `~EventBus` closes admission. On an executor thread it does not wait: frames finish against the shared core. Off the executor it calls `close_and_join` (blocking, or pumping on `ManualExecutor`).
- NEW `[[nodiscard]] Void::Result::Result<void> flush_blocking();` returns `self_join` on an executor thread or inside a bus callback, and `invalid_argument` on a `ManualExecutor` (`Executor.hpp:195`).
- NEW `flush_pumping(ManualExecutor&)`.
- Legacy `flush()` in Injected mode calls `flush_blocking()` and discards the error, because the 1.x signature returns `void` (`EventBus.hpp:193-201`). It never deadlocks.
- **TimerQueue (B1):**
```cpp
enum class TimerEvent : std::uint8_t { expired, closed };
using TimerCallback = std::move_only_function<void(TimerEvent) noexcept>;
```
- `TimerHandle` holds `shared_ptr<detail::TimerEntry>`, whose state is an atomic pending→{fired, cancelled} transition. `cancel()` is valid after the queue is destroyed.
- The callback runs exactly once (`expired` or `closed`), or never if `cancel()` returned true. Queue close or destruction invokes pending callbacks with `closed`; AsyncChannel maps that to `cancelled`.
- Test: `timer_handle_cancel_after_queue_destroyed_safe`.
- **`parallel_for` (A2):**
- Shared `detail::PForState` holds the decay-copied `F`, the chunk counter and the error slots.
- The caller waits for every submitted runner future, including runners that were never started.
- Nested use on the same pool from a pool worker is documented as unsupported.
- Test: `parallel_for_bounded_waits_all_submitted_runners`.
## F13 File descriptor lifetime (B2)
- `detail::FileState` is shared-owned and holds the fd, the shim, the in-flight count, a `close_pending` flag and the per-file ordering lane. Every request holds a reference to it.
- When the last handle drops:
- with no requests in flight, an internal close request is enqueued, using reserved capacity outside `max_file_queue`;
- otherwise `close_pending` is set, and the poll-turn retirement of the last request enqueues the close.
- Close always executes on a worker, or in `run_file_work`. Teardown closes any remaining file fds after the workers are joined.
- `File::close_and_join(options)` is always admitted.
- Deadline or stop expiry returns `IoErrorCode::incomplete_shutdown`; the File stays valid with its fd and buffers retained, so the call can be repeated.
- Success invalidates the File.
- A close syscall failure returns `os_error`, and the fd is treated as closed.
- This differs from `ByteStream::close_and_join`, which consumes the stream (`Stream.hpp:105`); document the difference.
- Tests:
- `io_file_drop_with_inflight_defers_close_until_drained`
- `io_file_close_and_join_expiry_incomplete_retains_then_completes`
## P3 resolutions
- **`retry_blocking` template defaults (A1):** use defaulted function-template parameters, because deduction cannot read a default function argument:
```cpp
template <class F, class NowFn = SteadyNow, class SleepFn = ThreadSleep,
class Classify = RetryEveryError, class URBG = std::mt19937_64>
auto retry_blocking(const RetrySpec&, F&&, BlockingRetryOptions<NowFn, SleepFn, Classify, URBG> = {});
```
Tests spell the option types explicitly; aggregate CTAD is a convenience only.
- **Observable/Signal (A3):**
- `Observable<T>` with `std::copy_constructible<T>`: a nested `set` updates the value immediately and queues `(old, new)` copies, delivered FIFO after the current pass and bounded at 1,024. On overflow, `set` keeps the new value and counts a dropped notification. `try_set` (only when copyable) returns `overloaded` without changing the value.
- Move-only `T`: the 1.x behavior stays — immediate recursive notification — but iteration runs over a listener snapshot. There is no queue and no `try_set`.
- `Signal<Args...>` follows the same rule when `(std::copy_constructible<std::decay_t<Args>> && ...)`; the queue is a `mutable` member, since `emit` is `const`.
- On a throw, the value stays the new value (as in 1.x, `Observable.hpp:40-42`), dispatch depth is restored, and that pass's queued notifications are dropped and counted.
- **S-IO-03 downstream build:**
```sh
-DVOID_ENABLED_MODULES="IO;IPC;SystemAsync;Storage;CryptoAsync;Runtime;ConfigurationAsync;Testing"
```
run unfiltered, plus `ctest`.
- **Error-kind alignment:** `RuntimeErrorCode::shutdown_incomplete = 9` maps to `ErrorKind::conflict`, matching `IoErrorCode::incomplete_shutdown` (`IO/Types.hpp:51-53`). IO is unchanged. Root pre-commit.
- **D1 regression seam (B2):**
- Test `io_epoll_stop_requested_at_deadline_scan_completes_once` uses a clock whose `now()` requests stop. That `now()` call happens in the wait computation, only when the op has a deadline (`EpollDriver.cpp:1083,1098`).
- The sequence:
1. The socket already has data.
2. The stop puts the cancel in the queue.
3. `drive_read` sees the stop and completes the op (`:1452`).
4. The end-of-turn cancel pass hits the same op (`:1173`).
- NEW appended telemetry field `DriverTelemetry::duplicate_completions_ignored`. The test asserts a single delivery and a counter ≥ 1.
- **Mock reactor spin (B3):** `MockBackend::poll_once` ignores `max_wait` (`EpollDriver.cpp:739-741`) and its `wake` only counts (`:637-640`).
- The Runtime reactor (and A4's `Driver::run`) waits on a stop-aware condition variable for `max_wait` when the backend is mock and a turn did no work.
- IO is unchanged, so the `IoDriver` test timing is untouched.
- **Business scope:** `TaskScopeOptions{.max_tasks = limits.max_cpu_tasks, .stop_on_first_error = false}`, because the default is `true` (`TaskScope.hpp:32`).
- **ThreadExecutor (A2):**
- After `close()`, a legacy `post()` goes onto the completion lane and is counted.
- `join()` drains until both lanes are empty and nothing is running. After join, posts resume inline and are counted.
- No drain cap: abandoning a handle would strand a frame, which C-03 forbids (`ARCHITECTURE.md:63-64`, "owner until exactly one terminal result"). A handle that re-posts itself forever prevents join; that is documented as a caller error.
- `~ThreadExecutor` without a prior join calls `close()` then `join()`. On its own worker it prints a diagnostic and terminates.
- **Runtime worker detection** uses `IO::is_io_worker_thread()` (F1).
- **Layering check (A4):**
```sh
rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO # expect no output
git diff --stat -- src/IO/module.cmake # expect empty
```
- **Budget accounting (B4):** test `runtime_shutdown_budget_bytes_retained_while_incomplete_zero_after_complete`.
- The Host passes `memory_budget()` as the Driver's pmr resource (`Driver.hpp:69-74`).
- An exporter holds a `BufferLease` across a stalled read.
- While incomplete: `memory_budget().stats().requested_live > 0` (`BudgetResource.hpp:106`, `Memory/Resource.hpp:22-30`), and `executor()->admitted()` and `DriverTelemetry::owned_buffer_bytes` stay as they were.
- After release and a second join: all three are 0.
- **M-ASYNC-05 captured-state tests (A3):**
- `bus_sync_unsubscribe_releases_captured_state`
- `bus_legacy_async_unsubscribe_then_flush_releases_captured_state`
- `bus_legacy_async_close_and_join_releases_capture_with_queued_copies`
All three assert the sentinel's `use_count() == 1`.
## Revised gates and ownership (changes only)
**Gates**
- G1–G5 as before.
- G4 now hands A4 only `Driver.hpp` (inline wrappers), the NEW `Pump.hpp` and tests.
- **G6 (new):** after A4 merges, all IO files are root-owned. B4 must stop and report if it needs an IO edit.
| Step | Owned-file delta |
| --- | --- |
| Root pre-commit | `RuntimeErrorCode::shutdown_incomplete` maps to `conflict` (changed from `timeout`) |
| B1 | adds `TimerEvent` and the shared-state `TimerHandle` to `Async/Timer.hpp` |
| B2 | adds to `IO/Driver.hpp`: `is_io_worker_thread`, `~Driver` teardown. Adds to `IO/Types.hpp`: `DriverShutdownReport`, `BackendOptions::before_file_worker_start`, `DriverTelemetry::duplicate_completions_ignored`. Adds to `IO/Detail/Backend.hpp`: the shutdown primitives. Also `src/IO/{EpollDriver.cpp, FileWorkers.{hpp,cpp}}` and `tests/standalone/IO/IoFile.cpp` |
| A4 | `include/Void/IO/Driver.hpp` (inline wrappers only), `include/Void/IO/Pump.hpp` (NEW), `tests/standalone/IO/{IoShutdown,IoPump}.cpp`, `tests/standalone/SystemAsync/SystemAsyncShutdown.cpp`. Not owned: `EpollDriver.cpp`, `Backend.hpp`, `Types.hpp`, `FileWorkers.*` (stop and report) |
| B3 / B4 | `Runtime/Lifecycle.hpp` gains `SignalGate::uninstall(bool)`, `StartOptions::{before_thread_start, cleanup_timeout}` and the renumbered `ShutdownPhase`. `Host.hpp` gains `valid()` and the 3-argument `shutdown_pumping`. A2 additionally owns `ThreadExecutor::idle()` |
## Root resolutions I'd adjust (not silently changed)
1. **F5 adapter wording.** "Releases its fd ... only on the owner thread" doesn't match 1.x: `SignalWatcher` closes the fd on any thread (`SignalWatcher.cpp:29-31`). Keeping the fd open off-owner would leak it, because no later owner-thread call is guaranteed. I recommend closing the fd and skipping only the mask restore, exactly as 1.x does; the F5 section above specifies that.
2. **F1(a) "workers never call user code".** The injected `FileSyscalls` shim runs on workers by design. It should be stated as the only exception: a syscall substitute that must not call Driver, Executor or File APIs.
3. **Observable copyable queuing.** It changes 1.x nested-set ordering from recursive to FIFO for copyable types. That's acceptable, since the roadmap mandates the queue, but it must appear in the MIGRATION record; F10 includes it.
**Checks not run:** no builds or tests. All citations come from direct reads during this session.
+125
View File
@@ -0,0 +1,125 @@
# Wave 11 execution-path backfill — architecture and task plan
Task ID: W11-PLAN
Role: opus-planner
Status: READY
## 1. Context and baseline
- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11`
created from `main` at `38436b1` (Waves 1–10 merged at `7d7d23e`, pushed to `origin/main`).
- Tracked tree clean. Untracked user files (`.env`, `WG.conf`, `keys`, `jev_token`, `.serena/`,
`.vbs/`, dotfiles, `compile_commands.json`) are NOT task inputs; never read, copy or quote them.
- Root gap analysis (2026-11-29): roadmap task tables list 300 tasks; `docs/agent-workflow/TASKS.md`
marks Waves 1–10 done, but these execution-path tasks remain open and their pre-roadmap
headers are untouched since baseline `f1f9ba3` (`git log f1f9ba3..HEAD` on
`Async/{Channel,EventBus,Observable,ParallelFor,ThreadPool}.hpp`, `Functional/Retry.hpp`
shows no commits; `IO`/`Runtime` only received `S-IO-01/02` `673bb7e` and `S-RUNTIME-01` `1b3331e`):
- P1 leftovers: `M-FUNCTIONAL-03`, `M-TIME-03`.
- P2: `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`, `S-RUNTIME-02`, `S-RUNTIME-03`.
- These gate `P-NETWORKED-02` / `P-RELOADABLE-02` ("Runtime/Async/IO lifecycle gates").
- Requirement/contract references: `docs/roadmap/REQUIREMENTS.md` R-001..R-016,
`docs/roadmap/ARCHITECTURE.md` C-01..C-14, gates G-ERROR/G-EXEC/G-IO in `DEPENDENCIES.md`.
- Baseline full build/test of `main` is running separately under root; not your concern.
## 2. Objective and deliverables
Produce an implementation-ready plan (returned as text, not written to files) for the eight
tasks above, plus a readiness verdict for `S-RPC-04` (WebSocket streaming) as an optional
ride-along. Deliverables in the reply:
1. Per task: observed baseline (exact existing symbols/behavior with `path:line`), the gap
against its roadmap row and area plan, and the minimal complete scope to satisfy the
row's acceptance text.
2. Per task: NEW public interfaces (C++ signatures, enums, error codes in existing domains,
limits/defaults) marked NEW, and which existing 1.x APIs stay unchanged (D-029).
3. Dependency graph between the eight tasks, and the module `INTERNAL_DEPS` changes, if any,
with a check that every edge respects `DEPENDENCIES.md` target package rules.
4. A partition into 2–3 worker packages with exclusive file ownership (exact paths), role
(`astra_*` rows → opus-implementer, `sol_*` rows → sonnet-implementer), and order.
Identify root-owned shared edits (e.g. `include/Void/Functional/Error.hpp`,
`tests/package/InstalledComponents.cmake`, top-level `CMakeLists.txt`, `cmake/*`).
5. Per task: concrete test list (test file paths, scenario names) mapping to acceptance text,
and exact verification commands (module subset, filters) in the repository's form.
6. Whether the "System signal gate" named by `S-RUNTIME-02` exists in current source
(cite symbols), or what minimal in-wave work it implies without adding Runtime→System
unless `DEPENDENCIES.md` permits it.
7. Risks, open questions that need a root decision, and anything in the roadmap rows that
is infeasible or contradictory, with a recommended resolution.
## 3. Scope and non-goals
In scope: planning only for the eight tasks and the S-RPC-04 readiness note.
Non-goals: editing files, writing specs, implementing code, running long builds, planning
foundation P2 leftovers (Core/Math/Text/Data/Binary/…) or P3/P4 platforms.
## 4. Files to inspect
- Roadmap: `docs/roadmap/modules/{Functional,Time,Async}.md`, `docs/roadmap/subsystems/{IO,Runtime,RPC}.md`,
`docs/roadmap/{ARCHITECTURE,DEPENDENCIES,MIGRATION,VALIDATION,PERFORMANCE}.md`,
`docs/roadmap/platforms/{NetworkedApplications,ReloadableApplications}.md` (gate wording only).
- Prior specs for style/precedent: `docs/agent-workflow/tasks/{M-ASYNC-02-03,S-IO-01-02,S-RUNTIME-01,M-TIME-02,M-FUNCTIONAL-02,M-SYSTEM-01-05}.md`.
- Source: `include/Void/Functional/{Retry,Error,Result}.hpp`, `src/Functional/module.cmake`;
`include/Void/Time/{Clock,Stopwatch}.hpp`; `include/Void/Async/*.hpp`, `src/Async/module.cmake`;
`include/Void/IO/{Types,Driver,Stream}.hpp`, `include/Void/IO/Detail/*`, `src/IO/{EpollDriver.cpp,module.cmake}`;
`include/Void/Runtime/{Options,ResourceGraph,Host}.hpp`, `src/Runtime/module.cmake`;
`include/Void/System/*` (signal handling), `include/Void/Net/*` (only for S-IO-04/S-RPC-04 adapters);
existing tests under `tests/standalone/{Functional,Time,Async,IO,Runtime}/`;
`cmake/Module.cmake`, `tests/CMakeLists.txt`, `tests/package/InstalledComponents.cmake`.
## 5. Write ownership and coordination
Write scope: none
Allowed commands: read-only `git`, `rg`, `ls`, `wc`, Serena/codebase-memory read tools. You may
compile a tiny probe only under `/tmp/void-w11-plan-probe` if essential; do not touch the
repository tree. `dev cpp-gcc ...` must run unsandboxed (nix fetcher lock); avoid it unless needed.
## 6. Implementation or investigation approach
1. Read each roadmap row and area-plan section; extract mandatory behavior and limits.
2. Inspect the current headers/tests via Serena symbol tools; record what exists.
3. Derive minimal complete NEW interfaces that layer beside 1.x APIs (Wave A+B, D-029).
4. Check layering: Functional has zero `INTERNAL_DEPS` (D-015) — retry decisions must take
injected time values or a template clock, not depend on `Time`; Async must not depend on
Log backends or Runtime; IO must not depend on Runtime/Net/System; Runtime composes.
5. Build the task DAG and the ownership partition minimizing cross-package header edits.
6. Draft test scenarios that prove each acceptance sentence deterministically (manual clocks,
mock IO backend) and TSan-relevant concurrency cases.
## 7. Interfaces and data contracts
Use existing contracts: `Void::Functional::{Result,Error,Status,ErrorCode}`, domains
`kTimeErrorDomain=4`, `kAsyncErrorDomain=7`, `kIoErrorDomain=8`, `kRuntimeErrorDomain=11`;
`Void::Time::{MonotonicClock,ManualClock}`; Async `OperationOptions`/`TaskScope`/`Executor`;
IO `Driver`/`BufferLease`; Runtime `Host`/`HostBuilder`/`ResourceGraph`. Any new error code
must extend an existing domain enum; propose exact enumerator names.
## 8. Dependencies and integration
Upstream: Waves 1–10 on `main`. Root owns integration, shared build files, and all commits.
Implementers will be dispatched only after a fresh opus-reviewer PREFLIGHT of your plan.
## 9. Edge cases security and performance
Call out: exactly-one-terminal-result races, stop/expiry/completion permutations, buffer
retention on active cancel, bounded queues including running work, reentrancy and
unsubscribe-during-dispatch, failed-start reverse cleanup with no leaked threads/fds,
signal-mask ownership, exporter-before-executor shutdown ordering, no user callbacks
under locks, overflow-safe deadline arithmetic.
## 10. Acceptance criteria
1. Each of the eight tasks has baseline, gap, NEW interface, tests and commands.
2. DAG and INTERNAL_DEPS changes respect DEPENDENCIES.md rules (stated per edge).
3. Ownership partition has no overlapping paths and lists root-owned shared files.
4. S-RUNTIME-02 signal-gate question answered with cited symbols.
5. S-RPC-04 readiness verdict with prerequisites cited.
6. Open decisions listed with a recommendation each.
## 11. Verification commands and evidence
Not applicable for builds: planning-only. Cite `path:line` for every baseline claim. Command
templates you propose must follow the observed form, e.g.
`dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-<x> -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-<x> && /tmp/void-w11-<x>/tests/VoidTests --filter "<Pattern>*" && ctest --test-dir /tmp/void-w11-<x> --output-on-failure --timeout 60'`.
## 12. Constraints and stop conditions
No repository edits, no commits, no network calls beyond local tools, no secrets. Stop and
report if a roadmap requirement contradicts a recorded decision (D-001..D-032) or would need
a new dependency edge forbidden by DEPENDENCIES.md.
## 13. Authorization and decisions
Root decision under D-027/D-031 (continuous roadmap-order execution): Wave 11 is the
execution-path backfill. Planning-only authorization; you do not approve your own plan.
## 14. Return format
Return task ID; DONE/BLOCKED/PARTIAL; summary; per-task sections (baseline, gap, NEW
interfaces, tests, commands); DAG; ownership partition; signal-gate answer; S-RPC-04 verdict;
risks; open decisions with recommendations; checks not run. Do not spawn children.
@@ -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,80 @@
# Wave 11 PREFLIGHT re-review of the contract addendum
Task ID: W11-PREFLIGHT-2
Role: opus-reviewer
Status: READY
## 1. Context and baseline
- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11` from `main`
`38436b1`. Uncommitted root prep: workflow docs, roadmap area-plan edits
(`docs/roadmap/{modules/Functional.md,subsystems/IO.md,subsystems/Runtime.md,MIGRATION.md}`), and new
enumerators `AsyncErrorCode::closed=9` (→cancelled), `IoErrorCode::sync_failed=12` (→io),
`RuntimeErrorCode::{self_join=8, shutdown_incomplete=9}` (→conflict). Untracked user files
(`.env`, `WG.conf`, `keys`, `jev_token`, `.serena/`, `.vbs/`, dotfiles) are not inputs.
- Baseline `38436b1`: `VoidTests` 1,484 discovered, 1,480 passed, 4 skipped, 0 failed.
- First PREFLIGHT verdict CHANGES_REQUIRED: `docs/agent-workflow/tasks/W11-PREFLIGHT-OUTPUT.md`.
Original plan: `W11-PLAN-OUTPUT.md`. Planner addendum answering it: `W11-PLAN-REV1-OUTPUT.md`.
Root disposition: `docs/agent-workflow/DECISIONS.md` D-038.
## 2. Objective and deliverables
Fresh, independent verdict (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE) on whether the
addendum plus root doc edits resolve findings F1–F13 and the P3 list without introducing new
defects, so implementation specs can be written. Severity-ranked findings for anything still
open or newly introduced.
## 3. Scope and non-goals
In scope (from the first review's re-review scope): revised S-IO-03, S-IO-04, S-RUNTIME-03
contracts (F1–F6, F9, F13); AsyncChannel, Retry, EventBus, TimerQueue invariants (F7, F8,
F12); area-plan/MIGRATION edits (F10); the three planner adjustments (signal adapter closes
fd off-owner; syscall shim exception; Observable FIFO ordering change). Also check the
`poll_once` concurrent-caller choice (`busy`), the `wake_closed_` atomic argument, the
`FileState` close-request reserved capacity, and `ThreadExecutor::idle()` use in phase 9.
Non-goals: re-reviewing parts confirmed sound in the first review, style, other waves.
## 4. Files to inspect
`docs/agent-workflow/tasks/{W11-PLAN-OUTPUT,W11-PREFLIGHT-OUTPUT,W11-PLAN-REV1-OUTPUT}.md`,
`docs/agent-workflow/DECISIONS.md` (D-038), `git diff` of the root prep, and source cited by
the addendum: `src/IO/EpollDriver.cpp`, `include/Void/IO/{Types,Driver,Stream}.hpp`,
`include/Void/IO/Detail/Backend.hpp`, `include/Void/Async/{Executor,Operation,TaskScope,EventBus,Observable}.hpp`,
`include/Void/Runtime/{Host,Options}.hpp`, `src/System/SignalWatcher.cpp`, `src/IPC/Session.cpp`
(poll_once result use), `include/Void/Memory/BudgetResource.hpp`.
## 5. Write ownership and coordination
Write scope: none
Allowed commands: read-only `git`, `rg`, `ls`, `sed -n`, Serena/codebase-memory read tools; optional
probes only under `/tmp/void-w11-preflight2-probe`. A root subset build runs in
`/tmp/void-w11-prep`; do not touch it.
## 6. Implementation or investigation approach
1. For each F1–F13 and P3 item: state RESOLVED / PARTIAL / UNRESOLVED with evidence.
2. Look for new hazards the resolutions introduce (e.g. raw waker pointer lifetime, `busy` from
`poll_once` breaking existing callers that loop on it, reserved close capacity unbounded,
phase-9 idle wait vs inline-resume after join, `~HostCore` unbounded shutdown on destruction).
3. Check the area-plan edits are consistent with the addendum and with D-001..D-038.
## 7. Interfaces and data contracts
Not applicable for new authorship: review the addendum's signatures as written.
## 8. Dependencies and integration
A1 (M-FUNCTIONAL-03) and B1 (M-TIME-03 Timer) may be dispatched in parallel with this review
(D-038); report any finding affecting F8/F12 explicitly so root can correct them.
## 9. Edge cases security and performance
Same list as the first PREFLIGHT: fd reuse, signal masks, partial start, TaskScope destructor,
ManualClock + blocking waits, inline resume after join, retained buffers, tombstones.
## 10. Acceptance criteria
1. Verdict with justification. 2. Each F1–F13/P3 item marked RESOLVED/PARTIAL/UNRESOLVED.
3. New findings have severity, location, trigger, impact, evidence, recommendation.
## 11. Verification commands and evidence
Read-only inspection, e.g. `git diff -- docs/roadmap include/Void`, `rg -n "poll_once\(" src include`.
## 12. Constraints and stop conditions
No edits, commits or network; no spawning. Mark INSUFFICIENT_EVIDENCE rather than guess.
## 13. Authorization and decisions
Root decisions D-034, D-038 under user decisions D-027/D-031. Technical check only.
## 14. Return format
Task ID; verdict; per-item status table; new findings P0→P3; checks not run. Compact.
@@ -0,0 +1,163 @@
# W11-PREFLIGHT output (opus-reviewer, 2026-11-29)
Verbatim agent return. Advisory input; root dispositions are recorded in `DECISIONS.md`.
**Task:** W11-PREFLIGHT. **Verdict: CHANGES_REQUIRED.**
The plan's direction is sound. The layering holds, no `INTERNAL_DEPS` change is needed, no two packages own a path at the same time, the gates G1–G5 contain no cycle, and almost every baseline claim matches the source. It is not yet complete enough to write specs from. There is one P1: the plan has no rule for what happens to driver teardown on a worker or poll thread. Eleven P2s need a fix or an explicit risk acceptance before dispatch.
Paths below are relative to `/home/faumaray/Projects/VoidLibrary`. "Plan" means `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md`.
## P1
**F1. S-IO-03: no destructor or teardown-thread rule once the driver owns threads.** (Inferred defect if the spec is written as the plan reads.)
- **Location:** plan :542-548. `Driver::~Driver` at `src/IO/EpollDriver.cpp:1737-1742` and `~EpollBackend` at :953-963 both call `shutdown_and_join()` and ignore the result.
- **Evidence:**
- `Driver::poll_once` (:1843-1847) does not hold its own reference to the backend during a turn.
- Streams hold only a `weak_ptr` to the backend (`include/Void/IO/Detail/Backend.hpp:85-125`). Stop forwarders lock it briefly (:279-285). So the last owning reference can drop on any thread.
- **Trigger:** the plan makes `shutdown_and_join` return `self_join` on a worker or during poll dispatch, and makes it block until the poll turn and the workers finish. Then either:
- `~Driver` or `~EpollBackend` runs on a file worker or the poll thread. The self_join result is ignored, and a joinable `std::thread` is destroyed or joins itself, which calls `std::terminate`. Or the poll turn waits on itself and deadlocks.
- The last backend reference drops on a worker or poller.
- Also, after `ThreadExecutor::join` the plan resumes coroutines inline, so a coroutine can run on a file worker and destroy the `Driver` or a `File` there.
- **Impact:** abort or deadlock on the main teardown path every 1.x IO user takes (IPC, SystemAsync, CryptoAsync, Storage, Runtime).
- **Fix:** add mandatory invariants to the S-IO-03 spec:
- Only `~Driver` does a blocking teardown. It defines what happens on a worker or poll thread: a documented programmer error such as `terminate`, or deferring the join to a safe owner.
- `~EpollBackend` and `~FileWorkers` never block and never destroy a joinable thread.
- Workers and pollers never hold the last owning reference to the backend, or the pool's state is owned separately.
- Tests: Driver destroyed inside a coroutine resumed by poll dispatch, and inside a worker completion.
## P2
**F2. S-IO-03 shutdown step 5 opens a new fd-reuse hazard.**
- **Location:** plan :547, "close the fds, epoll and eventfd".
- **Evidence:** in 1.x, `epoll_fd_` and `wake_fd_` are closed only in `~EpollBackend` (:953-963). `wake()` reads a plain `int` and writes to it (:1033-1042). `enqueue_cancel` (:153-166) and `request_stop` call `wake()`.
- **Trigger:** S-RUNTIME-03 phase 7 shuts the driver down, then phase 8 stops the reactor, which typically calls `wake()`. Late stop forwarders do the same. The write lands on a closed, possibly reused, integer fd. That is also a data race that TSan will report.
- **Fix:** keep epoll/eventfd closure in the backend destructor (1.x placement), or guard `wake()` with a lock and a closed flag. After shutdown, `poll_once` must return before touching any fd. 1.x already returns early once `stopping_` is set (:1056-1058).
**F3. S-RUNTIME-03 contradicts itself on exporter vs executor order.**
- Plan :729-730 joins the executor (phase 8) before dropping component references (phase 9).
- The test at :742 asserts `exporter_destroyed < executor_joined`.
- **Fix:** drop exporter/component references after their stop finishes and before reactor/executor join (this matches the row name), or change the assertion. Decide in the spec.
**F4. S-RUNTIME-03: a repeated join after expiry has no budget.**
- Plan :719 fixes the total deadline at the first `begin_shutdown`. Plan :734 says the next call continues.
- After the first expiry, every later `shutdown_blocking` has zero wait budget. Thread joins and executor progress need real waiting, so "release → join again → complete" (:742) becomes a busy loop or a flaky test.
- **Fix:** after a total-budget expiry, later calls use the caller's new deadline. Expired phase deadlines (drain, flush) stay expired. Also say explicitly that an incomplete phase stops the sequence; plan :728 "if incomplete, retain it" is ambiguous.
**F5. Host lifecycle holes.**
- **Move-assignment:** `Host& operator=(Host&&) = default` (`include/Void/Runtime/Host.hpp:91`) destroys the overwritten state through the `unique_ptr<HostCore>` without running `~Host`. If teardown lives in `~Host` (plan :661), move-assigning over a started Host leaks joinable threads, and `std::thread`'s destructor terminates. Put teardown in `~HostCore` or write a custom move-assignment.
- **Moved-from Host:** accessors like `options()` and `state()` need defined behaviour when the core is null.
- **`~Host` on a Runtime worker:** behaviour is unspecified. The roadmap calls it a detected programmer error.
- **`~Host` off the owner thread:** a non-owner destructor cannot restore the mask, and `SignalWatcher` silently skips the restore off-thread (`src/System/SignalWatcher.cpp:27-37`). The plan (:731) must say whether the gate is leaked or uninstalled without a mask restore.
**F6. Embedded mode would shut down borrowed resources.**
- Phase 7 calls `driver->shutdown()` and phase 8 joins the executor unconditionally (plan :728-729). In embedded mode both are borrowed (`include/Void/Runtime/Host.hpp:31-56`). The roadmap says borrowed resources must outlive final cleanup.
- **Fix:** tear down by `ResourceOwnership`. Embedded `shutdown_pumping` drains only the business scope and components, and must drive IO and timers through `pump_until`; `TaskScope::join_pumping` never polls IO (`include/Void/Async/TaskScope.hpp:639-647`).
**F7. AsyncChannel: hand-off vs stop/close arbitration is unspecified (value-loss risk).**
- Plan :327-344 states only the outcomes.
- **Fix:** mandate that a waiter is claimed under the channel lock before a value moves; the stop callback must take the same lock to remove a waiter; a value is never in limbo; a sender gets either success or its value back, exactly once.
- Add a receiver-stop test (no value lost).
**F8. Retry: the default URBG is deterministic.**
- Plan :102, :137 and :228 default-construct `std::mt19937_64`, which always starts from the same fixed seed. Every process then draws the same jitter, which defeats jitter's purpose.
- House convention seeds from `random_device` unless a deterministic seed is given (`include/Void/Functional/Retry.hpp:87`; `include/Void/Resilience/AsyncPolicy.hpp:487,525-529`).
- **Fix:** seed from `random_device` by default; tests pass a seeded engine.
**F9. D-W11-05 routing: sonnet takes the riskiest code.**
- A4 (sonnet) rewrites the bounded, repeatable shutdown, poll-owner exclusion, manual-clock-sliced waits and `run()` concurrency in the same `src/IO/EpollDriver.cpp` B2 just changed. That is astra-level work.
- **Fix:** B2 delivers an internal deadline-aware shutdown/poll-owner primitive; A4 only adds the public wrappers, `pump_until` and tests. Or route that part to opus.
**F10. C-13: area plans must be updated before parallel work.**
- The plan changes contracts in area plans:
- Functional.md: the clock/sleeper adapter moves out of the separate Time header (D-W11-02).
- Runtime.md: awaited shutdown becomes blocking/polling APIs; `file_workers` authority.
- IO.md: the "driver thread" model.
- Several row prerequisites change.
- `docs/roadmap/ARCHITECTURE.md` C-13 (:246-252) requires the decision ledger and area plans to be updated before parallel implementation. `docs/roadmap/**` is missing from the root-owned list (plan :786-790). Add a root step before dispatch.
**F11. Within-step start failures are not covered (S-RUNTIME-02 acceptance).**
- The `before_step` hook (plan :652, :686) only injects failure between steps.
- Not specified or tested:
- partial failure inside `start_file_workers()`
- the reactor thread constructor throwing `std::system_error`
- `std::thread` throwing inside `ThreadExecutor::start`
- the stop budget for components during failed-start cleanup.
- **Fix:** add an IO fault hook and `io_file_workers_partial_start_failure_joins_started`, catch thread-creation exceptions, and bound the cleanup.
**F12. Async lifetimes of borrowed objects.**
- **EventBus (Injected mode):** `~TaskScope` skips joining when it runs on an executor thread (`include/Void/Async/TaskScope.hpp:562-575`). If `~EventBus` runs on a worker, dispatch frames can still touch the destroyed bus. Dispatch must reference only a shared core, or this must be a documented error. `flush()` semantics in Injected mode are also unspecified.
- **TimerHandle:** move-only and may outlive its `TimerQueue` (plan :198-199). It needs shared control state.
- **Bounded `parallel_for`:** "All started runners are always joined" (plan :358). Runners that were queued but not yet started would later touch the caller's stack. Either wait for all submitted runners (and document that nested use on the same pool is unsupported) or put runner state, including the copied `F`, in shared ownership.
**F13. File lifetime is unspecified.**
- `~File` with requests still in flight must defer the fd close until they drain; otherwise the fd can be reused while a worker still uses it.
- `File::close_and_join` on expiry should return `incomplete_shutdown` (exists at `include/Void/IO/Types.hpp:32`) and keep the fd and buffers.
- The roadmap says workers keep the descriptor until the syscall returns.
## P3
- **`retry_blocking` signature:** the template parameters have no defaults (plan :139-141), so `retry_blocking(spec, fn)` cannot deduce `NowFn` and the rest from the defaulted argument. Add the defaults.
- **Observable/Signal:** queuing nested `(old, new)` notifications and arguments requires copyable `T`/`Args`, which breaks 1.x compile for move-only types (D-029). Also state "state restored" precisely: the value stays new, as in 1.x.
- **S-IO-03 downstream build** (plan :576): omits CryptoAsync, Runtime and ConfigurationAsync, which also depend on IO.
- **Error kinds:** Runtime `shutdown_incomplete` maps to `timeout`, but IO `incomplete_shutdown` maps to `conflict` (`include/Void/IO/Types.hpp:50-52`). Align them.
- **D1 regression test needs a seam:** the double release isn't visible through the public API. Suggested deterministic trigger: an injected clock whose `now()` requests stop. That call happens between the step-1 drain and the event dispatch (:1083).
- **Mock reactor spin:** the mock `poll_once` ignores `max_wait` (:739-740), so a Runtime reactor on a mock driver busy-spins under TSan.
- **Host business scope:** the default `stop_on_first_error=true` (`include/Void/Async/TaskScope.hpp:32`) means one failing business task stops all of them, against the roadmap's per-component failure policy.
- **MIGRATION records needed** ("observable behavior" row): `shutdown_and_join` now blocks and joins; `validate_limits` rejects `max_file_queue==0`; Sync EventBus becomes snapshot dispatch; legacy `parallel_for` waits for all tasks.
- **Unspecified:** behaviour of concurrent `poll_once` callers; who owns IO files after G5; a stop-and-report rule if B3 or B4 needs an IO edit; how Runtime detects that it is running on a file worker.
- **ThreadExecutor:** `join()` can drain forever if `post()` keeps re-posting after close. `~ThreadExecutor` without `join` is unspecified.
## D1 claims (all confirmed)
- **(a) Unconditional release — CONFIRMED.** `complete_op_and_collect_tickets` releases at :448, even though `retire_op_locked` is idempotent (:391-394). `release_backend_ref` cannot be called twice safely (`include/Void/Async/Operation.hpp:185-193`); the count underflows.
- **(b) Cancel path doesn't skip finished operations — CONFIRMED** (:1332-1351). The mock path does skip them (:770-781).
- Precise trigger: a stop arrives after the start-of-turn drain (:1053) while `drive_read`/`drive_write` completes the operation (including their own stop check, :1453-1458 and :1527-1535). The end-of-turn drain (:1173) then releases a second time.
- Impact the plan omits: if the waiting coroutine has not suspended yet, `try_arm_suspend` sees a non-zero count and the coroutine hangs forever. Otherwise the counter is silently corrupted.
- **(c) Syscalls outside `mu_` without `in_execution` — CONFIRMED.** `::read` at :1466; `::send` and `::write` at :1549 and :1560. `in_execution` is used only by the mock (:653-671, 758, 774, 791, 847-850).
- **(d) Cross-thread shutdown — CONFIRMED** (:1179-1238).
- It finishes operations regardless of whether a syscall is in progress (:1186-1206). The caller can then free its buffer while `::read` is still writing into it.
- It closes the fd (:1221 → :363) while the poller still holds the integer it read at :1151, so the number can be reused.
- Additional facet: when `~Driver` is the shutdown path, the backend object itself can be destroyed mid-turn (F1).
- **"No test covers it" — CONFIRMED.** `tests/standalone/IO/IoDriver.cpp:458-508` cancels a read that never becomes readable and joins the poller before teardown.
## Other source claims
- **ManualExecutor bound — CONFIRMED.** `post` counts without a check (`include/Void/Async/Executor.hpp:128-135`); `run_one` decrements before resuming (:216-228).
- **SignalWatcher — CONFIRMED** (`include/Void/System/SignalWatcher.hpp:13-15`; `src/System/SignalWatcher.cpp:27-37,74-90`).
- **Host movable, default destructor, worker count always 0 — CONFIRMED** (`include/Void/Runtime/Host.hpp:88-92,173`).
- **Threads flags — CONFIRMED** (`tests/package/InstalledComponents.cmake:73-79,104-112`; `cmake/VoidConfig.cmake.in:97`).
- **Minor:** `tests/standalone/Async/OperationScope.cpp:135` is not a thread-backed executor; it wraps a ManualExecutor.
## D-W11-01..15
| ID | Recommendation |
| --- | --- |
| D-W11-01 | Accept |
| D-W11-02 | Accept, and update Functional.md (F10) |
| D-W11-03 | Accept; label the pinned test as defect characterization and record it for Wave C |
| D-W11-04 | Accept. System requires Threads, so a Runtime→System edge would also break RuntimeOnly. Add the off-owner rules from F5 |
| D-W11-05 | Modify (F9) |
| D-W11-06 | Accept, provided a throwing `error_sink` is caught and counted and Sync propagation is unchanged; record the change |
| D-W11-07 | Accept |
| D-W11-08 | Accept, provided IOOnly/RuntimeOnly start a real worker thread with Threads disabled; record the libc-with-integrated-pthreads assumption (IO already relies on it at `src/IO/EpollDriver.cpp:47`) |
| D-W11-09 | Accept |
| D-W11-10 | Accept; it fixes a real use-after-free when caller-stack captures outlive a throw. Record the timing change |
| D-W11-11 | Accept, plus partial-start semantics (F11) |
| D-W11-12 | Accept (`max_output_*` unused in `src/Net`, confirmed) |
| D-W11-13 | Accept; record that the C-05 defaults are deferred |
| D-W11-14 | Accept; document that nothing polls a TimerQueue under managed Runtime, so channel deadlines and `retry_async` need caller-driven polling or `pump_until` |
| D-W11-15 | Accept; align error kinds (P3) |
## Acceptance sentences not covered
- **S-IO-04:** "no IO→Runtime/Net dependency" has no check. Add `rg -n "Void/(Runtime|Net|System)/" include/Void/IO src/IO` (expect no output) plus a diff of `src/IO/module.cmake`.
- **S-RUNTIME-02:** "failure at every creation/start step" only covers failures between steps (F11).
- **S-RUNTIME-03:** "exporter-before-executor ordering" contradicts the phase order (F3). "Budget accounting" is ambiguous: only the shutdown budget is tested, not memory or admission permits.
- **M-ASYNC-04:** no test for receiver-side cancellation.
- **M-ASYNC-05:** "no captured state in use after join" is tested only for Injected mode, not the legacy Async or Sync modes.
- M-FUNCTIONAL-03, M-TIME-03 and S-IO-03 are fully mapped.
## Checks not run
- No builds or compile probes; every plan command is unverified.
- No Serena or codebase-memory coverage checks; all evidence comes from direct `sed`/`rg` reads.
- The advisor call timed out.
- Not inspected: the SystemAsync `ProcessManager` shutdown path, IPC/Storage/CryptoAsync internals, `docs/roadmap/VALIDATION.md`, `docs/roadmap/PERFORMANCE.md`.
**Re-review scope:** the revised S-IO-03, S-IO-04 and S-RUNTIME-03 contracts (F1–F6, F9, F13), the AsyncChannel, Retry, EventBus and TimerQueue invariants (F7, F8, F12), and the area-plan updates (F10).
+107
View File
@@ -0,0 +1,107 @@
# Wave 11 PREFLIGHT review of the execution-path plan
Task ID: W11-PREFLIGHT
Role: opus-reviewer
Status: READY
## 1. Context and baseline
- Repo root / cwd: `/home/faumaray/Projects/VoidLibrary`; branch `feat/roadmap-p2-wave11` from
`main` `38436b1`. Only workflow docs changed so far (uncommitted): `docs/agent-workflow/{STATE,TASKS,DECISIONS}.md`,
`docs/agent-workflow/tasks/W11-*.md`. Untracked user files (`.env`, `WG.conf`, `keys`, `jev_token`,
`.serena/`, `.vbs/`, dotfiles) are not inputs; never read or quote them.
- Observed baseline: full RelWithDebInfo `-Werror` build of `38436b1` in `/tmp/void-w11-base`:
`VoidTests` 1,484 discovered, 1,480 passed, 4 skipped, 0 failed; `ctest` 2/2 passed.
- Subject: `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` (opus-planner output for
`M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04`, `M-ASYNC-05`, `S-IO-03`, `S-IO-04`,
`S-RUNTIME-02`, `S-RUNTIME-03`). Assignment it answered: `W11-PLAN.md`. Root decisions D-033..D-037 in
`docs/agent-workflow/DECISIONS.md`. Contracts C-01..C-14 in `docs/roadmap/ARCHITECTURE.md`.
## 2. Objective and deliverables
Independent PREFLIGHT verdict (READY / CHANGES_REQUIRED / INSUFFICIENT_EVIDENCE) on whether the
plan's contracts, ordering gates, ownership partition and failure semantics are correct and
complete enough to write implementation specs. Deliver severity-ranked findings (P0–P3) with
location, trigger, impact, evidence and recommended correction, plus a disposition
recommendation for each open decision D-W11-01..D-W11-15.
## 3. Scope and non-goals
In scope: contract soundness, missing or contradictory invariants, cross-file obligations,
hidden dependencies, layering violations, 1.x compatibility (D-029), testability of every
acceptance sentence, and the plan's factual claims about current source (especially the
claimed epoll defects "D1" in `src/IO/EpollDriver.cpp`, the `ManualExecutor` bound,
`SignalWatcher` behavior, `Host` movability, and installed-consumer Threads flags).
Non-goals: writing code or specs, reviewing unrelated modules, style nits, re-planning
other waves. Do not agree with the planner by default; verify claims in source.
## 4. Files to inspect
- `docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md` (subject) and `W11-PLAN.md` (its brief).
- Roadmap rows/plans: `docs/roadmap/modules/{Functional,Time,Async}.md`,
`docs/roadmap/subsystems/{IO,Runtime}.md`, `docs/roadmap/{DEPENDENCIES,ARCHITECTURE,MIGRATION}.md`.
- Source cited by the plan: `include/Void/Functional/Retry.hpp`, `include/Void/Time/Clock.hpp`,
`include/Void/Async/{Executor,Operation,TaskScope,ThreadPool,Channel,ParallelFor,EventBus,Observable}.hpp`,
`include/Void/Async/Detail/Types.hpp`, `include/Void/IO/{Types,Driver,Stream}.hpp`,
`include/Void/IO/Detail/Backend.hpp`, `src/IO/EpollDriver.cpp`, `include/Void/Runtime/*.hpp`,
`include/Void/System/SignalWatcher.hpp`, `src/System/SignalWatcher.cpp`,
`include/Void/Resilience/AsyncPolicy.hpp`, `src/SystemAsync/AsyncProcess.cpp`,
`tests/package/InstalledComponents.cmake`, `tests/CMakeLists.txt`, `CMakeLists.txt`, `cmake/Module.cmake`,
`src/Testing/Runner.cpp` (filter semantics), existing tests in `tests/standalone/{Functional,Async,IO,Runtime}/`.
## 5. Write ownership and coordination
Write scope: none
Allowed commands: read-only `git`, `rg`, `ls`, `wc`, `sed -n`, Serena/codebase-memory read tools.
Optional tiny compile probes only under `/tmp/void-w11-preflight-probe` (never in the repo);
`dev cpp-gcc ...` works only unsandboxed. No repository writes, no commits.
## 6. Implementation or investigation approach
1. Verify every baseline claim the plan relies on against source (cite `path:line`).
2. For each NEW interface, check: invariants stated, ownership/lifetime of borrowed objects,
exactly-one-terminal-result, stop/expiry/completion races, callbacks outside locks,
overflow-safe time arithmetic, bounded resources, error mapping into existing domains.
3. Check gate order G1..G5 and the A/B partition for overlapping writes, impossible orders,
or hidden edges the plan missed (e.g. Runtime needing Timer, Host move with live threads,
IO `Types.hpp` edited by both root pre-commit and B2/A4).
4. Check layering against `DEPENDENCIES.md` rules 1–2 and D-015 (Functional std-only),
and installed consumers IOOnly/RuntimeOnly (`-DCMAKE_DISABLE_FIND_PACKAGE_Threads=TRUE`).
5. Check 1.x compatibility: `JitterMode` relocation, `ExponentialBackoff` users in Resilience,
EventBus/Observable behavior changes, legacy `parallel_for` change (D-W11-10).
6. Check that each acceptance sentence of the eight roadmap rows maps to at least one
deterministic test in the plan.
## 7. Interfaces and data contracts
Not applicable for new authorship: you review the plan's proposed interfaces as written in
`W11-PLAN-OUTPUT.md`. Existing contracts: `Void::Functional` error domains (`Error.hpp`),
`Async::OperationOptions`/`AdmissionError`/`TaskScope`, `IO::Driver`/`BufferLease`, `Runtime::Host`.
## 8. Dependencies and integration
Root will convert your verdict into persisted per-package task specs. Blocking findings
(P0/P1) must be resolved before dispatch; P2 need fix or explicit risk acceptance.
## 9. Edge cases security and performance
Pay particular attention to: fd reuse after close during concurrent poll, signal-mask
inheritance and pending-signal default action, thread/fd leak on partial start failure,
`TaskScope` destructor pumping/blocking, `ManualClock` + blocking waits, coroutine resume
on a joined executor, retained buffers after shutdown timeout, unbounded tombstones.
## 10. Acceptance criteria
1. Verdict stated with justification.
2. Every finding has severity, location, trigger, impact, evidence, recommendation.
3. Each D1 defect claim is CONFIRMED or REFUTED with cited lines.
4. Each of D-W11-01..15 has an accept/modify/reject recommendation.
5. Uncovered acceptance sentences (if any) are listed per task.
## 11. Verification commands and evidence
Read-only inspection. Example: `rg -n "release_backend_ref|in_execution" src/IO/EpollDriver.cpp`,
`sed -n 430,460p src/IO/EpollDriver.cpp`, `git log --oneline f1f9ba3..HEAD -- include/Void/Async`.
Report any probe compile command and its exit status if you run one.
## 12. Constraints and stop conditions
No edits, commits or network. Stop and report INSUFFICIENT_EVIDENCE for any claim you cannot
verify rather than guessing. Do not spawn agents.
## 13. Authorization and decisions
Root decision D-034 (Wave 11 scope) under user decisions D-027/D-031. PREFLIGHT is a technical
check; it neither approves scope nor authorizes commits.
## 14. Return format
Return task ID; verdict; findings ranked P0→P3 (severity, location, trigger, impact,
evidence, recommendation); D1 confirm/refute; D-W11-01..15 dispositions; uncovered
acceptance sentences; checks not run. Compact bullets. Do not spawn children.
@@ -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.
+1 -1
View File
@@ -58,7 +58,7 @@ the explicit path when a backward-compatible downgrade is impossible.
| Core/Functional | Error categories, formatting adapters, foundation dependency cleanup | Existing representations and error chains; minimal consumer with optional packages absent |
| Containers/Memory | Allocator-aware variants and changed invalidation/ownership | Move-only values, allocator lifetime, stable-handle/invalidation examples, old default behavior |
| Data/Binary/Text | Exact integers, checked conversions, Unicode/limit policies | Large identifiers round-trip; overflow errors; old strict signed documents remain accepted/rejected identically |
| Async/IO | Borrowed queued handles and detached work toward structured ownership | Cancellation/parked destruction and explicit join; blocking bridge cannot deadlock its own executor |
| Async/IO | Borrowed queued handles and detached work toward structured ownership | Cancellation/parked destruction and explicit join; blocking bridge cannot deadlock its own executor. Recorded W11 changes: `Driver::shutdown_and_join` blocks for in-flight syscalls and joins file workers; `validate_limits` rejects `max_file_queue == 0`; Sync EventBus and Observable/Signal dispatch over snapshots (subscription changes take effect next pass); nested Observable/Signal updates for copyable types are queued FIFO; legacy `parallel_for` waits for all tasks before rethrowing; Async-mode EventBus handler exceptions are counted instead of terminating; legacy `retry` zero-attempt result kept until Wave C; 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 |
+10 -6
View File
@@ -92,18 +92,22 @@ immutable and bounded; destructor traversal must not recurse through unbounded c
## Pure retry and callable ownership
NEW `RetryState::next(now, last_error)` returns either `stop`, `attempt`, or an absolute
next-attempt time. Defaults: three total attempts and a 30-second total budget; explicit
NEW `RetryState` exposes `begin(now)`, `next(now, outcome)` and `resume(now)`: `next`
returns `stop` or `wait_until(absolute time)`; `begin`/`resume` return `attempt` or `stop`.
Callers map their error to `AttemptOutcome` with a supplied classifier. Defaults: three total attempts and a 30-second total budget; explicit
`no_deadline` is required for unlimited time. Zero attempts is invalid. Backoff arithmetic
saturates at a configured cap before overflow, rejects negative durations/nonfinite
multipliers, and accepts an injected URBG for reproducible jitter. A stop request or
multipliers, and accepts an injected URBG for reproducible jitter; the default engine is seeded from
`std::random_device`. A stop request or
expired admission deadline prevents the next attempt; the policy cannot interrupt an
already-running callback or reverse its side effects. Retryability is a supplied
predicate and retrying writes still requires the caller's idempotency contract.
Retain the synchronous `retry` adapter temporarily, explicitly named as blocking. A
Time-clock/sleeper adapter belongs in a separate Time-dependent header; Async supplies
its own awaiting adapter. This prevents foundational retry code from importing execution.
Retain 1.x `retry`/`retry_while` unchanged, including the zero-attempt default-result
defect (recorded for Wave C). NEW `retry_blocking` takes injected `now`/`sleep` callables,
so Functional stays standard-library-only and no Time-dependent retry header exists.
Async supplies `Async::retry_async` over `TimerQueue`. This prevents foundational retry
code from importing execution (W11 decision D-038).
Memoization becomes per-instance with an explicit key/result signature, default 1,024
entries and FIFO eviction. Recursive calls mark an entry as computing; a repeated key
+16 -7
View File
@@ -74,9 +74,11 @@ semantics avoid requiring every dispatch to drain a descriptor completely; the f
budget can yield while data remains ready. This follows the
[Linux epoll interface](https://man7.org/linux/man-pages/man7/epoll.7.html).
One driver thread owns interest updates and descriptor generations. Producers submit
bounded control messages and wake it through eventfd; an embedder may drive bounded
`poll_once` turns instead. Dispatch up to 64 ready descriptors and 64 KiB/direction per
The Driver owns no thread. One thread at a time runs a `poll_once` turn (the poll owner)
and owns interest updates and generations; a concurrent caller gets `busy` without
touching descriptors. Producers submit bounded control messages and wake the owner
through eventfd. Runtime or the embedder supplies the thread (`Driver::run`,
`pump_until`). Dispatch up to 64 ready descriptors and 64 KiB/direction per
descriptor per turn before yielding. Enable writable interest only with pending writes
to avoid idle busy loops. HUP/ERR still trigger final read/error inspection. Async
completion tickets transfer continuations to the supplied executor outside driver locks.
@@ -89,7 +91,10 @@ integer directly. Socket connect completion checks the socket error state; accep
obey the same fairness/admission budget. Platform-specific endpoint conversion remains
an IO/Net adapter detail until the Net endpoint contract is integrated.
Files initially use a bounded native blocking worker pool. Positional pread/pwrite
Files initially use a bounded native blocking worker pool, started explicitly by
`start_file_workers()` or stepped by `run_file_work()`. Workers run only the syscall (or
an injected syscall shim, the single documented exception) and queue its result;
completions are delivered only by a poll turn. Positional pread/pwrite
avoids shared offset races; default writes/syncs for one file are serialized in admission
order, and reads expose explicit offsets. Worker ownership retains descriptor and buffer
until the syscall returns. Cancelled queued work is removed before execution; an active
@@ -116,8 +121,12 @@ Only terminal delivery is arbitrated once; no callback is delivered merely becau
arrived while backend access or outcome classification was still pending.
Driver shutdown closes admission, cancels queued requests, asks active requests to
stop, drains readiness/control/completion lanes, joins file workers, then releases
descriptors/wake resources. It must keep the executor alive until all completion tickets
stop, waits for the poll owner and in-flight syscalls, drains readiness/control/completion
lanes, joins file workers, then closes operation descriptors. Epoll and wake descriptors
close in the backend destructor. Blocking teardown runs in `Driver::~Driver`; destruction
on a file worker or inside a poll turn is a programmer error. `File::close_and_join`
returns `incomplete_shutdown` on expiry and retains the fd and buffers; a dropped File
closes its fd after its last in-flight request drains. It must keep the executor alive until all completion tickets
drain. `close_and_join` cannot free buffers when its own deadline expires; return an
incomplete-shutdown report through the owning driver and retain work. Blocking joins
are off-driver/off-worker operations; embedded drivers pump until their scopes join.
@@ -151,7 +160,7 @@ are not owned by this document.
| S-IO-01 | P1 / Async operation ownership and Time clock gates | Portable transfer/error/driver API, buffer leases, descriptor and quota ownership | Mock backend completes/stops in every ordering with exactly one result and no borrowed-buffer escape / astra_implementer |
| S-IO-02 | P1 / S-IO-01 | Level-triggered epoll driver, wake/control path, generation-safe close and stream operations | Fragmentation/EAGAIN/EINTR/HUP/fd reuse and full queues do not lose completion or busy-spin / astra_implementer |
| S-IO-03 | P2 / S-IO-01 | Bounded positional file workers, serialization, sync and active-cancel handling | Short writes preserve progress; active timeout retains buffers; sync success/failure after stop remains authoritative in the sole result / astra_implementer |
| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, optional System/Net adapters | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer |
| S-IO-04 | P2 / S-IO-02, S-IO-03 | Embedded pumping, joined shutdown, SystemAsync conformance (Net adapter deferred: Net has no IO use) | Shutdown during pending socket/file work retains resources; no IO→Runtime/Net dependency / sol_implementer |
| S-IO-05 | P3 / S-IO-04; performance harness | Optional io_uring capability/backend gate and portability conformance specification | Same tests pass; denied/unsupported capability falls back only before submission; profile evidence justifies enablement / astra_implementer |
## Validation, measurements and migration
+24 -14
View File
@@ -45,10 +45,14 @@ struct Options {
class Host { // owns managed resources
public:
static Result<Host> create(Options); // validates, starts no workers
Result<void> start(); // explicit startup transaction
Async::Executor& executor();
IO::Driver& io();
Coro::Task<Result<ShutdownReport>> shutdown(Async::OperationOptions);
Result<void> start(StartOptions); // explicit startup transaction
Async::Executor* executor();
IO::Driver* io();
Result<ShutdownReport> shutdown_blocking(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.
}
@@ -70,11 +74,13 @@ constructors remain inert; start is explicit and errors return before publicatio
Use a lifecycle graph of explicit resources, with required/optional dependencies and
deterministic topological ordering. Default core order: validate limits/capabilities →
establish signal handling on the designated owner thread → allocate budgets and queues →
install the injected `SignalGate` on the designated owner thread (Runtime has no System
dependency; a System-backed adapter is optional) → allocate budgets and queues →
start CPU executor → start IO driver/file workers → start optional service/admission
adapters → report ready. SignalWatcher is created before worker threads as required by
[its contract](../../../include/Void/System/SignalWatcher.hpp), and is destroyed on
the same creating thread after workers join.
the same creating thread after workers join; off-owner teardown calls `uninstall(false)`,
which closes the gate's descriptor but cannot restore the owner's mask.
Each start step returns a retained cleanup action. A failed step aborts its partial
resources and unwinds previously successful starts in reverse dependency order.
@@ -111,19 +117,23 @@ idempotent; callers join one retained result rather than issue competing stop pa
data and requests cooperative cancellation, but all admitted backend activity must
still quiesce. Expiry of the total shutdown budget returns shutdown_incomplete with
exporter owners and their execution resources retained; a later join continues them.
6. Only after cleanup/export callbacks and backend references retire, stop reactor and
CPU/file workers and release budgets/descriptors/signal masks in reverse creation
order. Observation failure cannot suppress cleanup or convert a failed operation
6. After cleanup/export callbacks and backend references retire, drop component/exporter
references, then stop owned IO, the reactor and CPU/file workers, and release budgets,
descriptors and the signal gate in reverse creation order. Borrowed executor, driver,
clock and memory are never shut down or joined by the Host. Observation failure cannot suppress cleanup or convert a failed operation
into success. A timed-out flush is not evidence that its resources are releasable.
Default total shutdown observation budget is 30 seconds, shortened by caller options.
Each shutdown call observes min(caller deadline, now + total_timeout) for remaining work;
drain-grace and flush deadlines are fixed at first entry to their phase. An incomplete
phase stops the sequence and the next call resumes there.
Expiry produces `shutdown_incomplete` containing pending owner IDs/counts and phase;
the Host remains in joining with resources retained. It can be waited again or the
application can choose explicit process termination. There is no forced thread kill,
buffer release or dlclose. Borrowed resources must outlive final cleanup, not merely
the first timed-out shutdown call. Destruction blocks to join only on an allowed
off-worker owner thread; on a runtime worker, callers must await shutdown before
destroying Host. Self-join misuse is detected as a programmer error. Process-level
the first timed-out shutdown call. Destruction blocks to join only off Runtime threads;
destruction on a Runtime worker, reactor or IO file-worker thread is a programmer error
that terminates after a diagnostic. Process-level
hard-stop policy belongs to the application, not a hidden destructor timeout.
Uncaught task exceptions reach explicit scope/error sinks. Default failure policy
@@ -156,8 +166,8 @@ Every row is PLANNED.
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
| --- | --- | --- | --- |
| S-RUNTIME-01 | P1 / Async ownership, IO driver, Time/Memory ports | Inert Host options, borrowed/owned resource graph, dependency validation | No constructor starts workers; invalid bounds/cycles fail before external admission / sol_implementer |
| S-RUNTIME-02 | P2 / S-RUNTIME-01; System signal gate | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer |
| S-RUNTIME-03 | P2 / S-RUNTIME-02 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer |
| S-RUNTIME-02 | P2 / S-RUNTIME-01, M-ASYNC-04, S-IO-03; signal gate (injected port) | Explicit start, readiness and reverse failed-start cleanup | Failure at every creation/start step leaves no worker/descriptors; signal-mask ownership retained / astra_implementer |
| S-RUNTIME-03 | P2 / S-RUNTIME-02, S-IO-04 | Structured shutdown, repeated join, exporter-before-executor ordering and budget accounting | Full queues deliver completion; in-flight export retains IO/workers through flush expiry; stalled work reports incomplete without freeing resources / astra_implementer |
| S-RUNTIME-04 | P3 / S-RUNTIME-03; Service/Configuration transaction gates | Optional managed adapters, transactional resize/reload and embedded examples | Same workload runs embedded/managed; failed resource prepare keeps active generation / sol_implementer |
| S-RUNTIME-05 | P3 / S-RUNTIME-04; profile harness | Latency/throughput/footprint presets, inspection and tuning gates | Limits remain invariant per preset; measured p99/RSS/build cost reported with environment / astra_implementer |
+768
View File
@@ -0,0 +1,768 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <expected>
#include <list>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <type_traits>
#include <utility>
// ── AsyncChannel ──────────────────────────────────────────────────────────────
// A bounded multi-producer / multi-consumer channel with coroutine `send` /
// `receive`, cooperative cancellation and optional injected-clock deadlines
// (C-03/C-04). Blocking waits do not exist: a waiter suspends its coroutine
// and is always resumed through `resume.post_completion(...)` (never while the
// channel lock is held; an executor that has been joined resumes the handle
// inline on the calling thread, as ThreadExecutor does after join()).
//
// Arbitration (one `std::mutex` covers the buffer and both waiter lists)
// A waiter is a heap node (`shared_ptr`) with the state
// {fresh, linked, claimed, cancelled, timed_out, closed, overloaded}.
// `fresh` is the pre-link state (callbacks that settle a fresh waiter make
// the awaiting coroutine skip suspension); `overloaded` is the internal
// result of a refused wait. Pairing a sender with a receiver happens in ONE
// critical section: the waiter is unlinked and claimed and the value is
// moved, so a value is always in exactly one place: the sender's node, the
// buffer, or the receiver's slot. Stop callbacks and timer callbacks take the
// same lock: a still-`linked` waiter is unlinked and settled
// `cancelled`/`timed_out` (a sender keeps its value and gets it back), a
// `claimed` waiter is left alone (a sender succeeded, a receiver already
// holds its value). Each operation is settled exactly once.
//
// Ordering and capacity
// FIFO means per-producer order (items of one producer are received in the
// order they were sent; items of different producers interleave). Waiting
// senders and waiting receivers are served in arrival order. `capacity` and
// `max_waiters` (per direction) must be > 0 (`create` -> invalid_argument).
// A wait that would exceed `max_waiters` returns `overloaded` (a send gets
// its value back).
//
// Close
// `close()` is idempotent and noexcept. Waiting senders complete `closed`
// and get their value back; waiting receivers complete `closed`. Items
// already buffered stay receivable: receivers drain the buffer in FIFO order
// and then get `closed`. `send`/`try_send` on a closed channel return
// `closed` with the value.
//
// Options checks (send/receive with OperationOptions), in this order and
// BEFORE any state change (a send returns its value in `SendFailure`):
// 1. stop already requested -> cancelled
// 2. a deadline is set: it is judged by
// `timers->clock()`; already reached -> timed_out
// no `timers` configured -> invalid_argument
// 3. the fast path (value moved / received)
// 4. a deadline timer is armed (schedule_at failure: overloaded ->
// overloaded, stopped -> cancelled; the value is returned)
// 5. the waiter is linked and the coroutine suspends.
// `TimerEvent::closed` (queue closed or destroyed) settles the wait
// `cancelled`. The system clock is never consulted.
//
// Lifetime and caller errors
// * `send`/`receive` return lazy Tasks; their frames hold
// `shared_from_this()`, so the channel outlives every pending operation.
// * Destroying a Task that is suspended inside a channel operation is a
// caller error (the waiter would be resumed into a destroyed frame).
// * The resume executor and the TimerQueue must outlive the channel and every
// pending operation.
// * Timer callbacks hold only weak references (channel + waiter); a stop or
// timer callback that races with completion finds a settled waiter and
// does nothing. No raw pointer into a coroutine frame is ever captured.
// * A `std::stop_callback` is never constructed or destroyed while the
// channel lock is held, and a timer is never cancelled under the lock.
// * Exceptions: if `T`'s move constructor throws, the exception propagates
// from the operation; the channel's structural invariants (lists, bound)
// are preserved, but the value being moved is then unspecified (strong
// guarantee only for T with a non-throwing move constructor).
namespace Void::Async
{
enum class ChannelError : std::uint8_t {
closed,
empty,
full,
cancelled,
timed_out,
overloaded,
invalid_argument
};
// closed -> AsyncErrorCode::closed, cancelled -> cancelled, timed_out ->
// timeout, overloaded/full -> overloaded, empty/invalid_argument ->
// invalid_argument.
[[nodiscard]] inline Void::Result::Error
make_async_error(ChannelError error, std::string message = {})
{
AsyncErrorCode code = AsyncErrorCode::invalid_argument;
const char* text = "Invalid async channel argument";
switch (error) {
case ChannelError::closed:
code = AsyncErrorCode::closed;
text = "Async channel is closed";
break;
case ChannelError::empty:
code = AsyncErrorCode::invalid_argument;
text = "Async channel is empty";
break;
case ChannelError::full:
code = AsyncErrorCode::overloaded;
text = "Async channel is full";
break;
case ChannelError::cancelled:
code = AsyncErrorCode::cancelled;
text = "Async channel operation cancelled";
break;
case ChannelError::timed_out:
code = AsyncErrorCode::timeout;
text = "Async channel operation deadline expired";
break;
case ChannelError::overloaded:
code = AsyncErrorCode::overloaded;
text = "Async channel waiter capacity exceeded";
break;
case ChannelError::invalid_argument:
code = AsyncErrorCode::invalid_argument;
text = "Invalid async channel argument";
break;
}
if (message.empty()) {
message = text;
}
return make_async_error(code, std::move(message));
}
struct ChannelOptions {
std::size_t capacity{1024};
std::size_t max_waiters{1024};
// Required only for waits with a deadline; must outlive the channel.
TimerQueue* timers{nullptr};
};
template <class T>
struct SendFailure {
ChannelError error;
T value;
};
namespace detail
{
enum class ChannelWaiterState : std::uint8_t {
fresh,
linked,
claimed,
cancelled,
timed_out,
closed,
overloaded
};
// Heap-allocated so stop/timer callbacks can reference it through shared or
// weak ownership instead of a pointer into a coroutine frame. All members
// except `sender` are protected by the owning channel's mutex (the waiter's
// owner may read `value` without the lock only after the state is terminal).
template <class T>
struct ChannelWaiter {
explicit ChannelWaiter(bool is_sender) noexcept : sender(is_sender) {}
const bool sender;
ChannelWaiterState state{ChannelWaiterState::fresh};
// Sender: the value to deliver. Receiver: the delivered value.
std::optional<T> value{};
std::coroutine_handle<> handle{};
TimerHandle timer{};
typename std::list<std::shared_ptr<ChannelWaiter>>::iterator position{};
};
} // namespace detail
template <class T>
class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>>
{
static_assert(std::is_object_v<T> && std::is_move_constructible_v<T>,
"AsyncChannel<T> requires a move-constructible object type");
using Waiter = detail::ChannelWaiter<T>;
using WaiterPtr = std::shared_ptr<Waiter>;
using WaiterList = std::list<WaiterPtr>;
using WaiterState = detail::ChannelWaiterState;
using SendResult = std::expected<void, SendFailure<T>>;
using ReceiveResult = std::expected<T, ChannelError>;
public:
// Errors: invalid_argument when capacity == 0 or max_waiters == 0.
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>>
create(Executor& resume, ChannelOptions options = {})
{
if (options.capacity == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"AsyncChannel capacity must be greater than zero")};
}
if (options.max_waiters == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"AsyncChannel max_waiters must be greater than zero")};
}
return std::shared_ptr<AsyncChannel>(new AsyncChannel(resume, options));
}
AsyncChannel(const AsyncChannel&) = delete;
AsyncChannel& operator=(const AsyncChannel&) = delete;
AsyncChannel(AsyncChannel&&) = delete;
AsyncChannel& operator=(AsyncChannel&&) = delete;
~AsyncChannel() = default;
// Non-blocking send. Errors (the value is returned): closed, full.
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T value)
{
WaiterPtr woken;
SendAttempt attempt{};
{
std::lock_guard lk{mu_};
attempt = try_send_locked(value, woken);
}
resume_waiter(woken);
switch (attempt) {
case SendAttempt::sent:
return {};
case SendAttempt::closed:
return std::unexpected{SendFailure<T>{ChannelError::closed, std::move(value)}};
case SendAttempt::full:
break;
}
return std::unexpected{SendFailure<T>{ChannelError::full, std::move(value)}};
}
// Suspends until the value is delivered (to a waiting receiver or the
// buffer). Results: success; or SendFailure with the value returned:
// closed, cancelled, timed_out, overloaded, invalid_argument (see the
// header comment for the check order).
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>>
send(T value, OperationOptions options = {})
{
return send_impl(this->shared_from_this(), std::move(value), std::move(options));
}
// Non-blocking receive. Errors: empty, closed (closed AND drained).
[[nodiscard]] std::expected<T, ChannelError> try_receive()
{
std::optional<T> out;
WaiterPtr woken;
ReceiveAttempt attempt{};
{
std::lock_guard lk{mu_};
attempt = try_receive_locked(out, woken);
}
resume_waiter(woken);
switch (attempt) {
case ReceiveAttempt::received:
return std::move(*out);
case ReceiveAttempt::closed:
return std::unexpected{ChannelError::closed};
case ReceiveAttempt::empty:
break;
}
return std::unexpected{ChannelError::empty};
}
// Suspends until a value arrives. Errors: closed (closed AND drained),
// cancelled, timed_out, overloaded, invalid_argument.
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>>
receive(OperationOptions options = {})
{
return receive_impl(this->shared_from_this(), std::move(options));
}
// Idempotent. See the header comment.
void close() noexcept
{
WaiterList senders;
WaiterList receivers;
{
std::lock_guard lk{mu_};
if (closed_) {
return;
}
closed_ = true;
senders.splice(senders.end(), senders_);
receivers.splice(receivers.end(), receivers_);
for (auto& waiter : senders) {
waiter->state = WaiterState::closed;
}
for (auto& waiter : receivers) {
waiter->state = WaiterState::closed;
}
}
for (auto& waiter : senders) {
resume_waiter(waiter);
}
for (auto& waiter : receivers) {
resume_waiter(waiter);
}
}
// Number of buffered items.
[[nodiscard]] std::size_t size() const
{
std::lock_guard lk{mu_};
return buffer_.size();
}
[[nodiscard]] bool is_closed() const
{
std::lock_guard lk{mu_};
return closed_;
}
private:
enum class SendAttempt : std::uint8_t { sent, closed, full };
enum class ReceiveAttempt : std::uint8_t { received, closed, empty };
AsyncChannel(Executor& resume, const ChannelOptions& options)
: resume_(resume)
, capacity_(options.capacity)
, max_waiters_(options.max_waiters)
, timers_(options.timers)
{
}
// ── locked primitives (mu_ held) ──────────────────────────────────────
// Moves from `value` only on success. A waiting receiver implies an empty
// buffer, so a direct hand-off preserves FIFO order.
[[nodiscard]] SendAttempt try_send_locked(T& value, WaiterPtr& woken)
{
if (closed_) {
return SendAttempt::closed;
}
if (!receivers_.empty()) {
WaiterPtr receiver = receivers_.front();
receiver->value.emplace(std::move(value));
receivers_.pop_front();
receiver->state = WaiterState::claimed;
woken = std::move(receiver);
return SendAttempt::sent;
}
if (buffer_.size() < capacity_) {
buffer_.push_back(std::move(value));
return SendAttempt::sent;
}
return SendAttempt::full;
}
// A waiting sender implies a full buffer: the freed slot is refilled from
// the first waiting sender, which is claimed (it succeeded).
[[nodiscard]] ReceiveAttempt try_receive_locked(std::optional<T>& out, WaiterPtr& woken)
{
if (!buffer_.empty()) {
out.emplace(std::move(buffer_.front()));
buffer_.pop_front();
if (!senders_.empty()) {
WaiterPtr sender = senders_.front();
try {
buffer_.push_back(std::move(*sender->value));
} catch (...) {
// Best effort: put the received value back so it is not lost.
try {
buffer_.push_front(std::move(*out));
} catch (...) {
}
throw;
}
senders_.pop_front();
sender->state = WaiterState::claimed;
woken = std::move(sender);
}
return ReceiveAttempt::received;
}
if (closed_) {
return ReceiveAttempt::closed;
}
return ReceiveAttempt::empty;
}
void link_locked(WaiterList& list, const WaiterPtr& waiter)
{
waiter->position = list.insert(list.end(), waiter);
waiter->state = WaiterState::linked;
}
// ── settlement (no lock held) ─────────────────────────────────────────
// Cancels the waiter's deadline timer and resumes its coroutine through
// the completion lane. The waiter must already be in a terminal state.
void resume_waiter(WaiterPtr& waiter)
{
if (!waiter) {
return;
}
(void)waiter->timer.cancel();
resume_.post_completion(waiter->handle);
waiter.reset();
}
// Stop/timer callback entry point. A `fresh` waiter is only marked (the
// awaiting coroutine will not suspend); a `linked` waiter is unlinked and
// resumed; anything else was already settled and is left alone.
void settle_pending(const WaiterPtr& waiter, WaiterState to) noexcept
{
{
std::lock_guard lk{mu_};
if (waiter->state == WaiterState::fresh) {
waiter->state = to;
return;
}
if (waiter->state != WaiterState::linked) {
return;
}
(waiter->sender ? senders_ : receivers_).erase(waiter->position);
waiter->state = to;
}
WaiterPtr settled = waiter;
resume_waiter(settled);
}
// ── option handling ───────────────────────────────────────────────────
[[nodiscard]] std::optional<ChannelError> precheck(const OperationOptions& options) const
{
if (options.stop.stop_requested()) {
return ChannelError::cancelled;
}
if (options.deadline.has_value()) {
if (timers_ == nullptr) {
return ChannelError::invalid_argument;
}
if (timers_->clock().now() >= *options.deadline) {
return ChannelError::timed_out;
}
}
return std::nullopt;
}
// Arms the deadline timer while the waiter is still `fresh` (so a failure
// leaves no state behind and a timer that fires early settles the fresh
// waiter without a ticket). The callback holds only weak references.
[[nodiscard]] std::optional<ChannelError>
arm_deadline(const WaiterPtr& waiter, Void::Time::MonotonicClock::time_point deadline)
{
auto scheduled = timers_->schedule_at(
deadline,
TimerCallback{[channel = this->weak_from_this(),
target = std::weak_ptr<Waiter>{waiter}](TimerEvent event) noexcept {
const auto chan = channel.lock();
const auto settled = target.lock();
if (chan && settled) {
chan->settle_pending(
settled,
event == TimerEvent::expired ? WaiterState::timed_out
: WaiterState::cancelled);
}
}});
if (!scheduled.has_value()) {
switch (scheduled.error()) {
case AdmissionError::overloaded:
return ChannelError::overloaded;
case AdmissionError::stopped:
return ChannelError::cancelled;
case AdmissionError::deadline_expired:
return ChannelError::timed_out;
case AdmissionError::invalid_argument:
case AdmissionError::self_join:
return ChannelError::invalid_argument;
}
return ChannelError::invalid_argument;
}
bool settled_meanwhile = false;
{
std::lock_guard lk{mu_};
if (waiter->state == WaiterState::fresh) {
waiter->timer = std::move(*scheduled);
} else {
settled_meanwhile = true;
}
}
if (settled_meanwhile) {
(void)scheduled->cancel();
}
return std::nullopt;
}
struct StopFn {
std::weak_ptr<AsyncChannel> channel;
WaiterPtr waiter;
void operator()() const noexcept
{
// Copy first: once the waiter is settled the resumed frame may
// destroy the stop_callback that owns this object.
const auto chan = channel.lock();
const WaiterPtr target = waiter;
if (chan) {
chan->settle_pending(target, WaiterState::cancelled);
}
}
};
// ── awaiters ──────────────────────────────────────────────────────────
// Links the waiter (re-running the fast path under the same lock so no
// wake-up can be lost) and suspends. Once the waiter is visible to other
// threads the frame may be resumed and destroyed concurrently, so
// everything after the unlock touches locals only.
struct SendAwaiter {
std::shared_ptr<AsyncChannel> channel;
WaiterPtr waiter;
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
{
std::shared_ptr<AsyncChannel> chan = channel;
WaiterPtr self = waiter;
WaiterPtr woken;
bool suspended = false;
try {
std::lock_guard lk{chan->mu_};
if (self->state == WaiterState::fresh) {
switch (chan->try_send_locked(*self->value, woken)) {
case SendAttempt::sent:
self->state = WaiterState::claimed;
break;
case SendAttempt::closed:
self->state = WaiterState::closed;
break;
case SendAttempt::full:
if (chan->senders_.size() >= chan->max_waiters_) {
self->state = WaiterState::overloaded;
} else {
self->handle = handle;
chan->link_locked(chan->senders_, self);
suspended = true;
}
break;
}
}
} catch (...) {
(void)self->timer.cancel();
throw;
}
if (suspended) {
return true;
}
(void)self->timer.cancel();
chan->resume_waiter(woken);
return false;
}
[[nodiscard]] SendResult await_resume()
{
WaiterState state{};
{
std::lock_guard lk{channel->mu_};
state = waiter->state;
}
switch (state) {
case WaiterState::claimed:
return {};
case WaiterState::closed:
return fail(ChannelError::closed);
case WaiterState::timed_out:
return fail(ChannelError::timed_out);
case WaiterState::overloaded:
return fail(ChannelError::overloaded);
case WaiterState::cancelled:
case WaiterState::fresh:
case WaiterState::linked:
break;
}
return fail(ChannelError::cancelled);
}
private:
[[nodiscard]] SendResult fail(ChannelError error)
{
return std::unexpected{SendFailure<T>{error, std::move(*waiter->value)}};
}
};
struct ReceiveAwaiter {
std::shared_ptr<AsyncChannel> channel;
WaiterPtr waiter;
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
{
std::shared_ptr<AsyncChannel> chan = channel;
WaiterPtr self = waiter;
WaiterPtr woken;
bool suspended = false;
try {
std::lock_guard lk{chan->mu_};
if (self->state == WaiterState::fresh) {
switch (chan->try_receive_locked(self->value, woken)) {
case ReceiveAttempt::received:
self->state = WaiterState::claimed;
break;
case ReceiveAttempt::closed:
self->state = WaiterState::closed;
break;
case ReceiveAttempt::empty:
if (chan->receivers_.size() >= chan->max_waiters_) {
self->state = WaiterState::overloaded;
} else {
self->handle = handle;
chan->link_locked(chan->receivers_, self);
suspended = true;
}
break;
}
}
} catch (...) {
(void)self->timer.cancel();
throw;
}
if (suspended) {
return true;
}
(void)self->timer.cancel();
chan->resume_waiter(woken);
return false;
}
[[nodiscard]] ReceiveResult await_resume()
{
WaiterState state{};
{
std::lock_guard lk{channel->mu_};
state = waiter->state;
}
switch (state) {
case WaiterState::claimed:
return std::move(*waiter->value);
case WaiterState::closed:
return std::unexpected{ChannelError::closed};
case WaiterState::timed_out:
return std::unexpected{ChannelError::timed_out};
case WaiterState::overloaded:
return std::unexpected{ChannelError::overloaded};
case WaiterState::cancelled:
case WaiterState::fresh:
case WaiterState::linked:
break;
}
return std::unexpected{ChannelError::cancelled};
}
};
// ── operations (free-standing coroutines holding the channel) ─────────
static Coro::Task<SendResult>
send_impl(std::shared_ptr<AsyncChannel> self, T value, OperationOptions options)
{
if (const auto refused = self->precheck(options); refused.has_value()) {
co_return std::unexpected{SendFailure<T>{*refused, std::move(value)}};
}
{
WaiterPtr woken;
SendAttempt attempt{};
{
std::lock_guard lk{self->mu_};
attempt = self->try_send_locked(value, woken);
}
self->resume_waiter(woken);
if (attempt == SendAttempt::sent) {
co_return SendResult{};
}
if (attempt == SendAttempt::closed) {
co_return std::unexpected{SendFailure<T>{ChannelError::closed, std::move(value)}};
}
}
auto waiter = std::make_shared<Waiter>(true);
waiter->value.emplace(std::move(value));
std::optional<std::stop_callback<StopFn>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter});
}
if (options.deadline.has_value()) {
if (const auto failure = self->arm_deadline(waiter, *options.deadline);
failure.has_value()) {
co_return std::unexpected{SendFailure<T>{*failure, std::move(*waiter->value)}};
}
}
SendResult result = co_await SendAwaiter{self, waiter};
// Waits for a stop callback that is mid-settle (no lock is held here).
stop_cb.reset();
co_return result;
}
static Coro::Task<ReceiveResult>
receive_impl(std::shared_ptr<AsyncChannel> self, OperationOptions options)
{
if (const auto refused = self->precheck(options); refused.has_value()) {
co_return std::unexpected{*refused};
}
{
std::optional<T> out;
WaiterPtr woken;
ReceiveAttempt attempt{};
{
std::lock_guard lk{self->mu_};
attempt = self->try_receive_locked(out, woken);
}
self->resume_waiter(woken);
if (attempt == ReceiveAttempt::received) {
co_return ReceiveResult{std::move(*out)};
}
if (attempt == ReceiveAttempt::closed) {
co_return std::unexpected{ChannelError::closed};
}
}
auto waiter = std::make_shared<Waiter>(false);
std::optional<std::stop_callback<StopFn>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter});
}
if (options.deadline.has_value()) {
if (const auto failure = self->arm_deadline(waiter, *options.deadline);
failure.has_value()) {
co_return std::unexpected{*failure};
}
}
ReceiveResult result = co_await ReceiveAwaiter{self, waiter};
stop_cb.reset();
co_return result;
}
Executor& resume_;
const std::size_t capacity_;
const std::size_t max_waiters_;
TimerQueue* const timers_;
mutable std::mutex mu_{};
std::deque<T> buffer_{};
WaiterList senders_{};
WaiterList receivers_{};
bool closed_{false};
};
} // namespace Void::Async
+3 -1
View File
@@ -29,7 +29,8 @@ enum class AsyncErrorCode : std::int32_t {
invalid_argument = 5,
self_join = 6,
backend_error = 7,
limit_exceeded = 8
limit_exceeded = 8,
closed = 9
};
enum class DomainOutcomeKind {
@@ -68,6 +69,7 @@ struct OperationOptions {
break;
case AsyncErrorCode::cancelled:
case AsyncErrorCode::stopped:
case AsyncErrorCode::closed:
kind = ErrorKind::cancelled;
break;
case AsyncErrorCode::timeout:
File diff suppressed because it is too large. Load diff
+17 -5
View File
@@ -276,29 +276,41 @@ struct ScheduleAwaiter {
// coroutine owns the task; its frame self-destroys on completion. An
// exception escaping the task terminates (there is no awaiter to receive
// it) — handle errors inside the task.
//
// The wrapper starts suspended and is posted only after its ramp function has
// returned. An eagerly started wrapper that posted itself from its first
// co_await could be resumed and destroyed by an executor worker while the
// spawning thread was still inside the ramp (data race reported by TSan when
// spawning from a non-worker thread onto a multi-worker executor; W11).
namespace Detail
{
struct DetachedTask {
struct promise_type {
DetachedTask get_return_object() noexcept { return {}; }
std::suspend_never initial_suspend() noexcept { return {}; }
DetachedTask get_return_object() noexcept
{
return DetachedTask{
std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() noexcept {}
void unhandled_exception() noexcept { std::terminate(); }
};
std::coroutine_handle<promise_type> handle{};
};
inline DetachedTask spawn_impl(Executor& executor, Coro::Task<void> task)
inline DetachedTask spawn_impl(Coro::Task<void> task)
{
co_await schedule_on(executor);
co_await std::move(task);
}
} // namespace Detail
inline void spawn(Executor& executor, Coro::Task<void> task)
{
Detail::spawn_impl(executor, std::move(task));
Detail::DetachedTask detached = Detail::spawn_impl(std::move(task));
executor.post(detached.handle);
}
struct ScheduleStatusAwaiter {
+131
View File
@@ -0,0 +1,131 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <concepts>
#include <coroutine>
#include <exception>
#include <expected>
#include <future>
#include <type_traits>
#include <utility>
// ── FuturePool ────────────────────────────────────────────────────────────────
// `std::future` adapter over a started `ThreadExecutor`.
//
// try_submit(f) is reserve-then-transfer:
// 1. one slot of the executor bound is reserved (`overloaded` / `stopped`
// are returned WITHOUT touching `f`: a rejected callable is never moved);
// 2. only after the reservation succeeded is `f` moved into a
// `std::packaged_task` owned by a self-destroying coroutine frame;
// 3. the frame is committed to the executor's normal lane.
// The reservation is released if any step throws (the exception propagates).
// Exceptions thrown by `f` are stored in the returned future. The executor
// bound counts queued, running and reserved work, so a running submission
// keeps its slot until `f` has returned.
//
// The executor must outlive the pool and must be started (or joined by the
// owner afterwards): a submission is resumed by a worker, or inline once the
// executor has been joined.
namespace Void::Async
{
namespace detail
{
// Fire-and-forget coroutine frame: created suspended, destroyed after it ran.
struct FutureJob {
struct promise_type {
FutureJob get_return_object() noexcept
{
return FutureJob{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() noexcept {}
// packaged_task stores the callable's exception in the future, so
// nothing escapes the frame.
void unhandled_exception() noexcept { std::terminate(); }
};
std::coroutine_handle<promise_type> handle{};
};
template <class R>
FutureJob run_future_job(std::packaged_task<R()> task)
{
task();
co_return;
}
// Releases a reservation unless dismissed.
class ReservationGuard
{
public:
explicit ReservationGuard(ThreadExecutor& executor) noexcept
: executor_(&executor)
{
}
ReservationGuard(const ReservationGuard&) = delete;
ReservationGuard& operator=(const ReservationGuard&) = delete;
~ReservationGuard()
{
if (executor_ != nullptr) {
executor_->release_reserved();
}
}
void dismiss() noexcept { executor_ = nullptr; }
private:
ThreadExecutor* executor_;
};
} // namespace detail
class FuturePool
{
public:
explicit FuturePool(ThreadExecutor& executor) noexcept
: executor_(&executor)
{
}
// Errors: overloaded (admitted() >= max_admitted), stopped (executor
// closed). On an error `f` is untouched. Throws only on allocation
// failure (the reservation is released first).
template <std::invocable F>
[[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
try_submit(F&& f)
{
using R = std::invoke_result_t<F>;
if (auto reserved = executor_->try_reserve_slot(); !reserved.has_value()) {
return std::unexpected{reserved.error()};
}
detail::ReservationGuard guard{*executor_};
std::packaged_task<R()> task{std::forward<F>(f)};
std::future<R> future = task.get_future();
detail::FutureJob job = detail::run_future_job<R>(std::move(task));
try {
executor_->commit_reserved(job.handle);
} catch (...) {
// The reservation is still held (guard releases it); the frame was
// never queued.
job.handle.destroy();
throw;
}
guard.dismiss();
return future;
}
private:
ThreadExecutor* executor_;
};
} // namespace Void::Async
+221 -52
View File
@@ -1,45 +1,92 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Functional/Result.hpp>
#include <algorithm>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Observable
{
// ── Handle — opaque subscription identifier ───────────────────────────────────
inline constexpr std::size_t kMaxPendingNotifications = 1024;
struct Handle
{
struct Handle {
std::uint64_t id{0};
[[nodiscard]] bool valid() const noexcept { return id != 0; }
[[nodiscard]] bool operator==(const Handle&) const noexcept = default;
};
// ── Observable<T> ─────────────────────────────────────────────────────────────
// A value that observers can subscribe to via on_change().
// Observers receive (old_value, new_value) on every set() call that changes
// the stored value.
namespace detail
{
struct EmptyQueue {};
} // namespace detail
/// Observable value container holding a T and notifying listeners on change.
/// Single-threaded (not thread-safe across threads), reentrancy-safe:
/// - Copyable T: nested set() updates the value immediately and queues (old, new)
/// notifications FIFO after the active pass (bounded at kMaxPendingNotifications).
/// - Move-only T: 1.x immediate recursive notification over a listener snapshot.
template <typename T>
class Observable
{
public:
using Listener = std::function<void(const T& old_val, const T& new_val)>;
explicit Observable(T initial = {}) : value_{std::move(initial)} {}
explicit Observable(T initial = {})
: value_{std::move(initial)}
{
}
[[nodiscard]] const T& get() const noexcept { return value_; }
[[nodiscard]] operator const T&() const noexcept { return value_; }
void set(T new_val)
{
if (new_val == value_) return;
if (new_val == value_) {
return;
}
T old = std::move(value_);
value_ = std::move(new_val);
notify(old, value_);
if constexpr (std::copy_constructible<T>) {
if (dispatch_depth_ > 0) {
if (pending_.size() < kMaxPendingNotifications) {
pending_.emplace_back(std::move(old), value_);
} else {
++dropped_notifications_;
}
return;
}
dispatch_fifo(std::move(old), value_);
} else {
notify_snapshot(old, value_);
}
}
/// Bounded reentrant update for copyable T: returns overloaded without
/// modifying value_ if the nested notification queue is full.
[[nodiscard]] Void::Result::Result<void> try_set(T new_val)
requires std::copy_constructible<T>
{
if (new_val == value_) {
return {};
}
if (dispatch_depth_ > 0 &&
pending_.size() >= kMaxPendingNotifications) {
return std::unexpected{Void::Async::make_async_error(
Void::Async::AsyncErrorCode::overloaded,
"Observable pending notification queue full")};
}
set(std::move(new_val));
return {};
}
Observable& operator=(T new_val)
@@ -48,21 +95,26 @@ public:
return *this;
}
Handle on_change(Listener listener)
Handle on_change(Listener fn)
{
const Handle h{++next_id_};
listeners_.push_back({h, std::move(listener)});
const Handle h{next_id_++};
auto entry = std::make_shared<Entry>(Entry{h, true, std::move(fn)});
listeners_.push_back(std::move(entry));
return h;
}
bool unsubscribe(Handle h)
{
const auto it =
std::ranges::find_if(listeners_,
[&](const auto& e) { return e.h == h; });
if (it == listeners_.end()) return false;
listeners_.erase(it);
return true;
for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
if ((*it)->handle == h) {
(*it)->active = false;
auto dropped = std::move((*it)->fn);
listeners_.erase(it);
dropped = {};
return true;
}
}
return false;
}
[[nodiscard]] std::size_t listener_count() const noexcept
@@ -70,52 +122,141 @@ public:
return listeners_.size();
}
private:
void notify(const T& old_val, const T& new_val)
[[nodiscard]] std::size_t dropped_notifications() const noexcept
{
for (auto& [h, fn] : listeners_) fn(old_val, new_val);
return dropped_notifications_;
}
T value_;
std::uint64_t next_id_{0};
struct Entry
{
Handle h;
Listener fn;
private:
struct Entry {
Handle handle{0};
bool active{true};
Listener fn{};
};
std::vector<Entry> listeners_;
void notify_snapshot(const T& old_val, const T& new_val) const
{
auto snapshot = listeners_;
for (const auto& entry : snapshot) {
if (!entry->active || !entry->fn) {
continue;
}
auto fn = entry->fn;
fn(old_val, new_val);
fn = {};
}
}
void dispatch_fifo(T first_old, T first_new)
requires std::copy_constructible<T>
{
dispatch_depth_ = 1;
try {
notify_snapshot(first_old, first_new);
while (!pending_.empty()) {
auto next = std::move(pending_.front());
pending_.pop_front();
notify_snapshot(next.first, next.second);
}
} catch (...) {
dropped_notifications_ += pending_.size();
pending_.clear();
dispatch_depth_ = 0;
throw;
}
dispatch_depth_ = 0;
}
using QueueType = std::conditional_t<
std::copy_constructible<T>,
std::deque<std::pair<T, T>>,
detail::EmptyQueue>;
T value_;
std::vector<std::shared_ptr<Entry>> listeners_{};
QueueType pending_{};
std::size_t dispatch_depth_{0};
std::size_t dropped_notifications_{0};
std::uint64_t next_id_{1};
};
// ── Signal<Args...> ───────────────────────────────────────────────────────────
// An event signal that observers connect to. emit() calls all connected slots.
/// Typed multi-slot signal.
/// Single-threaded (not thread-safe across threads), reentrancy-safe:
/// snapshots connected slots and queues nested emit() calls FIFO when all
/// decayed Args are copy-constructible (bounded at kMaxPendingNotifications).
template <typename... Args>
class Signal
{
public:
using Slot = std::function<void(const Args&...)>;
Handle connect(Slot slot)
Handle connect(Slot fn)
{
const Handle h{++next_id_};
slots_.push_back({h, std::move(slot)});
const Handle h{next_id_++};
auto entry = std::make_shared<Entry>(Entry{h, true, std::move(fn)});
slots_.push_back(std::move(entry));
return h;
}
bool disconnect(Handle h)
{
const auto it =
std::ranges::find_if(slots_,
[&](const auto& e) { return e.h == h; });
if (it == slots_.end()) return false;
slots_.erase(it);
return true;
for (auto it = slots_.begin(); it != slots_.end(); ++it) {
if ((*it)->handle == h) {
(*it)->active = false;
auto dropped = std::move((*it)->fn);
slots_.erase(it);
dropped = {};
return true;
}
}
return false;
}
void clear() noexcept
{
auto all = std::move(slots_);
slots_.clear();
for (auto& e : all) {
e->active = false;
e->fn = {};
}
}
void emit(const Args&... args) const
{
for (const auto& [h, fn] : slots_) fn(args...);
constexpr bool kAllCopyable =
(std::copy_constructible<std::decay_t<Args>> && ...);
if constexpr (kAllCopyable) {
if (dispatch_depth_ > 0) {
if (pending_.size() < kMaxPendingNotifications) {
pending_.emplace_back(args...);
} else {
++dropped_notifications_;
}
return;
}
dispatch_depth_ = 1;
try {
emit_snapshot(args...);
while (!pending_.empty()) {
auto next = std::move(pending_.front());
pending_.pop_front();
std::apply(
[this](const auto&... packed) {
emit_snapshot(packed...);
},
next);
}
} catch (...) {
dropped_notifications_ += pending_.size();
pending_.clear();
dispatch_depth_ = 0;
throw;
}
dispatch_depth_ = 0;
} else {
emit_snapshot(args...);
}
}
[[nodiscard]] std::size_t slot_count() const noexcept
@@ -123,17 +264,45 @@ public:
return slots_.size();
}
void clear() noexcept { slots_.clear(); }
[[nodiscard]] std::size_t dropped_notifications() const noexcept
{
return dropped_notifications_;
}
private:
std::uint64_t next_id_{0};
struct Entry
{
Handle h;
Slot fn;
struct Entry {
Handle handle{0};
bool active{true};
Slot fn{};
};
std::vector<Entry> slots_;
void emit_snapshot(const Args&... args) const
{
auto snapshot = slots_;
for (const auto& entry : snapshot) {
if (!entry->active || !entry->fn) {
continue;
}
auto fn = entry->fn;
fn(args...);
fn = {};
}
}
static constexpr bool kCopyableArgs =
(std::copy_constructible<std::decay_t<Args>> && ...);
using TupleType = std::tuple<std::decay_t<Args>...>;
using QueueType = std::conditional_t<
kCopyableArgs,
std::deque<TupleType>,
detail::EmptyQueue>;
std::vector<std::shared_ptr<Entry>> slots_{};
mutable QueueType pending_{};
mutable std::size_t dispatch_depth_{0};
mutable std::size_t dropped_notifications_{0};
std::uint64_t next_id_{1};
};
} // namespace Void::Observable
+302 -3
View File
@@ -1,7 +1,20 @@
#pragma once
#include <Void/Async/ThreadPool.hpp>
#include <algorithm>
#include <atomic>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <expected>
#include <future>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Concurrency
@@ -9,6 +22,10 @@ namespace Void::Concurrency
// Submit one task per index in [first, last) to pool; block until all done.
// Exceptions from tasks propagate via std::future::get() to the caller.
//
// Every submitted future is waited for before the first exception is
// rethrown (a throwing task, or a failing submit, never leaves other tasks
// running against the caller's stack).
template <std::integral I, std::invocable<I> F>
void parallel_for(I first, I last, F&& f, ThreadPool& pool)
{
@@ -17,11 +34,25 @@ namespace Void::Concurrency
}
std::vector<std::future<void>> futures;
futures.reserve(static_cast<std::size_t>(last - first));
for (auto i = first; i < last; ++i) {
futures.push_back(pool.submit([f, i] { f(i); }));
std::exception_ptr first_error;
try {
for (auto i = first; i < last; ++i) {
futures.push_back(pool.submit([f, i] { f(i); }));
}
} catch (...) {
first_error = std::current_exception();
}
for (auto& fut : futures) {
fut.get();
try {
fut.get();
} catch (...) {
if (!first_error) {
first_error = std::current_exception();
}
}
}
if (first_error) {
std::rethrow_exception(first_error);
}
}
@@ -34,4 +65,272 @@ namespace Void::Concurrency
parallel_for(first, last, std::forward<F>(f), pool);
}
// ── Bounded, chunked parallel_for ────────────────────────────────────────
struct ParallelForOptions {
// Indices per chunk; zero is invalid.
std::size_t grain{1};
// Maximum chunks running at once (the calling thread counts when it
// runs chunks inline); zero means the pool's thread count.
std::size_t max_concurrency{0};
// No new chunk starts once stop is requested.
std::stop_token stop{};
// No new chunk starts after the first failed chunk. When false every
// chunk runs and all failures are counted.
bool stop_on_error{true};
};
struct ParallelForError {
enum class Kind : std::uint8_t {
invalid_argument,
rejected, // reserved: not produced in this release
stopped,
failed
} kind;
std::size_t chunks_total{0};
std::size_t chunks_started{0};
std::size_t chunks_failed{0};
std::optional<std::size_t> first_failed_chunk{};
std::exception_ptr first_exception{};
};
namespace detail
{
// Shared between the caller and every runner. Runners hold it through
// a shared_ptr, so a runner that starts after the caller stopped
// claiming chunks (or that the pool never started in time) never
// touches freed state.
template <class Fn, class Index> struct PForState {
template <class G>
PForState(G&& fn_in, Index first_in, std::uintmax_t count_in,
std::uintmax_t grain_in, std::size_t chunks,
std::stop_token stop_in, bool stop_on_error_in)
: fn(std::forward<G>(fn_in)), first(first_in),
count(count_in), grain(grain_in), chunks_total(chunks),
stop(std::move(stop_in)), stop_on_error(stop_on_error_in)
{
}
const Fn fn;
const Index first;
const std::uintmax_t count;
const std::uintmax_t grain;
const std::size_t chunks_total;
const std::stop_token stop;
const bool stop_on_error;
std::atomic<std::size_t> next_chunk{0};
std::atomic<std::size_t> started{0};
std::atomic<bool> failed_flag{false};
std::atomic<bool> aborted{false};
std::mutex error_mu{};
std::size_t failed{0};
std::optional<std::size_t> first_failed{};
std::exception_ptr first_exception{};
[[nodiscard]] bool should_stop() const noexcept
{
return aborted.load(std::memory_order_acquire) ||
stop.stop_requested() ||
(stop_on_error &&
failed_flag.load(std::memory_order_acquire));
}
void record_failure(std::size_t chunk, std::exception_ptr error)
{
std::lock_guard lk{error_mu};
++failed;
if (!first_failed.has_value() || chunk < *first_failed) {
first_failed = chunk;
first_exception = std::move(error);
}
failed_flag.store(true, std::memory_order_release);
}
// Claims and runs chunks until the range is exhausted, a stop
// is requested or (stop_on_error) a chunk failed. Never throws:
// every chunk failure is recorded.
void run_chunks() noexcept
{
using U = std::make_unsigned_t<std::conditional_t<
std::same_as<Index, bool>, unsigned char, Index>>;
for (;;) {
if (should_stop()) {
return;
}
const std::size_t chunk =
next_chunk.fetch_add(1, std::memory_order_acq_rel);
if (chunk >= chunks_total) {
return;
}
// A stop that arrived between the check and the claim:
// the claimed chunk is abandoned unstarted.
if (should_stop()) {
return;
}
started.fetch_add(1, std::memory_order_relaxed);
const std::uintmax_t begin =
static_cast<std::uintmax_t>(chunk) * grain;
const std::uintmax_t length =
std::min<std::uintmax_t>(grain, count - begin);
try {
for (std::uintmax_t k = 0; k < length; ++k) {
const Index i = static_cast<Index>(
static_cast<U>(static_cast<U>(first) +
static_cast<U>(begin + k)));
fn(i);
}
} catch (...) {
record_failure(chunk, std::current_exception());
}
}
}
};
// Waits for every future on every exit path (including an exception
// thrown while submitting): a runner may still call `f`, which can
// capture the caller's stack by reference.
class RunnerJoin
{
public:
explicit RunnerJoin(std::vector<std::future<void>>& futures)
: futures_(futures)
{
}
RunnerJoin(const RunnerJoin&) = delete;
RunnerJoin& operator=(const RunnerJoin&) = delete;
~RunnerJoin() { join(); }
void join() noexcept
{
for (auto& fut : futures_) {
if (fut.valid()) {
fut.wait();
}
}
}
private:
std::vector<std::future<void>>& futures_;
};
} // namespace detail
// Bounded, chunked parallel_for over [first, last).
//
// The range is split into chunks of `options.grain` indices. At most
// `max_concurrency` chunks run at once (0 = pool.thread_count(); the
// caller counts when it runs chunks inline). Runners are submitted with
// try_submit; when the pool rejects a runner (full or stopped) the CALLING
// thread runs chunks itself (no further runner is submitted). The caller
// waits for EVERY submitted runner, including runners that never started.
//
// Results: success when every chunk ran (also for first >= last);
// otherwise a ParallelForError with precedence invalid_argument (grain ==
// 0) > failed (a chunk threw; the lowest-indexed failed chunk is
// reported) > stopped (stop requested before every chunk started).
// `Kind::rejected` is not produced in this release. With `stop_on_error`
// no new chunk starts after the first failure (chunks already running
// finish). Chunk boundaries and the range arithmetic use the unsigned type
// of `I`, so the full range of `I` is safe.
//
// `f` is copied once into shared state and invoked concurrently through a
// const reference, so it must be safe to call concurrently (as with the
// legacy overload). Calling this from a worker of the same `pool` is
// unsupported (the caller would wait for runners that need its thread).
template <std::integral I, std::invocable<I> F>
[[nodiscard]] std::expected<void, ParallelForError>
parallel_for(I first, I last, F&& f, ThreadPool& pool,
ParallelForOptions options)
{
using Fn = std::decay_t<F>;
using U = std::make_unsigned_t<
std::conditional_t<std::same_as<I, bool>, unsigned char, I>>;
if (options.grain == 0) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::invalid_argument}};
}
if (first >= last) {
return {};
}
const std::uintmax_t count = static_cast<std::uintmax_t>(
static_cast<U>(static_cast<U>(last) - static_cast<U>(first)));
const std::uintmax_t grain = options.grain;
const std::uintmax_t chunk_count =
count / grain + (count % grain != 0 ? 1 : 0);
if (chunk_count > std::numeric_limits<std::size_t>::max()) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::invalid_argument}};
}
const std::size_t chunks_total = static_cast<std::size_t>(chunk_count);
std::size_t concurrency = options.max_concurrency != 0
? options.max_concurrency
: pool.thread_count();
concurrency = std::max<std::size_t>(concurrency, 1);
const std::size_t runner_count = std::min(concurrency, chunks_total);
auto state = std::make_shared<detail::PForState<Fn, I>>(
std::forward<F>(f), first, count, grain, chunks_total, options.stop,
options.stop_on_error);
std::vector<std::future<void>> futures;
futures.reserve(runner_count);
bool run_inline = false;
if (!options.stop.stop_requested()) {
// Declared after `futures`: waits for every submitted runner on
// every exit path, including an exception while submitting.
detail::RunnerJoin join{futures};
try {
for (std::size_t r = 0; r < runner_count; ++r) {
// The runner moves its reference out of the capture and
// drops it before its future becomes ready, so the caller
// always releases the last reference: the shared state
// (copied F, stored exception) is never destroyed on a
// pool worker after parallel_for has returned.
auto submitted = pool.try_submit(
[runner_state = state]() mutable {
auto local = std::move(runner_state);
local->run_chunks();
});
if (!submitted.has_value()) {
run_inline = true;
break;
}
futures.push_back(std::move(*submitted));
}
if (run_inline) {
// The pool is full or stopped: this thread is one more
// runner (fewer than runner_count runners were submitted,
// so the total stays within the bound).
state->run_chunks();
}
} catch (...) {
state->aborted.store(true, std::memory_order_release);
throw;
}
}
const std::size_t started =
state->started.load(std::memory_order_acquire);
std::lock_guard lk{state->error_mu};
if (state->failed > 0) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::failed, chunks_total, started,
state->failed, state->first_failed, state->first_exception}};
}
if (started < chunks_total) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::stopped, chunks_total, started, 0,
std::nullopt, nullptr}};
}
return {};
}
} // namespace Void::Concurrency
+220
View File
@@ -0,0 +1,220 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Functional/RetryState.hpp>
#include <concepts>
#include <cstdint>
#include <expected>
#include <functional>
#include <optional>
#include <random>
#include <type_traits>
#include <utility>
// ── retry_async ───────────────────────────────────────────────────────────────
// Asynchronous adapter over `Void::Retry::RetryState` (C-03/C-04). Attempts run
// on the coroutine; every backoff between attempts is a `TimerQueue` sleep in
// the queue's injected clock domain.
//
// * "Now" is always `timers.clock().now()`, re-read after every suspension. The
// host clock is never consulted and no thread ever sleeps. A backoff ends
// only when the queue's owner advances the injected clock (or real time
// passes, for a system clock), calls `poll_expired()` and then drains the
// queue's completion executor. Even a zero-length backoff needs that poll, so
// the adapter never spins.
// * The effective deadline is min(start + spec.budget, options.deadline), where
// `start` is the clock reading taken when the (lazy) task first runs and
// `options.deadline` is an absolute admission deadline in the same domain.
// * `options.stop` is checked before every attempt (RetryState::begin/resume),
// after every failed attempt (RetryState::next), and wakes a pending backoff.
// No attempt starts after a stop decision. An attempt that succeeds is
// returned even if the stop was requested while it ran.
//
// Results (exactly one):
// success the value of the successful attempt
// invalid spec RetryError{reason = none, attempts = 0, last_error = {},
// config = error}; `fn` is never called
// RetryState stop RetryError{reason, attempts, last_error} with reason
// attempts_exhausted, deadline_exceeded, not_retryable or
// stop_requested
// failed backoff a backoff sleep that does not complete normally ends the
// retry at once, with no further attempt:
// cancelled (stop won the race with the timer) -> stop_requested
// timeout (options.deadline had already passed when the
// backoff was admitted) -> deadline_exceeded
// stopped (the queue was closed before or during the
// backoff: queue closure aborts the retry)
// -> stop_requested
// overloaded (the queue already holds max_timers timers;
// reported rather than retried without a wait)
// -> stop_requested
// any other sleep error -> stop_requested
// A backoff that completes normally always goes through RetryState::resume
// with a fresh clock reading and stop state, so a stop that lands after the
// timer fired (the sleep then reports success) or a deadline that passed
// before the poll still prevents the next attempt. `attempts` counts started
// attempts; `last_error` holds the most recent attempt error and is empty iff
// no attempt ran. A closed queue does not prevent the first attempt (it needs
// no timer); it ends the retry at the first backoff.
//
// Callable: `fn` is invoked as an lvalue and returns `std::expected<T, E>` or
// `Coro::Task<std::expected<T, E>>` (awaited). `T` may be void or move-only,
// `E` and `F` may be move-only. `classify` is called as AttemptOutcome(const E&).
// An exception thrown by `fn`, by its task or by `classify` propagates out of
// the retry task (rethrown where the retry task is awaited); no further
// attempt is made, and no backoff timer is in flight while an attempt runs.
// `Task::run()` / `sync_wait()` are valid only when the retry finishes without
// suspending in a backoff; otherwise co_await the task and drive the timer
// queue (poll_expired) and its executor until it completes.
//
// Threading: the first attempt runs on the thread that starts the task; every
// later attempt runs where the backoff sleep resumes, i.e. on the completion
// lane of `timers.executor()`. The RetryState is touched only by the coroutine.
//
// Lifetime: the task owns `spec`, `fn`, `options`, `classify` and `urbg` by
// value. `timers`, its completion executor and its clock must outlive the task.
// The TimerQueue sleep rules apply to a retry task suspended in a backoff: it
// may be destroyed only while that backoff's timer is still pending and the
// destruction is serialized with poll, close and stop (the timer is then
// cancelled); once the timer has been settled (fired, cancelled by stop, or
// closed) the task must stay alive until its posted resume has run. Shutdown
// order: `timers.close()`, drain the completion executor, then destroy the
// task. While an attempt's own task is suspended, that task's rules apply.
namespace Void::Async
{
namespace detail
{
template <class R>
struct retry_attempt_traits;
template <class T, class E>
struct retry_attempt_traits<std::expected<T, E>> {
using value_type = T;
using error_type = E;
static constexpr bool is_task = false;
};
template <class T, class E>
struct retry_attempt_traits<Coro::Task<std::expected<T, E>>> {
using value_type = T;
using error_type = E;
static constexpr bool is_task = true;
};
template <class F>
using retry_attempt_traits_t =
retry_attempt_traits<std::remove_cvref_t<std::invoke_result_t<F&>>>;
template <class F>
using retry_async_result_t = std::expected<
typename retry_attempt_traits_t<F>::value_type,
Void::Retry::RetryError<typename retry_attempt_traits_t<F>::error_type>>;
// Reason a retry stops with when its backoff sleep did not complete normally.
[[nodiscard]] inline Void::Retry::RetryStopReason
retry_backoff_stop_reason(const Void::Result::Error& error) noexcept
{
const Void::Result::ErrorCode code = error.code();
if (code.domain == Void::Result::kAsyncErrorDomain &&
code.value == static_cast<std::int32_t>(AsyncErrorCode::timeout)) {
return Void::Retry::RetryStopReason::deadline_exceeded;
}
// cancelled, stopped (queue closed), overloaded, or anything unexpected:
// terminal, never a retry without a wait.
return Void::Retry::RetryStopReason::stop_requested;
}
} // namespace detail
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<detail::retry_async_result_t<F>>
{
using Traits = detail::retry_attempt_traits_t<F>;
using T = typename Traits::value_type;
using E = typename Traits::error_type;
using Error = Void::Retry::RetryError<E>;
using Out = std::expected<T, Error>;
using Void::Retry::RetryAction;
using Void::Retry::RetryDecision;
using Void::Retry::RetryStopReason;
static_assert(std::uniform_random_bit_generator<URBG>,
"URBG must satisfy std::uniform_random_bit_generator");
static_assert(
std::is_invocable_r_v<Void::Retry::AttemptOutcome, Classify&, const E&>,
"Classify must be callable as AttemptOutcome(const E&)");
if (const auto valid = Void::Retry::validate(spec); !valid) {
co_return Out(std::unexpect,
Error{RetryStopReason::none, 0, std::nullopt, valid.error()});
}
const Void::Time::MonotonicClock& clock = timers.clock();
const Void::Retry::SteadyTimePoint start = clock.now();
auto created = Void::Retry::RetryState<URBG>::create(
spec, start, std::move(urbg), options.deadline);
if (!created.has_value()) { // unreachable after validate()
co_return Out(std::unexpect,
Error{RetryStopReason::none, 0, std::nullopt, created.error()});
}
Void::Retry::RetryState<URBG>& state = *created;
std::optional<E> last_error;
RetryDecision decision = state.begin(start, options.stop.stop_requested());
for (;;) {
if (decision.action == RetryAction::attempt) {
std::optional<std::expected<T, E>> result;
if constexpr (Traits::is_task) {
result.emplace(co_await std::invoke(fn));
} else {
result.emplace(std::invoke(fn));
}
if (result->has_value()) {
(void)state.succeed();
if constexpr (std::is_void_v<T>) {
co_return Out{};
} else {
co_return Out(std::in_place, std::move(**result));
}
}
last_error.emplace(std::move(*result).error());
result.reset();
const Void::Retry::AttemptOutcome outcome =
std::invoke(classify, std::as_const(*last_error));
decision = state.next(clock.now(), outcome, options.stop.stop_requested());
} else if (decision.action == RetryAction::wait_until) {
OperationOptions sleep_options{options.stop, options.deadline};
auto slept = co_await timers.sleep_until(decision.at, std::move(sleep_options));
if (!slept.has_value()) {
co_return Out(std::unexpect,
Error{detail::retry_backoff_stop_reason(slept.error()),
state.attempts_started(),
std::move(last_error),
std::nullopt});
}
decision = state.resume(clock.now(), options.stop.stop_requested());
} else {
co_return Out(std::unexpect,
Error{decision.reason,
decision.attempts_started,
std::move(last_error),
std::nullopt});
}
}
}
} // namespace Void::Async
+604
View File
@@ -0,0 +1,604 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <exception>
#include <expected>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>
// ── ThreadExecutor ────────────────────────────────────────────────────────────
// A thread-backed `Executor` with a bounded normal lane and a reserved,
// prioritized completion lane (C-03/C-04).
//
// Lifecycle
// create() builds the object and starts NO thread. Admission before start()
// queues normally; nothing runs until start() succeeds.
// start() once. `before_worker_start(i)` (a fault-injection hook, called on
// the starting thread with no lock held) and every `std::thread`
// construction share ONE failure path: workers that were already
// started are told to exit WITHOUT dequeuing anything and are
// joined, start() returns the error and may be retried. start()
// after a successful start, or after close()/join(), returns
// `invalid_argument`.
// close() normal admission (`try_post`, `try_reserve_slot`) returns
// `stopped`; a legacy `post()` is redirected onto the completion
// lane (counted); `post_completion` keeps working. Reservations
// taken before close() stay binding.
// join() close() + drain BOTH lanes until they are empty with nothing
// running and no reservation outstanding, then joins the worker
// threads. Safe to call repeatedly and concurrently (later callers
// wait for the first join to finish). On an executor thread it
// returns `AdmissionError::self_join`. When no worker is running
// (never started, or start() failed) join() drains both lanes
// INLINE on the caller under `ExecutorThreadGuard` (counted as
// `inline_after_join`) and never waits for workers; it still waits
// for an outstanding reservation, which another thread must commit
// or release.
// after join(): `post` / `post_completion` / `commit_reserved` resume the
// handle inline on the caller (counted `inline_after_join`);
// a handle is never dropped. `try_post` / `try_reserve_slot`
// return `stopped`. The switch to inline mode happens under the
// executor mutex in the same critical section that observes
// quiescence, so no handle can be stranded between the two modes.
// ~ThreadExecutor without a prior join() is close() + join(). Destroying the
// executor on one of its own executor threads (a worker, or a
// thread currently resuming a handle inline) prints a diagnostic
// to stderr and calls std::terminate.
//
// Bound
// `admitted()` = queued + running (normal lane) + reserved. `try_post` and
// `try_reserve_slot` return `overloaded` once `admitted() >= max_admitted`.
// A slot is released only after the resumed handle returns. A reservation
// counts in the bound until it is committed or released. Legacy `post()`
// never rejects (it is counted and may exceed the bound). The completion
// lane is not bounded and not counted in `admitted()`.
//
// Drain policy
// There is NO drain cap (C-03 forbids abandoning a frame). A handle that
// keeps re-posting itself prevents join() from returning; that is a caller
// error. A handle must not let an exception escape `resume()` (the worker
// would std::terminate). A reservation that is never committed or released
// prevents join() from returning (caller error).
//
// Snapshots: `idle()`, `admitted()` and `stats()` are point-in-time snapshots.
// `has_background_workers()` is the constant `true` (the design intent is a
// threaded executor; start() must have succeeded for work to make progress).
namespace Void::Async
{
struct ThreadExecutorOptions {
// Number of worker threads; zero is rejected by create().
std::size_t workers{1};
// Bound on queued + running normal-lane work (+ reservations); >= 1.
std::size_t max_admitted{4096};
// Called once per worker, on the starting thread with no lock held, before
// that worker's std::thread is created. An error (or a thrown exception)
// aborts start() through the shared failure path.
std::function<Void::Result::Result<void>(std::size_t)> before_worker_start{};
};
struct ThreadExecutorStats {
std::size_t queued{0}; // normal lane, not yet running
std::size_t running{0}; // handles being resumed now (both lanes)
std::size_t completion_queued{0}; // completion lane, not yet running
std::uint64_t rejected{0}; // try_post / try_reserve_slot -> overloaded
std::uint64_t legacy_posts{0}; // every post() call
std::uint64_t inline_after_join{0}; // handles resumed inline on a caller
};
class ThreadExecutor final : public Executor
{
public:
// Errors: invalid_argument when workers == 0 or max_admitted == 0.
// Starts no thread.
[[nodiscard]] static Void::Result::Result<std::unique_ptr<ThreadExecutor>>
create(ThreadExecutorOptions options = {})
{
if (options.workers == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"ThreadExecutor workers must be greater than zero")};
}
if (options.max_admitted == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"ThreadExecutor max_admitted must be greater than zero")};
}
return std::unique_ptr<ThreadExecutor>(new ThreadExecutor(std::move(options)));
}
ThreadExecutor(const ThreadExecutor&) = delete;
ThreadExecutor& operator=(const ThreadExecutor&) = delete;
ThreadExecutor(ThreadExecutor&&) = delete;
ThreadExecutor& operator=(ThreadExecutor&&) = delete;
~ThreadExecutor() override
{
if (is_executor_thread()) {
std::fputs(
"Void::Async::ThreadExecutor destroyed on its own executor thread\n",
stderr);
std::terminate();
}
(void)join();
}
// Starts the workers. Errors: invalid_argument (after close(), join() or a
// successful start()), the hook's error, or backend_error (with the
// system code when a std::system_error was caught) when a thread could not
// be created. After an error no thread is left running and start() may be
// retried.
[[nodiscard]] Void::Result::Result<void> start()
{
{
std::lock_guard lk{mu_};
if (closed_ || phase_ != Phase::created) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"ThreadExecutor::start after start, close or join")};
}
phase_ = Phase::starting;
}
std::optional<Void::Result::Error> failure;
try {
workers_.reserve(options_.workers);
for (std::size_t i = 0; i < options_.workers; ++i) {
if (options_.before_worker_start) {
auto hook = options_.before_worker_start(i);
if (!hook.has_value()) {
failure = std::move(hook.error());
break;
}
}
workers_.emplace_back([this] { worker_loop(); });
}
} catch (const std::system_error& e) {
failure = Void::Result::Error{
Void::Result::ErrorKind::internal,
std::string{"ThreadExecutor worker start failed: "} + e.what(),
Void::Result::ErrorCode{
Void::Result::kAsyncErrorDomain,
static_cast<std::int32_t>(AsyncErrorCode::backend_error)},
e.code()};
} catch (const std::exception& e) {
failure = make_async_error(
AsyncErrorCode::backend_error,
std::string{"ThreadExecutor worker start failed: "} + e.what());
} catch (...) {
failure = make_async_error(
AsyncErrorCode::backend_error,
"ThreadExecutor worker start failed: unknown exception");
}
if (failure.has_value()) {
{
std::lock_guard lk{mu_};
abort_start_ = true;
}
work_cv_.notify_all();
for (auto& worker : workers_) {
worker.join();
}
workers_.clear();
{
std::lock_guard lk{mu_};
abort_start_ = false;
phase_ = Phase::created;
}
state_cv_.notify_all();
return std::unexpected{std::move(*failure)};
}
{
std::lock_guard lk{mu_};
phase_ = Phase::running;
}
work_cv_.notify_all();
state_cv_.notify_all();
return {};
}
// Legacy admission: never rejects and never drops the handle. Counted in
// `legacy_posts`; may exceed the bound. After close() the handle goes to
// the completion lane; after join() it is resumed inline on the caller.
void post(std::coroutine_handle<> handle) override
{
if (!handle) {
return;
}
bool run_inline = false;
{
std::lock_guard lk{mu_};
if (inline_mode_) {
++legacy_posts_;
++inline_after_join_;
run_inline = true;
} else {
if (closed_) {
completion_.push_back(handle);
} else {
normal_.push_back(handle);
}
++legacy_posts_;
}
}
if (run_inline) {
resume_inline(handle);
} else {
wake_one();
}
}
// Bounded admission. Errors: invalid_argument (empty handle), stopped
// (after close()), overloaded (admitted() >= max_admitted).
[[nodiscard]] std::expected<void, AdmissionError>
try_post(std::coroutine_handle<> handle) override
{
if (!handle) {
return std::unexpected{AdmissionError::invalid_argument};
}
{
std::lock_guard lk{mu_};
if (closed_) {
return std::unexpected{AdmissionError::stopped};
}
if (admitted_locked() >= options_.max_admitted) {
++rejected_;
return std::unexpected{AdmissionError::overloaded};
}
normal_.push_back(handle);
}
wake_one();
return {};
}
// Reserved lane: never rejected, prioritized over the normal lane and
// drained after close(). After join() the handle is resumed inline.
void post_completion(std::coroutine_handle<> handle) override
{
if (!handle) {
return;
}
bool run_inline = false;
{
std::lock_guard lk{mu_};
if (inline_mode_) {
++inline_after_join_;
run_inline = true;
} else {
completion_.push_back(handle);
}
}
if (run_inline) {
resume_inline(handle);
} else {
wake_one();
}
}
[[nodiscard]] bool supports_reservation() const noexcept override { return true; }
// Reserves one slot of the bound. Errors: stopped (after close()),
// overloaded (admitted() >= max_admitted). A reservation must be answered
// by commit_reserved() or release_reserved().
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override
{
std::lock_guard lk{mu_};
if (closed_) {
return std::unexpected{AdmissionError::stopped};
}
if (admitted_locked() >= options_.max_admitted) {
++rejected_;
return std::unexpected{AdmissionError::overloaded};
}
++reserved_;
return {};
}
// Turns a reservation into a queued handle. Binding even after close().
// If enqueuing throws (allocation failure) the reservation is still held
// and the caller must release_reserved() it. An empty handle releases the
// reservation.
void commit_reserved(std::coroutine_handle<> handle) override
{
if (!handle) {
release_reserved();
return;
}
bool run_inline = false;
{
std::lock_guard lk{mu_};
if (inline_mode_) {
if (reserved_ > 0) {
--reserved_;
}
++inline_after_join_;
run_inline = true;
} else {
normal_.push_back(handle);
if (reserved_ > 0) {
--reserved_;
}
}
}
if (run_inline) {
resume_inline(handle);
} else {
wake_one();
}
}
void release_reserved() noexcept override
{
{
std::lock_guard lk{mu_};
if (reserved_ > 0) {
--reserved_;
}
}
state_cv_.notify_all();
}
[[nodiscard]] bool has_background_workers() const noexcept override { return true; }
// Closes normal admission (see the class comment). Idempotent.
void close() noexcept
{
{
std::lock_guard lk{mu_};
closed_ = true;
}
work_cv_.notify_all();
state_cv_.notify_all();
}
// close() + drain + join (see the class comment). Errors: self_join on an
// executor thread.
[[nodiscard]] Void::Result::Result<void> join()
{
if (is_executor_thread()) {
return std::unexpected{make_async_error(
AdmissionError::self_join,
"ThreadExecutor::join called from an executor thread")};
}
std::unique_lock lk{mu_};
closed_ = true;
for (;;) {
if (phase_ == Phase::joined) {
return {};
}
if (phase_ == Phase::starting || phase_ == Phase::joining) {
state_cv_.wait(lk, [this] {
return phase_ != Phase::starting && phase_ != Phase::joining;
});
continue;
}
break;
}
if (phase_ == Phase::running) {
phase_ = Phase::joining;
work_cv_.notify_all();
state_cv_.wait(lk, [this] { return quiescent_locked(); });
// Same critical section as the quiescence observation: from here
// every admission resumes inline on its caller.
inline_mode_ = true;
std::vector<std::thread> threads = std::move(workers_);
workers_.clear();
lk.unlock();
work_cv_.notify_all();
for (auto& worker : threads) {
worker.join();
}
lk.lock();
phase_ = Phase::joined;
lk.unlock();
state_cv_.notify_all();
return {};
}
// Phase::created: no worker exists. The joiner is the worker.
phase_ = Phase::joining;
for (;;) {
if (!completion_.empty() || !normal_.empty()) {
const bool from_completion = !completion_.empty();
std::coroutine_handle<> handle;
if (from_completion) {
handle = completion_.front();
completion_.pop_front();
} else {
handle = normal_.front();
normal_.pop_front();
}
++inline_after_join_;
run_locked(lk, handle, from_completion);
continue;
}
if (reserved_ == 0 && running_normal_ == 0 && running_completion_ == 0) {
break;
}
state_cv_.wait(lk, [this] {
return !completion_.empty() || !normal_.empty() ||
(reserved_ == 0 && running_normal_ == 0 &&
running_completion_ == 0);
});
}
inline_mode_ = true;
phase_ = Phase::joined;
lk.unlock();
state_cv_.notify_all();
return {};
}
// True when both lanes are empty and nothing is running (a snapshot).
[[nodiscard]] bool idle() const noexcept
{
std::lock_guard lk{mu_};
return normal_.empty() && completion_.empty() && running_normal_ == 0 &&
running_completion_ == 0;
}
// queued + running (normal lane) + reserved (a snapshot).
[[nodiscard]] std::size_t admitted() const noexcept
{
std::lock_guard lk{mu_};
return admitted_locked();
}
[[nodiscard]] ThreadExecutorStats stats() const noexcept
{
std::lock_guard lk{mu_};
return ThreadExecutorStats{
normal_.size(),
running_normal_ + running_completion_,
completion_.size(),
rejected_,
legacy_posts_,
inline_after_join_};
}
private:
enum class Phase : std::uint8_t {
created, // no worker; start() allowed
starting, // start() in progress
running, // workers live
joining, // join() in progress
joined // workers gone; inline mode
};
explicit ThreadExecutor(ThreadExecutorOptions options)
: options_(std::move(options))
{
}
[[nodiscard]] std::size_t admitted_locked() const noexcept
{
return normal_.size() + running_normal_ + reserved_;
}
[[nodiscard]] bool quiescent_locked() const noexcept
{
return normal_.empty() && completion_.empty() && running_normal_ == 0 &&
running_completion_ == 0 && reserved_ == 0;
}
void wake_one()
{
work_cv_.notify_one();
// A joiner without workers drains the lanes itself and waits for them
// on the state condition variable.
state_cv_.notify_all();
}
void resume_inline(std::coroutine_handle<> handle)
{
detail::ExecutorThreadGuard guard{this};
handle.resume();
}
// Resumes `handle` (already popped and not yet counted as running) with
// the lock released, then re-acquires it and releases the slot. The slot is
// released only after the handle returned (or threw).
void run_locked(std::unique_lock<std::mutex>& lk,
std::coroutine_handle<> handle,
bool from_completion)
{
if (from_completion) {
++running_completion_;
} else {
++running_normal_;
}
lk.unlock();
try {
detail::ExecutorThreadGuard guard{this};
handle.resume();
} catch (...) {
lk.lock();
finish_locked(from_completion);
throw;
}
lk.lock();
finish_locked(from_completion);
}
void finish_locked(bool from_completion) noexcept
{
if (from_completion) {
--running_completion_;
} else {
--running_normal_;
}
if (phase_ == Phase::joining) {
state_cv_.notify_all();
}
}
void worker_loop()
{
std::unique_lock lk{mu_};
for (;;) {
work_cv_.wait(lk, [this] {
if (abort_start_ || inline_mode_) {
return true;
}
if (phase_ != Phase::running && phase_ != Phase::joining) {
return false;
}
return !completion_.empty() || !normal_.empty();
});
if (abort_start_ || inline_mode_) {
return;
}
const bool from_completion = !completion_.empty();
std::coroutine_handle<> handle;
if (from_completion) {
handle = completion_.front();
completion_.pop_front();
} else {
handle = normal_.front();
normal_.pop_front();
}
run_locked(lk, handle, from_completion);
}
}
ThreadExecutorOptions options_;
mutable std::mutex mu_{};
std::condition_variable work_cv_{}; // wakes workers
std::condition_variable state_cv_{}; // wakes start()/join() waiters
std::deque<std::coroutine_handle<>> normal_{};
std::deque<std::coroutine_handle<>> completion_{};
std::vector<std::thread> workers_{};
std::size_t running_normal_{0};
std::size_t running_completion_{0};
std::size_t reserved_{0};
std::uint64_t rejected_{0};
std::uint64_t legacy_posts_{0};
std::uint64_t inline_after_join_{0};
Phase phase_{Phase::created};
bool closed_{false};
bool inline_mode_{false};
bool abort_start_{false};
};
} // namespace Void::Async
+686
View File
@@ -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 -1
View File
@@ -188,7 +188,7 @@ public:
return std::unexpected{bytes.error()};
}
std::array<std::byte, sizeof(T)> storage{};
std::ranges::copy(*bytes, storage.begin());
std::memcpy(storage.data(), bytes->data(), sizeof(T));
T value = std::bit_cast<T>(storage);
if (byteOrder != std::endian::native) {
value = std::byteswap(value);
+216
View File
@@ -0,0 +1,216 @@
#pragma once
#include <Void/Discovery/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Discovery
{
class Catalog;
/// Move-only RAII handle for a local endpoint registration.
/// Destruction releases the registration from future snapshots.
class Registration final
{
public:
Registration() noexcept = default;
~Registration() noexcept;
Registration(Registration&& other) noexcept;
Registration& operator=(Registration&& other) noexcept;
Registration(const Registration&) = delete;
Registration& operator=(const Registration&) = delete;
[[nodiscard]] bool active() const noexcept;
[[nodiscard]] const std::string& service() const noexcept
{
return m_service;
}
[[nodiscard]] const std::string& instance() const noexcept
{
return m_instance;
}
[[nodiscard]] std::optional<Void::Time::MonotonicClock::time_point>
expires_at() const noexcept;
[[nodiscard]] Result<Void::Time::MonotonicClock::time_point> renew();
void release() noexcept;
private:
friend class Catalog;
struct State;
std::shared_ptr<void> m_catalog_state{};
std::string m_service{};
std::string m_instance{};
std::uint64_t m_token{0};
bool m_leased{false};
std::chrono::milliseconds m_ttl{0};
bool m_active{false};
};
/// Move-only handle for a bounded service watch.
/// `cancel()` stops new admission and is safe from inside the callback.
/// `join()` waits for already-admitted callbacks and returns `SelfJoin`
/// instead of deadlocking when called synchronously from the callback itself.
class WatchHandle final
{
public:
WatchHandle() noexcept = default;
~WatchHandle() noexcept;
WatchHandle(WatchHandle&& other) noexcept;
WatchHandle& operator=(WatchHandle&& other) noexcept;
WatchHandle(const WatchHandle&) = delete;
WatchHandle& operator=(const WatchHandle&) = delete;
[[nodiscard]] bool active() const noexcept;
[[nodiscard]] std::size_t pending_events() const noexcept;
void cancel() noexcept;
[[nodiscard]] Result<void> join() noexcept;
/// Explicit deterministic delivery step for `Manual` watch mode.
/// Returns true if an event was delivered.
bool deliver_one();
std::size_t deliver_all();
private:
friend class Catalog;
std::shared_ptr<void> m_catalog_state{};
std::shared_ptr<void> m_watch_node{};
std::uint64_t m_watch_id{0};
};
/// Pure, thread-free service endpoint catalog supporting atomic static
/// snapshots, local RAII leased/unleased registrations, and bounded watches.
class Catalog final
{
public:
explicit Catalog(CatalogOptions options = {});
~Catalog() noexcept;
Catalog(Catalog&&) noexcept;
Catalog& operator=(Catalog&&) noexcept;
Catalog(const Catalog&) = delete;
Catalog& operator=(const Catalog&) = delete;
/// Validate candidate static snapshot completely before atomic
/// publication. On any validation/conflict/cap error, preserves the
/// active revision unchanged.
[[nodiscard]] Result<std::uint64_t>
replace_static(std::vector<EndpointRecord> candidate,
bool bump_provider_generation = false);
/// Explicitly set provider health (e.g. for stale/unavailable
/// resolution policy testing or upper replicated directory adapters).
void set_provider_health(Freshness freshness,
std::optional<Error> provider_error =
std::nullopt);
[[nodiscard]] Result<Snapshot>
resolve(std::string_view service,
ResolvePolicy policy = {}) const;
[[nodiscard]] Result<Registration>
register_local(EndpointRecord record,
LeasePolicy lease = LeasePolicy::unleased());
[[nodiscard]] Result<WatchHandle>
watch(std::string service, std::uint64_t after_revision,
WatchCallback callback, WatchOptions options = {});
/// Process at most `limits.max_expirations_per_turn` logically
/// expired local leases, advancing revision and notifying watches.
std::size_t reap_expired();
/// Remove local entries, stop watch admission, and join admitted
/// callbacks. Destruction alone only requests stop.
[[nodiscard]] Result<void> shutdown_and_join() noexcept;
[[nodiscard]] std::uint64_t revision() const noexcept;
[[nodiscard]] std::uint64_t provider_generation() const noexcept;
[[nodiscard]] std::size_t active_record_count() const noexcept;
[[nodiscard]] std::size_t active_watch_count() const noexcept;
[[nodiscard]] std::size_t shared_watch_event_bytes() const noexcept;
private:
friend class Registration;
friend class WatchHandle;
struct State;
std::shared_ptr<State> m_state;
};
/// Explicit, thread-free lease renewal helper driven by injected steady time.
class ManagedLeaseRenewer final
{
public:
ManagedLeaseRenewer(
Registration& registration,
std::chrono::milliseconds renew_interval =
std::chrono::seconds{10},
const Void::Time::MonotonicClock* clock =
&Void::Time::SystemMonotonicClock::instance()) noexcept;
[[nodiscard]] bool due() const noexcept;
[[nodiscard]] Result<bool> tick();
[[nodiscard]] std::size_t consecutive_failures() const noexcept
{
return m_consecutive_failures;
}
private:
Registration* m_registration{nullptr};
std::chrono::milliseconds m_interval{std::chrono::seconds{10}};
const Void::Time::MonotonicClock* m_clock{
&Void::Time::SystemMonotonicClock::instance()};
Void::Time::MonotonicClock::time_point m_next_renew{};
std::size_t m_consecutive_failures{0};
};
/// Deterministic client-side smooth weighted round-robin selector over an
/// immutable Snapshot.
class WeightedRoundRobinSelector final
{
public:
WeightedRoundRobinSelector() = default;
[[nodiscard]] Result<EndpointRecord>
select(const Snapshot& snapshot);
void reset() noexcept;
private:
mutable std::mutex m_mu{};
std::map<std::string, std::int64_t, std::less<>> m_current_weights{};
};
/// Deterministic client-side affinity selector using weighted Rendezvous
/// (HRW) hashing over `Void::Hash::fnv1a64`.
class AffinitySelector final
{
public:
[[nodiscard]] static Result<EndpointRecord>
select(const Snapshot& snapshot, std::string_view affinity_key);
};
} // namespace Void::Discovery
+245
View File
@@ -0,0 +1,245 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Discovery
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class DiscoveryErrorCode : std::int32_t {
None = 0,
InvalidArgument = 1,
NotFound = 2,
Conflict = 3,
LimitExceeded = 4,
Expired = 5,
Unavailable = 6,
Stale = 7,
Cancelled = 8,
SelfJoin = 9,
Closed = 10,
TlsIdentityMismatch = 11,
};
[[nodiscard]] inline Error make_discovery_error(DiscoveryErrorCode code,
std::string message)
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case DiscoveryErrorCode::None:
kind = ErrorKind::internal;
break;
case DiscoveryErrorCode::InvalidArgument:
case DiscoveryErrorCode::TlsIdentityMismatch:
kind = ErrorKind::invalid_argument;
break;
case DiscoveryErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case DiscoveryErrorCode::Conflict:
case DiscoveryErrorCode::Expired:
case DiscoveryErrorCode::SelfJoin:
kind = ErrorKind::conflict;
break;
case DiscoveryErrorCode::LimitExceeded:
kind = ErrorKind::exhausted;
break;
case DiscoveryErrorCode::Unavailable:
case DiscoveryErrorCode::Stale:
kind = ErrorKind::overloaded;
break;
case DiscoveryErrorCode::Cancelled:
case DiscoveryErrorCode::Closed:
kind = ErrorKind::cancelled;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kDiscoveryErrorDomain,
static_cast<std::int32_t>(code)}};
}
enum class Freshness : std::uint8_t {
Fresh = 0,
Stale = 1,
Unavailable = 2,
};
struct EndpointAddress {
std::string scheme{"http"};
std::string host{};
std::uint16_t port{0};
/// Configured peer identity retained across IP/address refreshes
/// so DNS/address updates cannot downgrade TLS expected-name checks.
std::string expected_tls_name{};
[[nodiscard]] std::string_view effective_tls_name() const noexcept
{
return expected_tls_name.empty()
? std::string_view{host}
: std::string_view{expected_tls_name};
}
[[nodiscard]] std::string to_origin_url() const
{
return scheme + "://" + host + ":" + std::to_string(port);
}
[[nodiscard]] auto
operator<=>(const EndpointAddress&) const noexcept = default;
};
struct EndpointRecord {
std::string instance{};
std::string service{};
EndpointAddress endpoint{};
std::uint32_t weight{1};
bool ready{true};
std::map<std::string, std::string, std::less<>> attributes{};
[[nodiscard]] bool
operator==(const EndpointRecord&) const noexcept = default;
};
struct Snapshot {
std::uint64_t provider_generation{1};
std::uint64_t revision{0};
std::vector<EndpointRecord> records{};
Freshness freshness{Freshness::Fresh};
std::optional<Error> provider_error{};
};
struct ResolvePolicy {
bool allow_stale{false};
bool include_unready{false};
};
struct LeasePolicy {
bool leased{false};
std::chrono::milliseconds ttl{std::chrono::seconds{30}};
std::chrono::milliseconds renew_interval{std::chrono::seconds{10}};
[[nodiscard]] static constexpr LeasePolicy unleased() noexcept
{
return LeasePolicy{
.leased = false,
.ttl = std::chrono::seconds{30},
.renew_interval = std::chrono::seconds{10},
};
}
[[nodiscard]] static constexpr LeasePolicy with_ttl(
std::chrono::milliseconds lease_ttl,
std::chrono::milliseconds renewal =
std::chrono::seconds{10}) noexcept
{
return LeasePolicy{
.leased = true,
.ttl = lease_ttl,
.renew_interval = renewal,
};
}
};
struct CatalogLimits {
std::size_t max_services{1024};
std::size_t max_endpoints_per_service{256};
std::size_t max_total_records{10000};
std::size_t max_attributes_per_record{16};
std::size_t max_metadata_bytes_per_record{4096};
std::size_t max_watches{1024};
std::size_t max_events_per_watch{64};
std::size_t max_shared_event_bytes{16ULL * 1024 * 1024};
std::size_t max_expirations_per_turn{256};
};
enum class WatchEventKind : std::uint8_t {
InitialSnapshot = 0,
Delta = 1,
ResyncRequired = 2,
};
struct WatchEvent {
WatchEventKind kind{WatchEventKind::InitialSnapshot};
std::string service{};
std::uint64_t provider_generation{1};
std::uint64_t revision{0};
std::optional<Snapshot> snapshot{};
std::vector<EndpointRecord> added{};
std::vector<EndpointRecord> updated{};
std::vector<std::string> removed_instances{};
};
using WatchCallback = std::function<void(WatchEvent)>;
enum class WatchDispatchMode : std::uint8_t {
/// Deliver outside catalog locks immediately on admission/mutation.
Inline = 0,
/// Queue events for explicit `WatchHandle::deliver_one()`/`deliver_all()`.
Manual = 1,
/// Serialize delivery on an injected `Void::Async::Executor`.
Executor = 2,
};
struct WatchOptions {
WatchDispatchMode dispatch_mode{WatchDispatchMode::Inline};
Void::Async::Executor* executor{nullptr};
std::size_t max_queued_events{0}; // 0 => CatalogLimits::max_events_per_watch
};
enum class ObservationKind : std::uint8_t {
Resolve = 0,
Register = 1,
Renew = 2,
Release = 3,
Expire = 4,
ReplaceStatic = 5,
WatchResync = 6,
};
/// Bounded low-cardinality observation event (never includes arbitrary
/// per-instance metric labels).
struct ObservationEvent {
ObservationKind kind{ObservationKind::Resolve};
bool ok{true};
std::size_t count{0};
};
using ObservationHook = std::function<void(const ObservationEvent&)>;
struct CatalogOptions {
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
CatalogLimits limits{};
ObservationHook observer{};
};
[[nodiscard]] Result<void>
validate_endpoint_record(const EndpointRecord& record,
const CatalogLimits& limits = {});
[[nodiscard]] std::size_t
estimate_record_bytes(const EndpointRecord& record) noexcept;
[[nodiscard]] std::size_t
estimate_watch_event_bytes(const WatchEvent& event) noexcept;
} // namespace Void::Discovery
@@ -0,0 +1,73 @@
#pragma once
#include <Void/Discovery/Catalog.hpp>
#include <Void/RPC/Rpc.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
namespace Void::DiscoveryRpc
{
struct EndpointResolverOptions {
std::string service{};
/// Optional pinned TLS peer identity. When set, any refreshed
/// endpoint whose effective TLS name differs or attempts to
/// downgrade from `https` is rejected with `TlsIdentityMismatch`.
std::string expected_tls_name{};
bool require_tls{false};
Void::Discovery::ResolvePolicy resolve_policy{};
Void::Net::HttpClientOptions http_options{
.verify_tls = true,
};
Void::RPC::RpcLimits rpc_limits{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
std::size_t max_outstanding_ops{128};
std::chrono::milliseconds total_deadline{std::chrono::seconds{5}};
};
struct SelectedEndpoint {
Void::Discovery::EndpointRecord record{};
std::string origin_url{};
std::string effective_tls_name{};
};
/// Optional RPC endpoint adapter living strictly above `Discovery` and
/// `RPC` (preserving `RPC`'s independence from `Discovery`).
class EndpointResolverClient final
{
public:
EndpointResolverClient(const Void::Discovery::Catalog& catalog,
EndpointResolverOptions options);
[[nodiscard]] Void::Discovery::Result<SelectedEndpoint>
select_endpoint(
std::optional<std::string_view> affinity_key = std::nullopt);
[[nodiscard]] Void::Result::Result<Void::RPC::OwnedBytes>
call(Void::RPC::MethodId method,
Void::RPC::OwnedBytes payload,
Void::RPC::CallOptions options = {},
std::optional<std::string_view> affinity_key =
std::nullopt);
[[nodiscard]] std::size_t outstanding_ops() const noexcept
{
return m_outstanding.load(std::memory_order_acquire);
}
private:
const Void::Discovery::Catalog* m_catalog{nullptr};
EndpointResolverOptions m_options{};
Void::Discovery::WeightedRoundRobinSelector m_rr{};
std::atomic<std::size_t> m_outstanding{0};
};
} // namespace Void::DiscoveryRpc
+6
View File
@@ -76,6 +76,12 @@ namespace Void::Result
inline constexpr std::uint32_t kConfigurationErrorDomain = 24;
inline constexpr std::uint32_t kFsmErrorDomain = 25;
inline constexpr std::uint32_t kNetErrorDomain = 26;
inline constexpr std::uint32_t kTestingMockErrorDomain = 27;
inline constexpr std::uint32_t kShortUrlErrorDomain = 28;
inline constexpr std::uint32_t kRpcErrorDomain = 29;
inline constexpr std::uint32_t kDiscoveryErrorDomain = 30;
inline constexpr std::uint32_t kSchedulerErrorDomain = 31;
inline constexpr std::uint32_t kMessagingErrorDomain = 32;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
+181 -2
View File
@@ -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
+416
View File
@@ -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
+51
View File
@@ -3,15 +3,19 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/File.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <vector>
namespace Void::IO
@@ -23,6 +27,7 @@ namespace detail
{
class StreamState;
class FileState;
enum class Direction {
read,
@@ -73,6 +78,52 @@ public:
[[nodiscard]] virtual Void::Result::Result<void> shutdown_and_join() = 0;
[[nodiscard]] virtual DriverTelemetry telemetry() const noexcept = 0;
// ── Positional files (bounded worker pool shared by every backend) ──────
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<FileState>>
open_file(const std::filesystem::path& path, const FileOpenOptions& options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<FileState>>
adopt_file_fd(int fd) = 0;
[[nodiscard]] virtual Void::Result::Result<void> start_file_workers() = 0;
[[nodiscard]] virtual Void::Result::Result<std::size_t>
run_file_work(std::size_t max_requests) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_file_read(const std::shared_ptr<FileState>& file,
std::uint64_t offset,
std::span<std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<Transfer>>>
submit_file_write(const std::shared_ptr<FileState>& file,
std::uint64_t offset,
std::span<const std::byte> buf,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
submit_file_sync(const std::shared_ptr<FileState>& file,
SyncMode mode,
Async::OperationOptions options) = 0;
[[nodiscard]] virtual Void::Result::Result<std::shared_ptr<Async::OperationState<void>>>
submit_file_close(const std::shared_ptr<FileState>& file,
Async::OperationOptions options) = 0;
// ── Bounded shutdown core ────────────────────────────────────────────────
// Idempotent: closes admission, cancels queued requests and records stop
// intent for active ones, then wakes the poller. Never completes,
// dispatches or frees anything itself.
virtual void begin_shutdown() noexcept = 0;
// Drives shutdown until complete, the injected-clock deadline passes or
// `stop` fires; the latter two return the current report with
// complete == false (not an error). Returns
// Async::make_async_error(AdmissionError::self_join) on one of this
// backend's file workers or inside one of its poll turns.
[[nodiscard]] virtual Void::Result::Result<DriverShutdownReport> advance_shutdown(
std::optional<Void::Time::MonotonicClock::time_point> deadline,
std::stop_token stop) = 0;
[[nodiscard]] virtual bool shutdown_complete() const noexcept = 0;
// No owned operations, file requests or in-flight syscalls remain.
[[nodiscard]] virtual bool quiescent() const noexcept = 0;
// Driver::~Driver only: begin + advance to completion (blocking).
virtual void teardown_blocking() noexcept = 0;
// Mock inspection / test-only control hooks (returns nullptr on non-mock backends).
[[nodiscard]] virtual class MockBackend* as_mock() noexcept { return nullptr; }
};
+133
View File
@@ -2,17 +2,23 @@
#include <Void/Async/Executor.hpp>
#include <Void/IO/Detail/Backend.hpp>
#include <Void/IO/File.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <memory_resource>
#include <mutex>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <utility>
@@ -56,6 +62,22 @@ private:
detail::MockBackend* backend_{nullptr};
};
// True on any Driver's file-worker thread (never on poll or executor threads).
[[nodiscard]] bool is_io_worker_thread() noexcept;
// The Driver owns no thread except its optional file workers. One thread at a
// time runs a poll_once turn (the poll owner); a concurrent or reentrant
// poll_once returns IoErrorCode::busy without touching any descriptor.
//
// Lifetime rules:
// - The executor must outlive the Driver. Resume tickets produced by
// shutdown/teardown are dispatched to it after poll ownership is released,
// so an owned executor must not be joined before Driver teardown.
// - ~Driver is the only blocking teardown: it begins shutdown, waits for
// in-flight syscalls and file requests, joins file workers, closes file and
// operation descriptors and delivers every pending result exactly once.
// Destroying a Driver on one of its file workers or inside one of its poll
// turns is a programmer error: it prints a diagnostic and terminates.
class Driver
{
public:
@@ -92,9 +114,120 @@ public:
std::optional<std::chrono::nanoseconds> max_wait = std::chrono::nanoseconds{0});
void wake() noexcept;
// Equivalent to begin_shutdown().
void request_stop() noexcept;
// Blocks until shutdown is complete (shutdown with no deadline or stop).
// Returns self_join on a file worker or inside a poll turn of this Driver.
[[nodiscard]] Void::Result::Result<void> shutdown_and_join();
// ── Positional files ─────────────────────────────────────────────────────
[[nodiscard]] Void::Result::Result<File> open_file(
const std::filesystem::path& path, FileOpenOptions options = {});
// Takes ownership of `fd` only on success.
[[nodiscard]] Void::Result::Result<File> adopt_file_fd(int fd);
// Starts IoLimits::file_workers threads once (0 = none, manual stepping).
// A second call is invalid_argument; after shutdown begins it is closed; a
// failed start joins the workers already started and may be retried.
[[nodiscard]] Void::Result::Result<void> start_file_workers();
// Runs up to `max_requests` queued file syscalls on the calling thread and
// queues their results for the next poll turn; busy while workers run.
[[nodiscard]] Void::Result::Result<std::size_t> run_file_work(std::size_t max_requests = 1);
// ── Bounded shutdown ─────────────────────────────────────────────────────
// Idempotent; closes admission, cancels queued requests, records stop
// intent for active ones and wakes the poller. Never blocks or frees.
void begin_shutdown() noexcept { backend_->begin_shutdown(); }
// Advances shutdown until complete, or until options.deadline (judged by
// clock()) or options.stop, which return complete == false with every
// listed resource retained. Repeatable.
[[nodiscard]] Void::Result::Result<DriverShutdownReport> shutdown(
Async::OperationOptions options)
{
return backend_->advance_shutdown(options.deadline, std::move(options.stop));
}
[[nodiscard]] bool quiescent() const noexcept { return backend_->quiescent(); }
[[nodiscard]] bool shutdown_complete() const noexcept
{
return backend_->shutdown_complete();
}
/// Runs the poll loop until `stop` is requested, `shutdown_complete()` becomes
/// true, or an unrecoverable error occurs. Retries `IoErrorCode::busy` and
/// idle mock turns with short stop-aware waits so the loop never busy-spins.
[[nodiscard]] Void::Result::Result<std::size_t> run(
std::stop_token stop,
std::chrono::nanoseconds max_wait = std::chrono::milliseconds{5})
{
if (max_wait < std::chrono::nanoseconds{0}) {
max_wait = std::chrono::nanoseconds{0};
}
auto wait_stop_aware = [&](std::chrono::nanoseconds budget) {
if (budget <= std::chrono::nanoseconds{0} ||
stop.stop_requested() || shutdown_complete()) {
return;
}
std::mutex mu;
std::condition_variable cv;
std::stop_callback cb(stop, [&]() noexcept {
std::lock_guard lk{mu};
cv.notify_all();
});
std::unique_lock lk{mu};
auto remaining = budget;
constexpr auto kSlice =
std::chrono::nanoseconds{std::chrono::milliseconds{1}};
while (remaining > std::chrono::nanoseconds{0} &&
!stop.stop_requested() && !shutdown_complete()) {
const auto step = std::min(remaining, kSlice);
cv.wait_for(lk, step, [&]() {
return stop.stop_requested() || shutdown_complete();
});
remaining -= step;
}
};
std::size_t total = 0;
std::size_t consecutive_fast_zero = 0;
while (!stop.stop_requested() && !shutdown_complete()) {
const auto poll_start = std::chrono::steady_clock::now();
auto res = poll_once(max_wait);
const auto poll_elapsed = std::chrono::steady_clock::now() - poll_start;
if (!res.has_value()) {
if (res.error().code().domain == Void::Result::kIoErrorDomain &&
res.error().code().value ==
static_cast<std::int32_t>(IoErrorCode::busy)) {
consecutive_fast_zero = 0;
const auto busy_slice =
max_wait > std::chrono::nanoseconds{0}
? std::min(max_wait,
std::chrono::nanoseconds{
std::chrono::milliseconds{1}})
: std::chrono::nanoseconds{
std::chrono::microseconds{200}};
wait_stop_aware(busy_slice);
continue;
}
return std::unexpected{std::move(res.error())};
}
total += *res;
if (*res == 0 && max_wait > std::chrono::nanoseconds{0} &&
poll_elapsed < max_wait) {
const auto remain = std::chrono::duration_cast<std::chrono::nanoseconds>(
max_wait - poll_elapsed);
if (active_backend() == BackendPreference::mock) {
wait_stop_aware(remain);
} else if (++consecutive_fast_zero >= 2) {
wait_stop_aware(std::min(
remain,
std::chrono::nanoseconds{std::chrono::milliseconds{1}}));
}
} else {
consecutive_fast_zero = 0;
}
}
return total;
}
private:
Driver(std::shared_ptr<detail::DriverBackend> backend,
std::shared_ptr<detail::OwnedBufferTracker> buffer_tracker) noexcept;
+198
View File
@@ -0,0 +1,198 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/IO/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <span>
#include <utility>
namespace Void::IO
{
// Flags for Driver::open_file. read+write maps to O_RDWR, write-only to
// O_WRONLY and read-only to O_RDONLY; neither read nor write, truncate without
// write, or exclusive without create is invalid_argument. O_CLOEXEC is always
// set and open(2) runs on the calling thread with ordinary path semantics.
struct FileOpenOptions {
bool read{true};
bool write{false};
bool create{false};
bool truncate{false};
bool exclusive{false};
std::uint32_t mode{0600};
};
enum class SyncMode : std::uint8_t {
data, // fdatasync
full // fsync
};
// Result of one positional-file syscall: on success `error == 0` and `value`
// holds the byte count (0 for sync/close); on failure `error` is the errno.
struct FileSyscallResult {
std::int64_t value{0};
int error{0};
};
// Injectable syscall shim used by the Driver's file workers. The base class
// is the native implementation (one syscall per call, no EINTR retry; the
// Driver retries EINTR). An override runs on file workers or inside
// Driver::run_file_work(); it must not call Driver, Executor or File APIs, and
// it must outlive Driver teardown (teardown closes remaining fds through it).
class FileSyscalls
{
public:
virtual ~FileSyscalls() = default;
[[nodiscard]] virtual FileSyscallResult pread(
int fd, std::span<std::byte> buf, std::uint64_t offset) noexcept;
[[nodiscard]] virtual FileSyscallResult pwrite(
int fd, std::span<const std::byte> buf, std::uint64_t offset) noexcept;
[[nodiscard]] virtual FileSyscallResult sync(int fd, SyncMode mode) noexcept;
[[nodiscard]] virtual FileSyscallResult close(int fd) noexcept;
[[nodiscard]] static FileSyscalls& native() noexcept;
};
namespace detail
{
class FileState;
} // namespace detail
// Move-only handle to a positional file owned by a Driver. Requests run on
// the Driver's bounded file workers (or Driver::run_file_work) and are
// delivered only by a poll turn.
//
// - Writes and syncs on one File run in admission order, one at a time; reads
// may run concurrently and are unordered relative to writes.
// - A queued request that is stopped or expires completes cancelled/timeout
// without a syscall. An active request keeps its buffer and reports the
// syscall's actual outcome even after stop or expiry.
// - Dropping a File with requests in flight defers the close until they have
// been delivered; the close never blocks the dropping thread.
// - Unlike ByteStream::close_and_join (which consumes the stream at once),
// File::close_and_join waits for the file's queued and active requests,
// never cancels them, and invalidates the File only on success. On deadline
// or stop it returns incomplete_shutdown and the File stays valid but
// closing (new requests fail with closed; a repeated call waits again).
// - After Driver teardown every request fails with closed without a syscall
// and close_and_join succeeds immediately.
class File
{
public:
File() noexcept;
File(File&& other) noexcept;
File& operator=(File&& other) noexcept;
~File();
File(const File&) = delete;
File& operator=(const File&) = delete;
[[nodiscard]] bool valid() const noexcept { return state_ != nullptr; }
[[nodiscard]] DescriptorId id() const noexcept;
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at(
std::uint64_t offset, std::span<std::byte> buf, Async::OperationOptions options = {});
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at(
std::uint64_t offset, std::span<const std::byte> buf, Async::OperationOptions options = {});
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> read_at_owned(
std::uint64_t offset, BufferLease& lease, Async::OperationOptions options = {})
{
auto res = co_await read_at(offset, lease.writable(), std::move(options));
if (res.has_value()) {
lease.set_valid_bytes(res->bytes);
}
co_return res;
}
[[nodiscard]] Coro::Task<Void::Result::Result<Transfer>> write_at_owned(
std::uint64_t offset, const BufferLease& lease, Async::OperationOptions options = {})
{
co_return co_await write_at(offset, lease.readable(), std::move(options));
}
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sync(
SyncMode mode = SyncMode::full, Async::OperationOptions options = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> close_and_join(
Async::OperationOptions options = {});
private:
friend class Driver; // the only producer of open Files
explicit File(std::shared_ptr<detail::FileState> state) noexcept;
void release_handle() noexcept;
std::shared_ptr<detail::FileState> state_{};
};
// Composed positional transfers mirroring read_exact/write_all: the offset
// advances with each chunk and one deadline/stop applies to the whole call.
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
read_exact_at(File& file,
std::uint64_t offset,
std::span<std::byte> buf,
Async::OperationOptions options = {})
{
std::size_t total = 0;
while (total < buf.size()) {
if (options.stop.stop_requested()) {
co_return std::unexpected{ComposedTransferError{
total,
false,
make_io_error(IoErrorCode::cancelled, "read_exact_at stopped before completion")}};
}
const auto chunk = co_await file.read_at(offset + total, buf.subspan(total), options);
if (!chunk.has_value()) {
co_return std::unexpected{ComposedTransferError{total, false, chunk.error()}};
}
total += chunk->bytes;
if (total < buf.size() && chunk->eof) {
co_return std::unexpected{ComposedTransferError{
total,
true,
make_io_error(IoErrorCode::eof, "Unexpected EOF before read_exact_at finished")}};
}
}
co_return total;
}
[[nodiscard]] inline Coro::Task<std::expected<std::size_t, ComposedTransferError>>
write_all_at(File& file,
std::uint64_t offset,
std::span<const std::byte> buf,
Async::OperationOptions options = {})
{
std::size_t total = 0;
while (total < buf.size()) {
if (options.stop.stop_requested()) {
co_return std::unexpected{ComposedTransferError{
total,
false,
make_io_error(IoErrorCode::cancelled, "write_all_at stopped before completion")}};
}
const auto chunk = co_await file.write_at(offset + total, buf.subspan(total), options);
if (!chunk.has_value()) {
co_return std::unexpected{ComposedTransferError{total, false, chunk.error()}};
}
if (chunk->bytes == 0) {
// A zero-byte pwrite with bytes remaining makes no progress; report
// it instead of looping.
co_return std::unexpected{ComposedTransferError{
total,
false,
make_io_error(IoErrorCode::os_error, "pwrite made no progress in write_all_at")}};
}
total += chunk->bytes;
}
co_return total;
}
} // namespace Void::IO
+150
View File
@@ -0,0 +1,150 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <chrono>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <stop_token>
#include <utility>
namespace Void::IO
{
struct PumpOptions {
std::chrono::nanoseconds max_wait{0};
std::size_t max_turns{1u << 20};
Async::OperationOptions operation{};
Async::TimerQueue* timers{nullptr};
};
/// Drives `driver.poll_once`, `options.timers->poll_expired()`, and
/// `manual.drain()` until `done()` returns true, `driver.shutdown_complete()`
/// becomes true, stop/deadline fires, or `max_turns` is exceeded.
template <class Done>
requires std::predicate<Done&>
[[nodiscard]] Void::Result::Result<std::size_t> pump_until(
Driver& driver,
Async::ManualExecutor& manual,
Done&& done,
PumpOptions options = {})
{
const auto wait_stop_aware = [&](std::chrono::nanoseconds slice) {
if (slice <= std::chrono::nanoseconds{0} ||
options.operation.stop.stop_requested() ||
driver.shutdown_complete()) {
return;
}
std::mutex mu;
std::condition_variable cv;
std::stop_callback cb(options.operation.stop, [&]() noexcept {
std::lock_guard lk{mu};
cv.notify_all();
});
std::unique_lock lk{mu};
cv.wait_for(lk, slice, [&]() {
return options.operation.stop.stop_requested() ||
driver.shutdown_complete();
});
};
const auto base_wait =
options.max_wait < std::chrono::nanoseconds{0}
? std::chrono::nanoseconds{0}
: options.max_wait;
std::size_t total_work = 0;
std::size_t turns = 0;
for (;;) {
if (done()) {
return total_work;
}
if (options.operation.stop.stop_requested()) {
return std::unexpected{make_io_error(
IoErrorCode::cancelled, "pump_until stop requested")};
}
if (Async::is_deadline_expired(options.operation, driver.clock())) {
return std::unexpected{make_io_error(
IoErrorCode::timeout, "pump_until deadline expired")};
}
if (turns >= options.max_turns) {
return std::unexpected{make_io_error(
IoErrorCode::exhausted, "pump_until max_turns exceeded")};
}
++turns;
std::chrono::nanoseconds wait = base_wait;
if (!manual.empty()) {
wait = std::chrono::nanoseconds{0};
} else if (options.timers != nullptr) {
wait = options.timers->wait_duration(base_wait);
}
if (options.operation.deadline.has_value()) {
const auto rem = Void::Time::remaining_until(
driver.clock(), *options.operation.deadline);
if (rem <= std::chrono::nanoseconds{0}) {
return std::unexpected{make_io_error(
IoErrorCode::timeout, "pump_until deadline expired")};
}
wait = std::min(wait, rem);
}
if (wait < std::chrono::nanoseconds{0}) {
wait = std::chrono::nanoseconds{0};
}
const auto poll_start = std::chrono::steady_clock::now();
auto poll_res = driver.poll_once(wait);
const auto poll_elapsed = std::chrono::steady_clock::now() - poll_start;
if (!poll_res.has_value()) {
if (poll_res.error().code().domain == Void::Result::kIoErrorDomain &&
poll_res.error().code().value ==
static_cast<std::int32_t>(IoErrorCode::busy)) {
const auto slice =
wait > std::chrono::nanoseconds{0}
? std::min(wait,
std::chrono::nanoseconds{
std::chrono::milliseconds{1}})
: std::chrono::nanoseconds{
std::chrono::microseconds{200}};
wait_stop_aware(slice);
continue;
}
return std::unexpected{std::move(poll_res.error())};
}
std::size_t turn_work = *poll_res;
if (options.timers != nullptr) {
turn_work += options.timers->poll_expired();
}
turn_work += manual.drain();
total_work += turn_work;
if (done()) {
return total_work;
}
if (driver.shutdown_complete()) {
return total_work;
}
if (turn_work == 0 && manual.empty() &&
wait > std::chrono::nanoseconds{0} && poll_elapsed < wait) {
const auto remain = std::chrono::duration_cast<std::chrono::nanoseconds>(
wait - poll_elapsed);
const auto slice = std::min(
remain,
std::chrono::nanoseconds{std::chrono::milliseconds{1}});
wait_stop_aware(slice);
}
}
}
} // namespace Void::IO
+33 -1
View File
@@ -7,6 +7,7 @@
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <memory_resource>
#include <new>
@@ -30,7 +31,8 @@ enum class IoErrorCode : std::int32_t {
invalid_argument = 8,
os_error = 9,
incomplete_shutdown = 10,
exhausted = 11
exhausted = 11,
sync_failed = 12
};
[[nodiscard]] inline Void::Result::Error make_io_error(
@@ -66,6 +68,7 @@ enum class IoErrorCode : std::int32_t {
break;
case IoErrorCode::eof:
case IoErrorCode::os_error:
case IoErrorCode::sync_failed:
kind = ErrorKind::io;
break;
case IoErrorCode::invalid_argument:
@@ -118,6 +121,11 @@ struct IoLimits {
IoErrorCode::invalid_argument,
"IoLimits descriptor, operation, control, and turn bounds must be non-zero")};
}
if (limits.max_file_queue == 0) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument,
"IoLimits max_file_queue must be non-zero")};
}
return {};
}
@@ -127,9 +135,18 @@ enum class BackendPreference {
mock
};
class FileSyscalls;
struct BackendOptions {
IoLimits limits{};
BackendPreference preference{BackendPreference::auto_native};
// Borrowed positional-file syscall shim (nullptr = FileSyscalls::native()).
// It runs on file workers or in run_file_work(), must not call Driver,
// Executor or File APIs, and must outlive Driver teardown.
FileSyscalls* file_syscalls{nullptr};
// Called before each file worker thread is created with its index; an
// error aborts start_file_workers() exactly like a thread-creation failure.
std::function<Void::Result::Result<void>(std::size_t)> before_file_worker_start{};
};
struct DescriptorId {
@@ -148,6 +165,21 @@ struct DriverTelemetry {
std::uint64_t turns{0};
std::uint64_t wakeups{0};
std::uint64_t stale_events_ignored{0};
std::size_t queued_file_requests{0};
std::size_t active_file_requests{0};
std::size_t file_workers_running{0};
// Cancel/expiry/shutdown paths that met an already-retired op and skipped it.
std::uint64_t duplicate_completions_ignored{0};
};
// Snapshot returned by Driver::shutdown(). `complete == false` means the
// bounded call expired (deadline or stop) and everything listed is retained.
struct DriverShutdownReport {
bool complete{false};
std::size_t pending_operations{0};
std::size_t active_file_requests{0};
std::size_t open_descriptors{0};
std::size_t retained_buffer_bytes{0};
};
namespace detail
+180
View File
@@ -0,0 +1,180 @@
#pragma once
#include <Void/Messaging/Types.hpp>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Messaging
{
/// Abstract queue interface implemented by both explicitly nondurable
/// `InMemoryQueue` and durable `MessagingStorage::StorageQueue`.
class Queue
{
public:
virtual ~Queue() = default;
[[nodiscard]] virtual Result<void>
create_queue(QueueConfig config) = 0;
[[nodiscard]] virtual Result<void>
create_group(std::string_view queue, GroupConfig config) = 0;
[[nodiscard]] virtual Result<PublishReceipt> publish(
std::string_view queue, Message message,
PublishDurability durability,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<std::optional<Delivery>>
try_receive(std::string_view queue, std::string_view group) = 0;
[[nodiscard]] virtual Result<Delivery> receive(
std::string_view queue, std::string_view group,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<void>
ack(const Receipt& receipt,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<void> nack(
const Receipt& receipt,
std::optional<std::chrono::milliseconds> delay = std::nullopt,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<Void::Time::MonotonicClock::time_point>
extend_visibility(
const Receipt& receipt, std::chrono::milliseconds extension,
Void::Async::OperationOptions options = {}) = 0;
/// Quarantine an unparseable or schema-incompatible message into
/// DLQ without falsely acknowledging it as processed.
[[nodiscard]] virtual Result<void> quarantine_corrupt(
const Receipt& receipt, std::string reason,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<DeliveryState>
query_receipt(const Receipt& receipt) const = 0;
[[nodiscard]] virtual Result<std::vector<DeadLetterEntry>>
list_dead_letters(std::string_view queue,
std::string_view group,
std::size_t limit = 100) const = 0;
[[nodiscard]] virtual std::size_t
stuck_dlq_count(std::string_view queue,
std::string_view group) const noexcept = 0;
/// Reclaim expired `InFlight` deliveries into `Pending` (with retry
/// backoff) or atomically move exhausted messages to DLQ.
[[nodiscard]] virtual Result<std::size_t>
reap_expired_visibility() = 0;
/// Apply configured retention policy (paused when civil clock
/// health is degraded).
[[nodiscard]] virtual Result<std::size_t> expire_retention() = 0;
virtual void set_clock_healthy(bool healthy) noexcept = 0;
[[nodiscard]] virtual Result<ShutdownReport> close_and_join(
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<QueueStats> stats() const = 0;
};
struct InMemoryQueueOptions {
QueueLimits limits{};
const Void::Time::MonotonicClock* monotonic_clock{
&Void::Time::SystemMonotonicClock::instance()};
const Void::Time::CivilClock* civil_clock{
&Void::Time::SystemCivilClock::instance()};
RandomU64Fn rng{};
};
/// Explicitly nondurable in-process queue implementing the full native
/// delivery state machine (`PublishDurability::Durable` is rejected with
/// `UnsupportedDurability`).
class InMemoryQueue final : public Queue
{
public:
explicit InMemoryQueue(InMemoryQueueOptions options = {});
~InMemoryQueue() noexcept override;
InMemoryQueue(InMemoryQueue&&) noexcept;
InMemoryQueue& operator=(InMemoryQueue&&) noexcept;
InMemoryQueue(const InMemoryQueue&) = delete;
InMemoryQueue& operator=(const InMemoryQueue&) = delete;
[[nodiscard]] Result<void> create_queue(QueueConfig config) override;
[[nodiscard]] Result<void>
create_group(std::string_view queue,
GroupConfig config) override;
[[nodiscard]] Result<PublishReceipt> publish(
std::string_view queue, Message message,
PublishDurability durability,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<std::optional<Delivery>>
try_receive(std::string_view queue,
std::string_view group) override;
[[nodiscard]] Result<Delivery> receive(
std::string_view queue, std::string_view group,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<void>
ack(const Receipt& receipt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<void> nack(
const Receipt& receipt,
std::optional<std::chrono::milliseconds> delay = std::nullopt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<Void::Time::MonotonicClock::time_point>
extend_visibility(
const Receipt& receipt, std::chrono::milliseconds extension,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<void> quarantine_corrupt(
const Receipt& receipt, std::string reason,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<DeliveryState>
query_receipt(const Receipt& receipt) const override;
[[nodiscard]] Result<std::vector<DeadLetterEntry>>
list_dead_letters(std::string_view queue,
std::string_view group,
std::size_t limit = 100) const override;
[[nodiscard]] std::size_t
stuck_dlq_count(std::string_view queue,
std::string_view group) const noexcept override;
[[nodiscard]] Result<std::size_t>
reap_expired_visibility() override;
[[nodiscard]] Result<std::size_t> expire_retention() override;
void set_clock_healthy(bool healthy) noexcept override;
[[nodiscard]] Result<ShutdownReport> close_and_join(
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<QueueStats> stats() const override;
private:
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::Messaging
+260
View File
@@ -0,0 +1,260 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Messaging
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class MessagingErrorCode : std::int32_t {
None = 0,
InvalidArgument = 1,
NotFound = 2,
Conflict = 3,
StaleReceipt = 4,
Overloaded = 5,
QuotaExceeded = 6,
IdempotencyCapacityExceeded = 7,
DlqFull = 8,
UnsupportedDurability = 9,
CorruptPayload = 10,
PersistenceError = 11,
UnknownOutcome = 12,
Cancelled = 13,
Timeout = 14,
Closed = 15,
};
[[nodiscard]] inline Error make_messaging_error(MessagingErrorCode code,
std::string message)
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case MessagingErrorCode::None:
kind = ErrorKind::internal;
break;
case MessagingErrorCode::InvalidArgument:
kind = ErrorKind::invalid_argument;
break;
case MessagingErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case MessagingErrorCode::Conflict:
case MessagingErrorCode::StaleReceipt:
case MessagingErrorCode::UnknownOutcome:
kind = ErrorKind::conflict;
break;
case MessagingErrorCode::Overloaded:
kind = ErrorKind::overloaded;
break;
case MessagingErrorCode::QuotaExceeded:
case MessagingErrorCode::IdempotencyCapacityExceeded:
case MessagingErrorCode::DlqFull:
kind = ErrorKind::exhausted;
break;
case MessagingErrorCode::UnsupportedDurability:
kind = ErrorKind::unsupported;
break;
case MessagingErrorCode::CorruptPayload:
kind = ErrorKind::corrupt;
break;
case MessagingErrorCode::PersistenceError:
kind = ErrorKind::io;
break;
case MessagingErrorCode::Cancelled:
case MessagingErrorCode::Closed:
kind = ErrorKind::cancelled;
break;
case MessagingErrorCode::Timeout:
kind = ErrorKind::timeout;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kMessagingErrorDomain,
static_cast<std::int32_t>(code)}};
}
/// Explicit publish durability contract. Nondurable queues must reject
/// `PublishDurability::Durable` rather than returning a false durable OK.
enum class PublishDurability : std::uint8_t {
Memory = 0,
Durable = 1,
};
enum class ConsumerMode : std::uint8_t {
Competing = 0,
SingleActive = 1,
};
enum class RetentionPolicy : std::uint8_t {
/// Initial default: block further publish at quota rather than silently
/// expiring unread work.
BlockAtQuota = 0,
/// Explicit opt-in lossy mode allowing retention expiry of unread work.
DropOldestLossy = 1,
};
enum class DeliveryState : std::uint8_t {
Pending = 0,
InFlight = 1,
Acked = 2,
DeadLetter = 3,
};
struct Message {
std::string id{};
std::vector<std::byte> payload{};
std::map<std::string, std::string, std::less<>> headers{};
std::uint32_t schema_version{1};
[[nodiscard]] bool
operator==(const Message&) const noexcept = default;
};
struct Receipt {
std::string queue{};
std::string group{};
std::string message_id{};
std::uint64_t sequence{0};
std::uint64_t generation{0};
[[nodiscard]] auto
operator<=>(const Receipt&) const noexcept = default;
};
struct PublishReceipt {
std::string queue{};
std::string message_id{};
std::uint64_t sequence{0};
PublishDurability durability{PublishDurability::Memory};
bool deduplicated{false};
};
struct Delivery {
Message message{};
Receipt receipt{};
std::uint32_t attempt{1};
Void::Time::MonotonicClock::time_point visibility_deadline{};
};
struct DeadLetterEntry {
Message message{};
std::string queue{};
std::string group{};
std::uint64_t sequence{0};
std::uint32_t attempts{0};
std::string reason{};
std::int64_t dead_lettered_utc_ms{0};
};
struct RetryPolicy {
std::uint32_t max_attempts{5};
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
std::chrono::milliseconds max_delay{std::chrono::seconds{60}};
};
struct QueueLimits {
std::size_t max_message_bytes{768ULL * 1024};
std::size_t max_headers_bytes{8ULL * 1024};
std::size_t max_header_count{32};
std::size_t max_queues{1024};
std::size_t max_groups_per_queue{32};
std::size_t max_in_flight_per_group{64};
std::size_t max_waiting_receives{1024};
std::size_t max_transient_payload_bytes{64ULL * 1024 * 1024};
std::uint64_t persistent_quota_bytes{1024ULL * 1024 * 1024};
std::size_t max_dlq_messages{10000};
std::chrono::milliseconds idempotency_retention{
std::chrono::hours{24}};
std::size_t max_idempotency_entries{100000};
std::chrono::milliseconds default_visibility_timeout{
std::chrono::seconds{30}};
std::chrono::milliseconds max_visibility_extension{
std::chrono::minutes{5}};
std::chrono::milliseconds logical_retention{
std::chrono::hours{24 * 7}};
std::chrono::milliseconds shutdown_drain_timeout{
std::chrono::seconds{10}};
};
struct QueueConfig {
std::string name{};
RetentionPolicy retention_policy{RetentionPolicy::BlockAtQuota};
RetryPolicy retry{};
};
struct GroupConfig {
std::string name{};
ConsumerMode mode{ConsumerMode::Competing};
std::chrono::milliseconds visibility_timeout{
std::chrono::seconds{30}};
std::size_t max_in_flight{64};
};
struct QueueStats {
std::size_t queues{0};
std::size_t pending{0};
std::size_t in_flight{0};
std::size_t acked{0};
std::size_t dead_letter{0};
std::size_t stuck_dlq{0};
std::uint64_t retained_bytes{0};
std::size_t idempotency_entries{0};
};
struct ShutdownReport {
bool complete{true};
std::size_t remaining_in_flight{0};
};
using RandomU64Fn = std::function<std::uint64_t()>;
[[nodiscard]] Result<void>
validate_identifier(std::string_view name, std::string_view label);
[[nodiscard]] Result<void> validate_message(const Message& message,
const QueueLimits& limits);
[[nodiscard]] std::size_t
estimate_message_bytes(const Message& message) noexcept;
[[nodiscard]] std::int64_t
compute_retry_backoff_ms(const RetryPolicy& retry,
std::uint32_t attempt,
const RandomU64Fn& rng);
[[nodiscard]] inline std::int64_t
to_mono_ns(Void::Time::MonotonicClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
tp.time_since_epoch())
.count();
}
[[nodiscard]] inline std::int64_t
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch())
.count();
}
} // namespace Void::Messaging
+89
View File
@@ -0,0 +1,89 @@
#pragma once
#include <Void/Messaging/Queue.hpp>
#include <Void/RPC/Rpc.hpp>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::MessagingRpc
{
inline constexpr std::uint64_t kMessagingRpcServiceId = 0x564D534752504301ULL;
inline constexpr Void::RPC::MethodId kPublishMethod{
kMessagingRpcServiceId, 1U};
inline constexpr Void::RPC::MethodId kTryReceiveMethod{
kMessagingRpcServiceId, 2U};
inline constexpr Void::RPC::MethodId kAckMethod{
kMessagingRpcServiceId, 3U};
inline constexpr Void::RPC::MethodId kNackMethod{
kMessagingRpcServiceId, 4U};
inline constexpr Void::RPC::MethodId kQueryReceiptMethod{
kMessagingRpcServiceId, 5U};
/// Mounts remote Messaging operations (`publish`, `try_receive`, `ack`,
/// `nack`, `query_receipt`) onto a `Void::RPC::Server`.
class RpcQueueServer final
{
public:
RpcQueueServer() = default;
~RpcQueueServer() noexcept;
RpcQueueServer(RpcQueueServer&&) noexcept = default;
RpcQueueServer& operator=(RpcQueueServer&&) noexcept = default;
RpcQueueServer(const RpcQueueServer&) = delete;
RpcQueueServer& operator=(const RpcQueueServer&) = delete;
[[nodiscard]] Void::Messaging::Result<void>
mount(Void::RPC::Server& server,
Void::Messaging::Queue& queue);
void unmount_and_drain() noexcept;
private:
std::vector<Void::RPC::Registration> m_registrations{};
};
/// Remote client executing Messaging operations over unary `Void::RPC::Client`,
/// propagating `UnknownOutcome` faithfully when network replies are lost.
class RpcQueueClient final
{
public:
explicit RpcQueueClient(Void::RPC::ClientOptions options);
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
publish(std::string_view queue,
const Void::Messaging::Message& message,
Void::Messaging::PublishDurability durability,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<
std::optional<Void::Messaging::Delivery>>
try_receive(std::string_view queue, std::string_view group,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<void>
ack(const Void::Messaging::Receipt& receipt,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<void>
nack(const Void::Messaging::Receipt& receipt,
std::optional<std::chrono::milliseconds> delay =
std::nullopt,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
query_receipt(const Void::Messaging::Receipt& receipt,
const Void::RPC::CallOptions& options = {});
private:
Void::RPC::Client m_client;
};
} // namespace Void::MessagingRpc
@@ -0,0 +1,260 @@
#pragma once
#include <Void/Messaging/Queue.hpp>
#include <Void/Storage/Batch.hpp>
#include <Void/Storage/Engine.hpp>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
namespace Void::MessagingStorage
{
struct OutboxRecord {
std::string outbox_id{};
std::string target_queue{};
Void::Messaging::Message message{};
};
/// Atomic local-batch helpers for the Outbox and Inbox patterns over a
/// single shared `Void::Storage::Engine`.
///
/// Boundary guarantee:
/// - Business state + outbox insert (or consumer state + inbox dedup key)
/// commit atomically ONLY within the same `Void::Storage::Batch`.
/// - External effects (email, HTTP/RPC calls, separate databases) remain
/// strictly outside this batch boundary and still require downstream
/// idempotency or compensation.
class OutboxInbox final
{
public:
static void append_outbox_in_batch(
Void::Storage::Batch& batch, const OutboxRecord& record,
std::string_view prefix = "outbox:v1:")
{
const std::string key =
std::string{prefix} + record.outbox_id;
batch.require_absent(key);
batch.put(key, encode_outbox(record));
}
/// Record inbox deduplication key inside the consumer's SAME
/// `Void::Storage::Batch` as its local business mutation. If the
/// message was already applied, the batch fails with `Conflict`
/// (duplicate prevented atomically).
static void apply_inbox_in_batch(
Void::Storage::Batch& batch, std::string_view consumer_id,
std::string_view message_id,
std::string_view prefix = "inbox:v1:")
{
const std::string key = std::string{prefix} +
std::string{consumer_id} + "\x1F" +
std::string{message_id};
batch.require_absent(key);
batch.put(key, "1");
}
/// Relay pending outbox entries to `queue` using stable
/// `Message::id` (idempotent on retry) and delete confirmed entries.
[[nodiscard]] static Void::Messaging::Result<std::size_t>
relay_outbox(Void::Storage::Engine& engine,
Void::Messaging::Queue& queue,
std::string_view prefix = "outbox:v1:",
std::size_t max_entries = 64)
{
auto snap = engine.snapshot();
if (!snap.has_value()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::PersistenceError,
snap.error().message()));
}
auto cur = engine.scan(
std::move(*snap),
Void::Storage::ScanBounds::prefix(prefix));
if (!cur.has_value()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::PersistenceError,
cur.error().message()));
}
std::size_t relayed = 0;
for (;;) {
auto page = cur->next_page();
if (!page.has_value()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
PersistenceError,
page.error().message()));
}
for (const auto& entry : page->entries) {
if (relayed >= max_entries) {
return relayed;
}
auto decoded = decode_outbox(
Void::Storage::to_string_view(entry.value));
if (!decoded.has_value()) {
return Void::Result::fail(decoded.error());
}
auto pub = queue.publish(
decoded->target_queue, decoded->message,
Void::Messaging::PublishDurability::Durable);
if (!pub.has_value()) {
return Void::Result::fail(pub.error());
}
Void::Storage::Batch erase_b{};
erase_b.require_version(entry.key, entry.version);
erase_b.erase(entry.key);
auto wr = engine.write(std::move(erase_b),
Void::Storage::Durability::Sync);
if (!wr.has_value()) {
if (wr.error().outcome ==
Void::Storage::Outcome::Unknown) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
UnknownOutcome,
"Outbox relay delete outcome unknown"));
}
if (wr.error().cause.code !=
Void::Storage::StorageErrorCode::conflict) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
PersistenceError,
wr.error().cause.error.message()));
}
}
++relayed;
}
if (!page->has_more) {
break;
}
}
return relayed;
}
private:
static void append_u32(std::string& out, std::uint32_t v)
{
out.push_back(static_cast<char>((v >> 24U) & 0xFFU));
out.push_back(static_cast<char>((v >> 16U) & 0xFFU));
out.push_back(static_cast<char>((v >> 8U) & 0xFFU));
out.push_back(static_cast<char>(v & 0xFFU));
}
static void append_str(std::string& out, std::string_view s)
{
append_u32(out, static_cast<std::uint32_t>(s.size()));
out.append(s);
}
[[nodiscard]] static bool read_u32(std::string_view& in,
std::uint32_t& out) noexcept
{
if (in.size() < 4U) return false;
out = (static_cast<std::uint32_t>(
static_cast<unsigned char>(in[0]))
<< 24U) |
(static_cast<std::uint32_t>(
static_cast<unsigned char>(in[1]))
<< 16U) |
(static_cast<std::uint32_t>(
static_cast<unsigned char>(in[2]))
<< 8U) |
static_cast<std::uint32_t>(
static_cast<unsigned char>(in[3]));
in.remove_prefix(4U);
return true;
}
[[nodiscard]] static bool read_str(std::string_view& in,
std::string& out)
{
std::uint32_t len = 0;
if (!read_u32(in, len) || len > in.size()) return false;
out.assign(in.data(), len);
in.remove_prefix(len);
return true;
}
[[nodiscard]] static std::string
encode_outbox(const OutboxRecord& r)
{
std::string out;
append_u32(out, 1U);
append_str(out, r.outbox_id);
append_str(out, r.target_queue);
append_str(out, r.message.id);
append_u32(out, r.message.schema_version);
append_u32(out,
static_cast<std::uint32_t>(r.message.payload.size()));
if (!r.message.payload.empty()) {
out.append(
reinterpret_cast<const char*>(r.message.payload.data()),
r.message.payload.size());
}
append_u32(
out, static_cast<std::uint32_t>(r.message.headers.size()));
for (const auto& [k, v] : r.message.headers) {
append_str(out, k);
append_str(out, v);
}
return out;
}
[[nodiscard]] static Void::Messaging::Result<OutboxRecord>
decode_outbox(std::string_view raw)
{
std::uint32_t ver = 0;
if (!read_u32(raw, ver) || ver != 1U) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::CorruptPayload,
"Outbox: unsupported schema version"));
}
OutboxRecord r{};
std::uint32_t plen = 0;
std::uint32_t hcount = 0;
if (!read_str(raw, r.outbox_id) ||
!read_str(raw, r.target_queue) ||
!read_str(raw, r.message.id) ||
!read_u32(raw, r.message.schema_version) ||
!read_u32(raw, plen) || plen > raw.size()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::CorruptPayload,
"Outbox: truncated payload"));
}
r.message.payload.resize(plen);
if (plen > 0U) {
std::memcpy(r.message.payload.data(), raw.data(), plen);
raw.remove_prefix(plen);
}
if (!read_u32(raw, hcount)) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::CorruptPayload,
"Outbox: truncated header count"));
}
for (std::uint32_t i = 0; i < hcount; ++i) {
std::string k, v;
if (!read_str(raw, k) || !read_str(raw, v)) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
CorruptPayload,
"Outbox: truncated header"));
}
r.message.headers.emplace(std::move(k), std::move(v));
}
return r;
}
};
} // namespace Void::MessagingStorage
@@ -0,0 +1,121 @@
#pragma once
#include <Void/Messaging/Queue.hpp>
#include <Void/Storage/Engine.hpp>
#include <memory>
#include <string>
namespace Void::MessagingStorage
{
struct StorageQueueOptions {
Void::Messaging::QueueLimits limits{};
std::string key_prefix{"msg:v1:"};
const Void::Time::MonotonicClock* monotonic_clock{
&Void::Time::SystemMonotonicClock::instance()};
const Void::Time::CivilClock* civil_clock{
&Void::Time::SystemCivilClock::instance()};
Void::Messaging::RandomU64Fn rng{};
};
/// Single-node durable `Void::Messaging::Queue` backed by
/// `Void::Storage::Engine` conditional batches (`Durability::Sync` for
/// `PublishDurability::Durable`).
///
/// Explicit at-least-once delivery:
/// - On open/restart, all prior `InFlight` records are promoted to
/// `Pending` with a bumped delivery generation so stale worker receipts
/// fail with `StaleReceipt` while preserving attempt counters.
/// - DLQ insertion and source delivery update execute in one atomic batch.
class StorageQueue final : public Void::Messaging::Queue
{
public:
[[nodiscard]] static Void::Messaging::Result<StorageQueue>
open(Void::Storage::Engine& engine,
StorageQueueOptions options = {});
~StorageQueue() noexcept override;
StorageQueue(StorageQueue&&) noexcept;
StorageQueue& operator=(StorageQueue&&) noexcept;
StorageQueue(const StorageQueue&) = delete;
StorageQueue& operator=(const StorageQueue&) = delete;
[[nodiscard]] Void::Messaging::Result<void>
create_queue(Void::Messaging::QueueConfig config) override;
[[nodiscard]] Void::Messaging::Result<void>
create_group(std::string_view queue,
Void::Messaging::GroupConfig config) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
publish(std::string_view queue, Void::Messaging::Message message,
Void::Messaging::PublishDurability durability,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<
std::optional<Void::Messaging::Delivery>>
try_receive(std::string_view queue,
std::string_view group) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::Delivery>
receive(std::string_view queue, std::string_view group,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<void>
ack(const Void::Messaging::Receipt& receipt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<void> nack(
const Void::Messaging::Receipt& receipt,
std::optional<std::chrono::milliseconds> delay = std::nullopt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<
Void::Time::MonotonicClock::time_point>
extend_visibility(
const Void::Messaging::Receipt& receipt,
std::chrono::milliseconds extension,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<void> quarantine_corrupt(
const Void::Messaging::Receipt& receipt, std::string reason,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
query_receipt(
const Void::Messaging::Receipt& receipt) const override;
[[nodiscard]] Void::Messaging::Result<
std::vector<Void::Messaging::DeadLetterEntry>>
list_dead_letters(std::string_view queue,
std::string_view group,
std::size_t limit = 100) const override;
[[nodiscard]] std::size_t
stuck_dlq_count(std::string_view queue,
std::string_view group) const noexcept override;
[[nodiscard]] Void::Messaging::Result<std::size_t>
reap_expired_visibility() override;
[[nodiscard]] Void::Messaging::Result<std::size_t>
expire_retention() override;
void set_clock_healthy(bool healthy) noexcept override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::ShutdownReport>
close_and_join(
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::QueueStats>
stats() const override;
private:
struct State;
explicit StorageQueue(std::shared_ptr<State> state) noexcept;
std::shared_ptr<State> m_state;
};
} // namespace Void::MessagingStorage
+172
View File
@@ -0,0 +1,172 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
struct HttpCodecLimits {
std::size_t max_start_line_bytes{8ULL * 1024};
std::size_t max_header_bytes{32ULL * 1024};
std::size_t max_headers{100};
std::uint64_t max_body_bytes{8ULL * 1024 * 1024};
std::size_t max_chunk_line_bytes{1024};
std::size_t max_trailer_bytes{8ULL * 1024};
std::size_t max_informational_responses{8};
};
enum class HttpParseStatus : std::uint8_t {
NeedMoreData,
Complete,
};
struct ParsedHttpRequest {
Method method{Method::Get};
std::string target{};
std::uint8_t version_major{1};
std::uint8_t version_minor{1};
std::vector<Header> headers{};
std::string body{};
std::vector<Header> trailers{};
bool keep_alive{true};
bool chunked{false};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
struct ParsedHttpResponse {
std::uint16_t status{200};
std::string reason{};
std::uint8_t version_major{1};
std::uint8_t version_minor{1};
std::vector<Header> headers{};
std::string body{};
std::vector<Header> trailers{};
std::vector<std::uint16_t> informational_statuses{};
bool keep_alive{true};
bool chunked{false};
bool close_delimited{false};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
/// Native incremental RFC 9110/9112 HTTP/1.1 request parser.
/// Enforces strict CRLF framing, header/body limits, and rejects
/// Transfer-Encoding + Content-Length smuggling ambiguity and conflicting
/// Content-Length values.
class HttpRequestParser
{
public:
explicit HttpRequestParser(HttpCodecLimits limits = {}) noexcept;
void reset() noexcept;
/// Feed arbitrary byte chunks. Returns Complete once a full message
/// has been parsed; `consumed` reports bytes consumed from `input`.
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::span<const std::byte> input, std::size_t& consumed);
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::string_view input, std::size_t& consumed);
[[nodiscard]] bool complete() const noexcept;
[[nodiscard]] bool connection_reusable() const noexcept;
[[nodiscard]] const ParsedHttpRequest& request() const noexcept;
[[nodiscard]] ParsedHttpRequest take_request();
private:
enum class Phase : std::uint8_t {
Headers,
FixedBody,
ChunkSize,
ChunkData,
ChunkDataCrlf,
Trailers,
Complete,
Failed,
};
HttpCodecLimits m_limits{};
Phase m_phase{Phase::Headers};
std::string m_buf{};
std::size_t m_header_bytes_seen{0};
std::size_t m_trailer_bytes_seen{0};
std::uint64_t m_remaining{0};
std::uint64_t m_body_received{0};
ParsedHttpRequest m_req{};
[[nodiscard]] Void::Result::Result<void> parse_header_block(
std::string_view block);
};
/// Native incremental RFC 9110/9112 HTTP/1.1 response parser.
/// Supports 1xx informational responses, HEAD/204/304 no-body responses,
/// fixed Content-Length, chunked transfer encoding with extensions and
/// trailers, and close-delimited bodies (completed via `finish_eof()`).
class HttpResponseParser
{
public:
explicit HttpResponseParser(
HttpCodecLimits limits = {},
Method request_method = Method::Get) noexcept;
void reset(Method request_method = Method::Get) noexcept;
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::span<const std::byte> input, std::size_t& consumed);
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::string_view input, std::size_t& consumed);
/// Signal peer EOF. Completes close-delimited responses cleanly;
/// errors on truncated fixed-length, chunked, or header frames.
[[nodiscard]] Void::Result::Result<void> finish_eof();
[[nodiscard]] bool complete() const noexcept;
[[nodiscard]] bool connection_reusable() const noexcept;
[[nodiscard]] const ParsedHttpResponse& response() const noexcept;
[[nodiscard]] ParsedHttpResponse take_response();
private:
enum class Phase : std::uint8_t {
Headers,
FixedBody,
ChunkSize,
ChunkData,
ChunkDataCrlf,
Trailers,
CloseDelimitedBody,
Complete,
Failed,
};
HttpCodecLimits m_limits{};
Method m_request_method{Method::Get};
Phase m_phase{Phase::Headers};
std::string m_buf{};
std::size_t m_header_bytes_seen{0};
std::size_t m_trailer_bytes_seen{0};
std::uint64_t m_remaining{0};
std::uint64_t m_body_received{0};
ParsedHttpResponse m_resp{};
[[nodiscard]] Void::Result::Result<bool> parse_header_block(
std::string_view block);
};
} // namespace Void::Net
+9
View File
@@ -3,6 +3,7 @@
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <Void/Net/WebSocket.hpp>
#include <chrono>
#include <cstddef>
@@ -89,6 +90,14 @@ namespace Void::Net
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
/// `sessions` (caller must keep `sessions` alive until after
/// `shutdown()`).
[[nodiscard]] Void::Result::Result<void>
add_websocket_route(std::string pattern,
WebSocketSessions& sessions,
WebSocketUpgradeOptions options = {});
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
+142
View File
@@ -0,0 +1,142 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace Void::Net
{
struct PoolLimits {
std::size_t max_total_connections{256};
std::size_t max_per_origin{8};
std::size_t max_idle_connections{128};
std::chrono::milliseconds idle_timeout{std::chrono::seconds{30}};
};
/// Pool partition key isolating origins, proxy identity, and TLS/trust
/// policy generations so connections never cross trust boundaries.
struct PoolKey {
std::string scheme{};
std::string host{};
std::uint16_t port{0};
std::string proxy_identity{};
std::uint64_t tls_policy_generation{0};
[[nodiscard]] auto
operator<=>(const PoolKey&) const noexcept = default;
};
/// Abstract pooled transport entry owned by ConnectionPool / leases.
class PooledConnection
{
public:
virtual ~PooledConnection() = default;
[[nodiscard]] virtual bool is_open() const noexcept = 0;
virtual void close() noexcept = 0;
};
using ConnectionFactory =
std::function<Void::Result::Result<std::unique_ptr<PooledConnection>>(
const PoolKey&)>;
struct PoolStats {
std::size_t total_connections{0};
std::size_t active_leases{0};
std::size_t idle_connections{0};
std::uint64_t total_acquires{0};
std::uint64_t idle_hits{0};
std::uint64_t idle_evictions{0};
std::uint64_t closed_dirty{0};
};
class ConnectionPool;
/// Move-only RAII lease for one HTTP/1.1 exchange. Only leases explicitly
/// marked reusable via `mark_reusable(true)` (after full body+trailers)
/// return to the idle pool on destruction; unmarked or dirty leases close.
class ConnectionLease final
{
public:
ConnectionLease() noexcept = default;
~ConnectionLease() noexcept;
ConnectionLease(ConnectionLease&& other) noexcept;
ConnectionLease& operator=(ConnectionLease&& other) noexcept;
ConnectionLease(const ConnectionLease&) = delete;
ConnectionLease& operator=(const ConnectionLease&) = delete;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool reused() const noexcept;
[[nodiscard]] const PoolKey& key() const noexcept;
[[nodiscard]] PooledConnection* get() const noexcept;
[[nodiscard]] PooledConnection& operator*() const noexcept;
[[nodiscard]] PooledConnection* operator->() const noexcept;
void mark_reusable(bool reusable = true) noexcept;
void release() noexcept;
private:
friend class ConnectionPool;
struct Impl;
std::shared_ptr<void> m_pool_state{};
PoolKey m_key{};
std::unique_ptr<PooledConnection> m_conn{};
bool m_reused{false};
bool m_reusable{false};
bool m_active{false};
};
/// Bounded HTTP/1.1 connection pool keyed by origin, proxy identity, and
/// TLS policy generation, with deterministic clock-driven idle eviction.
class ConnectionPool final
{
public:
explicit ConnectionPool(
PoolLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~ConnectionPool() noexcept;
ConnectionPool(ConnectionPool&&) noexcept;
ConnectionPool& operator=(ConnectionPool&&) noexcept;
ConnectionPool(const ConnectionPool&) = delete;
ConnectionPool& operator=(const ConnectionPool&) = delete;
/// Acquire an idle connection for `key` or invoke `factory(key)`
/// outside pool locks while enforcing total and per-origin limits.
[[nodiscard]] Void::Result::Result<ConnectionLease>
acquire(const PoolKey& key, const ConnectionFactory& factory);
/// Evict all idle connections older than `idle_timeout` or closed.
std::size_t evict_expired();
/// Close all idle connections (e.g. on trust-store rotation).
std::size_t clear_idle();
/// Prevent new leases and close all currently idle connections.
void shutdown() noexcept;
[[nodiscard]] PoolStats stats() const;
private:
friend class ConnectionLease;
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::Net
+62 -2
View File
@@ -98,6 +98,49 @@ namespace Void::Net
std::uintmax_t size{};
};
/// Move-only RAII handle for a regular file opened beneath a pinned root
/// directory descriptor using `openat(..., O_NOFOLLOW)` (zero TOCTOU).
class OpenedStaticFile final
{
public:
OpenedStaticFile() noexcept = default;
OpenedStaticFile(int fd, std::filesystem::path relative_path,
std::string_view content_type,
std::uint64_t size) noexcept;
~OpenedStaticFile() noexcept;
OpenedStaticFile(OpenedStaticFile&& other) noexcept;
OpenedStaticFile& operator=(OpenedStaticFile&& other) noexcept;
OpenedStaticFile(const OpenedStaticFile&) = delete;
OpenedStaticFile& operator=(const OpenedStaticFile&) = delete;
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
[[nodiscard]] int native_handle() const noexcept { return fd_; }
[[nodiscard]] const std::filesystem::path&
relative_path() const noexcept
{
return relative_path_;
}
[[nodiscard]] std::string_view content_type() const noexcept
{
return content_type_;
}
[[nodiscard]] std::uint64_t size() const noexcept { return size_; }
[[nodiscard]] Void::Result::Result<std::string>
read_all(std::uint64_t max_bytes = 64ULL * 1024 * 1024) const;
void close() noexcept;
private:
int fd_{-1};
std::filesystem::path relative_path_{};
std::string_view content_type_{};
std::uint64_t size_{0};
};
[[nodiscard]] std::string_view
content_type_for(const std::filesystem::path& path);
@@ -115,6 +158,12 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<StaticFile>>
resolve(std::string_view request_path) const;
/// Descriptor-pinned open beneath the retained root directory
/// descriptor (`openat` + `O_NOFOLLOW` per component). Rejects
/// symlinks, traversal, and non-regular files without TOCTOU races.
[[nodiscard]] Void::Result::Result<std::optional<OpenedStaticFile>>
open_safe(std::string_view request_path) const;
[[nodiscard]] const std::filesystem::path& root() const noexcept
{
return root_;
@@ -122,14 +171,25 @@ namespace Void::Net
private:
struct DirHandle {
int fd{-1};
explicit DirHandle(int d) noexcept : fd(d) {}
~DirHandle() noexcept;
DirHandle(const DirHandle&) = delete;
DirHandle& operator=(const DirHandle&) = delete;
};
StaticFileResolver(std::filesystem::path root,
std::string index_file)
: root_(std::move(root)), index_file_(std::move(index_file))
std::string index_file,
std::shared_ptr<DirHandle> root_dir)
: root_(std::move(root)), index_file_(std::move(index_file)),
root_dir_(std::move(root_dir))
{
}
std::filesystem::path root_;
std::string index_file_;
std::shared_ptr<DirHandle> root_dir_;
};
struct WebSocketConnectionId {
+185
View File
@@ -0,0 +1,185 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
enum class WebSocketOpcode : std::uint8_t {
Continuation = 0x0,
Text = 0x1,
Binary = 0x2,
Close = 0x8,
Ping = 0x9,
Pong = 0xA,
};
struct WebSocketLimits {
std::size_t max_message_bytes{1024ULL * 1024};
std::size_t max_output_messages{64};
std::size_t max_output_bytes{4ULL * 1024 * 1024};
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
};
struct WebSocketUpgradeOptions {
std::vector<std::string> allowed_origins{};
std::vector<std::string> supported_subprotocols{};
WebSocketLimits limits{};
};
struct WebSocketUpgradeHandshake {
std::string accept_key{};
std::optional<std::string> selected_subprotocol{};
};
struct WebSocketFrame {
bool fin{true};
WebSocketOpcode opcode{WebSocketOpcode::Text};
bool masked{false};
std::array<std::byte, 4> mask_key{};
std::vector<std::byte> payload{};
};
struct WebSocketMessage {
WebSocketOpcode opcode{WebSocketOpcode::Text};
std::vector<std::byte> payload{};
std::optional<WebSocketClose> close_info{};
[[nodiscard]] std::string_view text_view() const noexcept
{
return std::string_view{
reinterpret_cast<const char*>(payload.data()),
payload.size()};
}
};
/// Compute RFC 6455 Sec-WebSocket-Accept = Base64(SHA1(key + GUID)).
[[nodiscard]] std::string compute_websocket_accept(std::string_view key);
/// Validate strict RFC 3629 UTF-8 byte sequences (required for text frames
/// and close reasons by RFC 6455 section 5.6 / 8.1).
[[nodiscard]] bool is_valid_utf8(std::span<const std::byte> data) noexcept;
[[nodiscard]] bool is_valid_utf8(std::string_view data) noexcept;
/// Validate a client HTTP/1.1 Upgrade request per RFC 6455 section 4.2.1.
[[nodiscard]] Void::Result::Result<WebSocketUpgradeHandshake>
validate_websocket_upgrade_request(
const ServerRequest& request,
const WebSocketUpgradeOptions& options = {});
/// Encode a single RFC 6455 frame. When `masked == true`, applies
/// `mask_key` XOR masking to payload bytes.
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_websocket_frame(const WebSocketFrame& frame);
/// Encode a RFC 6455 Close control frame (2-byte big-endian code + UTF-8
/// reason <= 123 bytes).
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_websocket_close_frame(const WebSocketClose& close, bool masked,
std::array<std::byte, 4> mask_key = {});
/// Incremental RFC 6455 frame decoder & fragmented message assembler.
/// `expect_masked_incoming = true` for server side, `false` for client.
class WebSocketDecoder final
{
public:
explicit WebSocketDecoder(bool expect_masked_incoming,
WebSocketLimits limits = {}) noexcept;
void reset() noexcept;
/// Feed arbitrary bytes and append any completed data or control
/// messages (Text, Binary, Ping, Pong, Close) to `out_messages`.
[[nodiscard]] Void::Result::Result<void>
feed(std::span<const std::byte> input,
std::vector<WebSocketMessage>& out_messages);
[[nodiscard]] bool close_received() const noexcept
{
return m_close_received;
}
private:
bool m_expect_masked{true};
WebSocketLimits m_limits{};
std::vector<std::byte> m_buf{};
bool m_in_fragment{false};
WebSocketOpcode m_fragment_opcode{WebSocketOpcode::Text};
std::vector<std::byte> m_fragment_payload{};
bool m_close_received{false};
};
struct WebSocketConnectOptions {
std::vector<Header> extra_headers{};
std::optional<std::string> subprotocol{};
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
WebSocketLimits limits{};
};
/// Synchronous RFC 6455 WebSocket client over loopback/TCP HTTP/1.1 Upgrade
/// (for direct ws:// endpoints and independent conformance testing).
class WebSocketClient final
{
public:
using ConnectOptions = WebSocketConnectOptions;
WebSocketClient() noexcept = default;
~WebSocketClient() noexcept;
WebSocketClient(WebSocketClient&&) noexcept;
WebSocketClient& operator=(WebSocketClient&&) noexcept;
WebSocketClient(const WebSocketClient&) = delete;
WebSocketClient& operator=(const WebSocketClient&) = delete;
[[nodiscard]] static Void::Result::Result<WebSocketClient>
connect(std::string_view ws_url,
const ConnectOptions& options = ConnectOptions{});
[[nodiscard]] bool is_open() const noexcept;
[[nodiscard]] const std::optional<std::string>&
selected_subprotocol() const noexcept;
[[nodiscard]] Void::Result::Result<void>
send_text(std::string_view text);
[[nodiscard]] Void::Result::Result<void>
send_binary(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void>
send_ping(std::span<const std::byte> payload = {});
[[nodiscard]] Void::Result::Result<void>
send_pong(std::span<const std::byte> payload = {});
[[nodiscard]] Void::Result::Result<void>
send_fragmented_text(std::span<const std::string_view> chunks);
/// Receive the next decoded WebSocket message (auto-answering Ping
/// when `auto_pong == true` unless callers want to inspect Ping).
[[nodiscard]] Void::Result::Result<WebSocketMessage>
receive(std::chrono::milliseconds timeout =
std::chrono::seconds{5});
[[nodiscard]] Void::Result::Result<void>
close(WebSocketClose close_info = {1000, ""});
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit WebSocketClient(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Net
+51
View File
@@ -0,0 +1,51 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/RPC/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace Void::RPC
{
/// Decoded Wire v1 envelope (deterministic big-endian binary format).
struct WireEnvelope {
std::uint16_t major{kWireMajorV1};
std::uint16_t minor{kWireMinorV1};
FrameKind kind{FrameKind::UnaryRequest};
std::uint8_t flags{kFlagEndOfMessage};
CallId call_id{};
MethodId method{};
std::uint32_t schema_version{1};
std::uint32_t remaining_timeout_ms{0};
RpcStatusCode status_code{RpcStatusCode::Ok};
std::vector<MetadataEntry> metadata{};
std::vector<std::byte> payload{};
};
/// Fixed Wire v1 header prefix size in bytes before metadata entries:
/// magic(4) + major(2) + minor(2) + header_len(4) + total_len(4) +
/// kind(1) + flags(1) + reserved(2) + call_id(16) + service_id(8) +
/// method_id(4) + schema_ver(4) + timeout_ms(4) + status_code(2) +
/// metadata_count(2) = 60 bytes.
inline constexpr std::size_t kWireFixedHeaderBytes{60};
/// Encode a Wire v1 envelope in explicit network byte order, validating
/// all header, metadata, and payload limits before allocation.
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_envelope(const WireEnvelope& env,
const RpcLimits& limits = {});
/// Decode a Wire v1 envelope in explicit network byte order. Rejects bad
/// magic, unsupported major versions, non-zero reserved bytes, unknown
/// required flags, integer overflow, truncation, trailing garbage, and
/// limit violations BEFORE allocating payload/metadata buffers. Unknown
/// optional minor header extensions beyond metadata are length-skipped.
[[nodiscard]] Void::Result::Result<WireEnvelope>
decode_envelope(std::span<const std::byte> bytes,
const RpcLimits& limits = {});
} // namespace Void::RPC
+184
View File
@@ -0,0 +1,184 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/RPC/Codec.hpp>
#include <Void/RPC/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::RPC
{
using OwnedBytes = std::vector<std::byte>;
struct CallContext {
CallId call_id{};
MethodDescriptor method{};
PrincipalView principal{};
Void::Time::MonotonicClock::time_point deadline{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
std::vector<MetadataEntry> metadata{};
std::stop_token stop{};
[[nodiscard]] std::chrono::milliseconds
remaining_timeout() const noexcept
{
const auto rem = Void::Time::remaining_until(*clock, deadline);
return std::chrono::duration_cast<std::chrono::milliseconds>(
rem);
}
};
struct CallOptions {
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
std::vector<MetadataEntry> metadata{};
std::vector<Void::Net::Header> transport_headers{};
std::stop_token stop{};
std::uint32_t schema_version{1};
};
using UnaryHandler =
std::function<Void::Result::Result<OwnedBytes>(const CallContext&,
OwnedBytes)>;
struct AuthHook {
std::function<Void::Result::Result<PrincipalView>(
const std::vector<Void::Net::Header>& transport_headers,
const std::vector<MetadataEntry>& metadata)>
authenticate{};
std::function<Void::Result::Result<void>(
const MethodDescriptor& method, const PrincipalView& principal)>
authorize{};
};
/// Move-only RAII method registration handle. Unregistering stops new
/// admission for the method and drains already-admitted calls before
/// returning.
class Registration final
{
public:
Registration() noexcept = default;
~Registration() noexcept;
Registration(Registration&& other) noexcept;
Registration& operator=(Registration&& other) noexcept;
Registration(const Registration&) = delete;
Registration& operator=(const Registration&) = delete;
[[nodiscard]] bool active() const noexcept;
void unregister_and_drain() noexcept;
private:
friend class Server;
struct Entry;
std::shared_ptr<void> m_server_state{};
MethodId m_id{};
std::uint64_t m_reg_gen{0};
bool m_active{false};
};
struct ServerOptions {
Void::Net::HttpServerOptions http_options{};
RpcLimits limits{};
AuthHook auth{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
};
/// Ownership-safe unary HTTP/1.1 RPC server implementing `/void-rpc/v1/call`.
class Server final
{
public:
explicit Server(ServerOptions options = {});
~Server() noexcept;
Server(Server&&) noexcept;
Server& operator=(Server&&) noexcept;
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
[[nodiscard]] Void::Result::Result<Registration>
bind(MethodDescriptor descriptor, UnaryHandler handler);
/// Mount `/void-rpc/v1/call` onto an external HttpServer (or call
/// `start()` to run the owned HttpServer directly).
[[nodiscard]] Void::Result::Result<void>
mount(Void::Net::HttpServer& http_server);
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
std::chrono::seconds{10}) noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::string base_url() const;
/// Direct in-process Wire v1 dispatch (useful for deterministic
/// unit/fault testing without TCP sockets).
[[nodiscard]] Void::Result::Result<OwnedBytes>
handle_raw_envelope(
std::span<const std::byte> request_bytes,
const std::vector<Void::Net::Header>& transport_headers =
{});
private:
friend class Registration;
struct State;
std::shared_ptr<State> m_state;
};
struct ClientOptions {
std::string endpoint_base_url{};
Void::Net::HttpClientOptions http_options{
.verify_tls = true,
};
RpcLimits limits{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
};
/// Unary HTTP/1.1 RPC client encoding Wire v1 envelopes over
/// `Void::Net::HttpClient`.
class Client final
{
public:
explicit Client(ClientOptions options);
~Client() noexcept;
Client(Client&&) noexcept;
Client& operator=(Client&&) noexcept;
Client(const Client&) = delete;
Client& operator=(const Client&) = delete;
[[nodiscard]] Void::Result::Result<OwnedBytes>
call(MethodId method, OwnedBytes payload,
const CallOptions& options = {});
[[nodiscard]] std::size_t in_flight_calls() const noexcept;
private:
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::RPC
+205
View File
@@ -0,0 +1,205 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <array>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <map>
#include <string>
#include <string_view>
#include <vector>
namespace Void::RPC
{
inline constexpr std::array<std::byte, 4> kWireMagic{
std::byte{'V'}, std::byte{'R'}, std::byte{'P'}, std::byte{'C'}};
inline constexpr std::uint16_t kWireMajorV1{1};
inline constexpr std::uint16_t kWireMinorV1{0};
inline constexpr std::string_view kUnaryHttpPath{"/void-rpc/v1/call"};
inline constexpr std::string_view kWireContentType{
"application/vnd.void.rpc.v1"};
enum class RpcStatusCode : std::uint16_t {
Ok = 0,
Cancelled = 1,
InvalidArgument = 2,
DeadlineExceeded = 3,
NotFound = 4,
PermissionDenied = 5,
Unauthenticated = 6,
ResourceExhausted = 7,
FailedPrecondition = 8,
Unimplemented = 9,
Unavailable = 10,
Internal = 11,
DataLoss = 12,
UnknownOutcome = 13,
ProtocolError = 14,
IncompatibleVersion = 15,
};
enum class FrameKind : std::uint8_t {
UnaryRequest = 1,
UnaryResponse = 2,
StreamOpen = 3,
StreamData = 4,
StreamCredit = 5,
StreamHalfClose = 6,
StreamCancel = 7,
StreamTerminal = 8,
};
/// Wire v1 frame flags. Bits 0..3 are optional/informational; bits 4..7 are
/// required-to-understand (unknown required flags fail closed).
inline constexpr std::uint8_t kFlagNone = 0x00U;
inline constexpr std::uint8_t kFlagEndOfMessage = 0x01U;
inline constexpr std::uint8_t kFlagRequiredMask = 0xF0U;
[[nodiscard]] inline Void::Result::Error
make_rpc_error(RpcStatusCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case RpcStatusCode::Ok:
case RpcStatusCode::Internal:
kind = ErrorKind::internal;
break;
case RpcStatusCode::Cancelled:
kind = ErrorKind::cancelled;
break;
case RpcStatusCode::InvalidArgument:
case RpcStatusCode::PermissionDenied:
case RpcStatusCode::Unauthenticated:
kind = ErrorKind::invalid_argument;
break;
case RpcStatusCode::DeadlineExceeded:
kind = ErrorKind::timeout;
break;
case RpcStatusCode::NotFound:
kind = ErrorKind::not_found;
break;
case RpcStatusCode::ResourceExhausted:
kind = ErrorKind::exhausted;
break;
case RpcStatusCode::FailedPrecondition:
case RpcStatusCode::UnknownOutcome:
kind = ErrorKind::conflict;
break;
case RpcStatusCode::Unimplemented:
case RpcStatusCode::IncompatibleVersion:
kind = ErrorKind::unsupported;
break;
case RpcStatusCode::Unavailable:
kind = ErrorKind::overloaded;
break;
case RpcStatusCode::DataLoss:
case RpcStatusCode::ProtocolError:
kind = ErrorKind::corrupt;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kRpcErrorDomain,
static_cast<std::int32_t>(code)}};
}
[[nodiscard]] inline RpcStatusCode
rpc_status_from_error(const Void::Result::Error& err) noexcept
{
if (err.code().domain == Void::Result::kRpcErrorDomain) {
return static_cast<RpcStatusCode>(err.code().value);
}
switch (err.kind()) {
case Void::Result::ErrorKind::cancelled:
return RpcStatusCode::Cancelled;
case Void::Result::ErrorKind::invalid_argument:
return RpcStatusCode::InvalidArgument;
case Void::Result::ErrorKind::timeout:
return RpcStatusCode::DeadlineExceeded;
case Void::Result::ErrorKind::not_found:
return RpcStatusCode::NotFound;
case Void::Result::ErrorKind::exhausted:
return RpcStatusCode::ResourceExhausted;
case Void::Result::ErrorKind::conflict:
return RpcStatusCode::FailedPrecondition;
case Void::Result::ErrorKind::unsupported:
return RpcStatusCode::Unimplemented;
case Void::Result::ErrorKind::overloaded:
return RpcStatusCode::Unavailable;
case Void::Result::ErrorKind::corrupt:
return RpcStatusCode::ProtocolError;
default:
return RpcStatusCode::Internal;
}
}
struct MethodId {
std::uint64_t service{0};
std::uint32_t method{0};
[[nodiscard]] auto
operator<=>(const MethodId&) const noexcept = default;
};
struct CallId {
std::array<std::byte, 16> bytes{};
[[nodiscard]] auto
operator<=>(const CallId&) const noexcept = default;
[[nodiscard]] static CallId generate();
};
struct MetadataEntry {
std::string key{};
std::string value{};
[[nodiscard]] bool
operator==(const MetadataEntry&) const noexcept = default;
};
/// Immutable authenticated principal descriptor provided by AuthHook.
struct PrincipalView {
bool authenticated{false};
std::string subject{};
std::vector<std::string> roles{};
std::map<std::string, std::string, std::less<>> attributes{};
};
struct MethodDescriptor {
MethodId id{};
std::string service_name{};
std::string method_name{};
std::uint32_t schema_version{1};
bool replay_safe{false};
};
struct RpcLimits {
std::size_t max_header_bytes{16ULL * 1024};
std::size_t max_metadata_entries{64};
std::size_t max_payload_bytes{4ULL * 1024 * 1024};
std::size_t max_client_calls{1024};
std::size_t max_server_executing{256};
std::size_t max_server_queued_bytes{64ULL * 1024 * 1024};
std::chrono::milliseconds max_server_timeout{
std::chrono::seconds{30}};
};
struct RpcStatus {
RpcStatusCode code{RpcStatusCode::Ok};
std::string message{};
[[nodiscard]] bool ok() const noexcept
{
return code == RpcStatusCode::Ok;
}
};
} // namespace Void::RPC
File diff suppressed because it is too large. Load diff
+231 -27
View File
@@ -1,15 +1,23 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Memory/BudgetResource.hpp>
#include <Void/Runtime/Lifecycle.hpp>
#include <Void/Runtime/Options.hpp>
#include <Void/Runtime/ResourceGraph.hpp>
#include <Void/Time/Clock.hpp>
#include <cassert>
#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <thread>
#include <utility>
#include <vector>
@@ -60,6 +68,14 @@ struct ShutdownReport {
HostState state{HostState::stopped};
std::size_t pending_owners{0};
std::vector<std::string> pending_owner_ids{};
ShutdownPhase phase{ShutdownPhase::not_started};
std::size_t pending_business_tasks{0};
std::size_t pending_cpu_admitted{0};
std::size_t pending_io_operations{0};
std::size_t retained_buffer_bytes{0};
bool drain_grace_expired{false};
bool export_flush_expired{false};
bool owner_release_pending{false};
};
[[nodiscard]] inline ResourceGraph make_default_resource_graph(bool embedded_mode)
@@ -79,9 +95,16 @@ struct ShutdownReport {
return g;
}
// Inert P1 Runtime composition handle: validates options, memory/time/IO limits,
// borrowed resources, and topological resource lifecycle order without implicitly
// spawning threads or opening descriptors on construction.
} // namespace Void::Runtime
#include <Void/Runtime/Detail/HostCore.hpp>
namespace Void::Runtime
{
/// Runtime composition handle managing startup, readiness, business execution,
/// and phased structured shutdown. Destruction blocks until shutdown is complete
/// in managed mode (or in embedded mode with a ManualExecutor).
class Host
{
public:
@@ -107,7 +130,8 @@ public:
std::move(options),
std::move(*plan),
EmbeddedResources{},
std::move(budget)};
std::move(budget),
{}};
}
[[nodiscard]] static Void::Result::Result<Host> create_embedded(
@@ -134,25 +158,152 @@ public:
std::move(options),
std::move(*plan),
embedded,
std::move(budget)};
std::move(budget),
{}};
}
[[nodiscard]] HostState state() const noexcept { return state_; }
[[nodiscard]] bool is_running() const noexcept { return state_ == HostState::running; }
[[nodiscard]] std::size_t started_worker_count() const noexcept { return started_workers_; }
[[nodiscard]] const Options& options() const noexcept { return options_; }
[[nodiscard]] const LifecyclePlan& lifecycle_plan() const noexcept { return plan_; }
[[nodiscard]] const EmbeddedResources& embedded_resources() const noexcept { return embedded_; }
[[nodiscard]] bool valid() const noexcept { return core_ != nullptr; }
[[nodiscard]] HostState state() const noexcept
{
return core_ ? core_->current_state() : HostState::stopped;
}
[[nodiscard]] bool is_running() const noexcept
{
return state() == HostState::running;
}
[[nodiscard]] bool is_ready() const noexcept
{
return core_ ? core_->current_ready() : false;
}
[[nodiscard]] std::size_t started_worker_count() const noexcept
{
return core_ ? core_->current_workers() : 0;
}
[[nodiscard]] std::size_t cpu_admitted() const noexcept
{
return core_ ? core_->cpu_admitted_count() : 0;
}
[[nodiscard]] Async::Executor* executor() noexcept
{
return core_ ? core_->active_executor() : nullptr;
}
[[nodiscard]] IO::Driver* io() noexcept
{
return core_ ? core_->get_io() : nullptr;
}
[[nodiscard]] std::optional<std::thread::id> owner_thread() const noexcept
{
return core_ ? core_->current_owner_thread() : std::nullopt;
}
/// Precondition: `valid()`.
[[nodiscard]] const Options& options() const noexcept
{
assert(valid());
return core_->options;
}
/// Precondition: `valid()`.
[[nodiscard]] const LifecyclePlan& lifecycle_plan() const noexcept
{
assert(valid());
return core_->plan;
}
/// Precondition: `valid()`.
[[nodiscard]] const EmbeddedResources& embedded_resources() const noexcept
{
assert(valid());
return core_->embedded;
}
/// Precondition: `valid()`.
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept
{
return embedded_.clock ? *embedded_.clock
: Void::Time::SystemMonotonicClock::instance();
assert(valid());
return core_->active_clock();
}
/// Precondition: `valid()`.
[[nodiscard]] Void::Memory::BudgetResource& memory_budget() noexcept
{
return embedded_.memory_budget ? *embedded_.memory_budget : *owned_budget_;
assert(valid());
return core_->active_budget();
}
[[nodiscard]] Void::Result::Result<void> start(StartOptions opts = {})
{
if (!core_) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_state,
"Cannot start a moved-from Host")};
}
return core_->start_impl(std::move(opts));
}
[[nodiscard]] std::expected<Async::JoinHandle, Async::AdmissionError> spawn(
Coro::Task<void>&& task, Async::OperationOptions opts = {})
{
if (!core_) {
return std::unexpected{Async::AdmissionError::stopped};
}
return core_->spawn_impl(std::move(task), std::move(opts));
}
void begin_shutdown() noexcept
{
if (core_) {
core_->begin_shutdown_impl();
}
}
[[nodiscard]] Void::Result::Result<ShutdownReport>
poll_shutdown(Async::OperationOptions opts = {})
{
if (!core_) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_state,
"Cannot poll_shutdown on a moved-from Host")};
}
return core_->poll_shutdown_impl(std::move(opts));
}
[[nodiscard]] Void::Result::Result<ShutdownReport>
shutdown_blocking(Async::OperationOptions opts = {})
{
if (!core_) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_state,
"Cannot shutdown_blocking on a moved-from Host")};
}
return core_->shutdown_blocking_impl(std::move(opts), false);
}
[[nodiscard]] Void::Result::Result<ShutdownReport> shutdown_pumping(
Async::ManualExecutor& manual,
Async::OperationOptions opts = {},
Async::TimerQueue* timers = nullptr)
{
if (!core_) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_state,
"Cannot shutdown_pumping on a moved-from Host")};
}
return core_->shutdown_pumping_impl(
manual, std::move(opts), timers, false);
}
[[nodiscard]] std::optional<ShutdownReport> last_shutdown_report() const
{
return core_ ? core_->current_last_report() : std::nullopt;
}
private:
@@ -161,20 +312,18 @@ private:
Host(Options options,
LifecyclePlan plan,
EmbeddedResources embedded,
std::unique_ptr<Void::Memory::BudgetResource> owned_budget) noexcept
: options_(std::move(options))
, plan_(std::move(plan))
, embedded_(embedded)
, owned_budget_(std::move(owned_budget))
std::unique_ptr<Void::Memory::BudgetResource> owned_budget,
std::vector<std::shared_ptr<detail::ComponentEntry>> components)
: core_(std::make_unique<detail::HostCore>(
std::move(options),
std::move(plan),
embedded,
std::move(owned_budget),
std::move(components)))
{
}
HostState state_{HostState::constructed};
std::size_t started_workers_{0};
Options options_{};
LifecyclePlan plan_{};
EmbeddedResources embedded_{};
std::unique_ptr<Void::Memory::BudgetResource> owned_budget_{};
std::unique_ptr<detail::HostCore> core_{};
};
class HostBuilder
@@ -190,6 +339,7 @@ public:
options_ = std::move(options);
if (!embedded_.has_value()) {
graph_ = make_default_resource_graph(options_.embedded_mode);
components_.clear();
}
return *this;
}
@@ -199,6 +349,7 @@ public:
options_.embedded_mode = true;
embedded_ = embedded;
graph_ = make_default_resource_graph(true);
components_.clear();
return *this;
}
@@ -214,6 +365,34 @@ public:
std::move(dependent), std::move(dependency), required);
}
[[nodiscard]] Void::Result::Result<void> add_component(
std::string id,
ResourceKind kind,
std::shared_ptr<Component> component,
std::vector<std::string> deps = {},
bool critical = true)
{
if (id.empty() || !component) {
return std::unexpected{make_runtime_error(
RuntimeErrorCode::invalid_argument,
"Component id must be non-empty and component pointer must be non-null")};
}
if (auto nr = graph_.add_node(
ResourceNode{id, kind, ResourceOwnership::owned, critical});
!nr.has_value()) {
return nr;
}
for (auto& d : deps) {
if (auto dr = graph_.add_dependency(id, std::move(d), true);
!dr.has_value()) {
return dr;
}
}
components_.push_back(ComponentSpec{
std::move(id), kind, std::move(component), critical});
return {};
}
[[nodiscard]] Void::Result::Result<Host> build() const
{
Options opts = options_;
@@ -237,13 +416,38 @@ public:
budget = std::make_unique<Void::Memory::BudgetResource>(
opts.limits.max_owned_memory_bytes);
}
return Host{std::move(opts), std::move(*plan), emb, std::move(budget)};
std::vector<std::shared_ptr<detail::ComponentEntry>> entries;
entries.reserve(components_.size());
for (const auto& c : components_) {
auto entry = std::make_shared<detail::ComponentEntry>();
entry->id = c.id;
entry->kind = c.kind;
entry->critical = c.critical;
entry->component = c.component;
entries.push_back(std::move(entry));
}
return Host{
std::move(opts),
std::move(*plan),
emb,
std::move(budget),
std::move(entries)};
}
private:
struct ComponentSpec {
std::string id{};
ResourceKind kind{ResourceKind::service};
std::shared_ptr<Component> component{};
bool critical{true};
};
Options options_{};
std::optional<EmbeddedResources> embedded_{};
ResourceGraph graph_;
std::vector<ComponentSpec> components_{};
};
} // namespace Void::Runtime
} // namespace Void::Runtime
+121
View File
@@ -0,0 +1,121 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Memory/BudgetResource.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <stop_token>
#include <utility>
namespace Void::Runtime
{
enum class StartStep : std::uint8_t {
signal_gate,
memory_budget,
cpu_executor,
io_driver,
file_workers,
reactor,
components,
readiness
};
enum class ShutdownPhase : std::uint8_t {
not_started,
closing_admission,
draining,
cancelling,
joining_business,
stopping_components,
flushing_exporters,
releasing_components,
stopping_io,
stopping_workers,
releasing,
stopped
};
/// Abstract OS-signal gate installed before Runtime threads start and
/// uninstalled after worker threads join. Runtime keeps no System dependency;
/// callers inject concrete gates (e.g. wrapping Process::SignalWatcher).
class SignalGate
{
public:
virtual ~SignalGate() = default;
[[nodiscard]] virtual Void::Result::Result<void> install() = 0;
virtual void uninstall(bool on_owner_thread) noexcept = 0;
};
/// Live composition context handed to Component::start outside Host locks.
class HostContext
{
public:
HostContext(Async::Executor& executor,
IO::Driver* io_driver,
const Void::Time::MonotonicClock& clock,
Void::Memory::BudgetResource& memory_budget,
std::stop_token business_stop) noexcept
: executor_(&executor)
, io_(io_driver)
, clock_(&clock)
, memory_budget_(&memory_budget)
, business_stop_(std::move(business_stop))
{
}
[[nodiscard]] Async::Executor& executor() noexcept { return *executor_; }
[[nodiscard]] IO::Driver* io() noexcept { return io_; }
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept
{
return *clock_;
}
[[nodiscard]] Void::Memory::BudgetResource& memory_budget() noexcept
{
return *memory_budget_;
}
[[nodiscard]] std::stop_token business_stop() const noexcept
{
return business_stop_;
}
private:
Async::Executor* executor_{nullptr};
IO::Driver* io_{nullptr};
const Void::Time::MonotonicClock* clock_{nullptr};
Void::Memory::BudgetResource* memory_budget_{nullptr};
std::stop_token business_stop_{};
};
/// Lifecycle-managed runtime service or exporter component.
class Component
{
public:
virtual ~Component() = default;
[[nodiscard]] virtual Void::Result::Result<void> start(HostContext&) = 0;
[[nodiscard]] virtual Void::Coro::Task<Void::Result::Result<void>>
stop(Async::OperationOptions) = 0;
};
struct StartOptions {
SignalGate* signal_gate{nullptr};
std::function<Void::Result::Result<void>(StartStep)> before_step{};
std::function<Void::Result::Result<void>(StartStep, std::size_t thread_index)>
before_thread_start{};
std::function<void(ShutdownPhase)> on_phase{};
std::chrono::milliseconds readiness_timeout{std::chrono::milliseconds{5000}};
std::chrono::milliseconds cleanup_timeout{std::chrono::milliseconds{5000}};
};
} // namespace Void::Runtime
+5 -1
View File
@@ -25,7 +25,9 @@ enum class RuntimeErrorCode : std::int32_t {
cycle_detected = 4,
invalid_state = 5,
unsupported = 6,
internal = 7
internal = 7,
self_join = 8,
shutdown_incomplete = 9
};
[[nodiscard]] inline Void::Result::Error make_runtime_error(
@@ -49,6 +51,8 @@ enum class RuntimeErrorCode : std::int32_t {
case RuntimeErrorCode::conflict:
case RuntimeErrorCode::cycle_detected:
case RuntimeErrorCode::invalid_state:
case RuntimeErrorCode::self_join:
case RuntimeErrorCode::shutdown_incomplete:
kind = ErrorKind::conflict;
break;
case RuntimeErrorCode::unsupported:
+135
View File
@@ -0,0 +1,135 @@
#pragma once
#include <Void/Scheduler/Types.hpp>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
struct CivilMinute {
std::int32_t year{1970};
std::uint32_t month{1}; // 1..12
std::uint32_t day{1}; // 1..31
std::uint32_t hour{0}; // 0..23
std::uint32_t minute{0}; // 0..59
std::uint32_t weekday{4}; // 0=Sunday .. 6=Saturday
};
/// Convert civil UTC components to minutes since 1970-01-01T00:00Z.
[[nodiscard]] std::int64_t
civil_to_epoch_minute(std::int32_t year, std::uint32_t month,
std::uint32_t day, std::uint32_t hour,
std::uint32_t minute) noexcept;
/// Convert minutes since 1970-01-01T00:00Z to civil components + weekday.
[[nodiscard]] CivilMinute
epoch_minute_to_civil(std::int64_t epoch_minute) noexcept;
/// Explicit DST transition rule for deterministic timezone resolution
/// without relying on ambient OS tzdata behavior.
struct DstTransitionRule {
std::string name{};
std::int32_t standard_offset_minutes{0};
std::int32_t dst_offset_minutes{0};
/// Spring-forward gap window in local wall minutes `[start, end)`.
std::optional<std::int64_t> gap_start_local_min{};
std::optional<std::int64_t> gap_end_local_min{};
/// Fall-back fold window in local wall minutes `[start, end)`.
/// Minutes in `[start, end)` happen twice: fold 0 at `dst_offset`,
/// fold 1 at `standard_offset`.
std::optional<std::int64_t> fold_start_local_min{};
std::optional<std::int64_t> fold_end_local_min{};
};
struct ResolvedSlot {
std::int64_t utc_ms{0};
std::uint8_t fold_index{0};
};
/// Explicit timezone registry. Recognizes `"UTC"`, `"Z"`, fixed numeric
/// offsets (`+HH:MM`, `-HH:MM`, `UTC+HH:MM`, `UTC-HH:MM`), and explicitly
/// registered `DstTransitionRule` zones. Unknown zones fail with
/// `UnsupportedTimezone` (never silent UTC fallback).
class TimezoneRegistry final
{
public:
TimezoneRegistry() = default;
void register_dst_zone(DstTransitionRule rule);
[[nodiscard]] Result<void>
validate_timezone(std::string_view tz) const;
[[nodiscard]] Result<std::vector<ResolvedSlot>>
resolve_local_minute(std::string_view tz,
std::int64_t local_epoch_minute,
DstGapPolicy gap_policy,
DstFoldPolicy fold_policy) const;
/// Approximate local epoch minute range covering `[utc_min_lo,
/// utc_min_hi]` for `tz`.
[[nodiscard]] Result<std::pair<std::int64_t, std::int64_t>>
local_minute_bounds(std::string_view tz,
std::int64_t utc_min_lo,
std::int64_t utc_min_hi) const;
private:
std::map<std::string, DstTransitionRule, std::less<>> m_dst_zones{};
};
struct MaterializedSlots {
std::vector<ResolvedSlot> slots{};
std::int64_t next_cursor_utc_ms{0};
bool more_pending{false};
};
/// 5-field cron-like calendar expression (`minute hour day month weekday`)
/// supporting `*`, lists, ranges, and steps. Both day-of-month and weekday
/// constraints apply.
class CalendarExpression final
{
public:
[[nodiscard]] static Result<CalendarExpression>
parse(std::string_view expression);
[[nodiscard]] bool matches(const CivilMinute& cm) const noexcept;
/// Next matching local epoch minute strictly >= `from_local_min`,
/// capped by `max_local_min`.
[[nodiscard]] std::optional<std::int64_t>
next_matching_minute(std::int64_t from_local_min,
std::int64_t max_local_min) const noexcept;
/// Latest matching local epoch minute <= `from_local_min` and
/// >= `min_local_min`. Allows O(1) coalescing across millions of
/// missed minutes.
[[nodiscard]] std::optional<std::int64_t>
prev_matching_minute(std::int64_t from_local_min,
std::int64_t min_local_min) const noexcept;
[[nodiscard]] Result<MaterializedSlots>
materialize_range(const CalendarSpec& spec,
const TimezoneRegistry& tz_registry,
std::int64_t after_utc_ms,
std::int64_t up_to_utc_ms,
MisfirePolicy misfire,
std::size_t max_catch_up) const;
private:
std::uint64_t m_minutes{0}; // bits 0..59
std::uint32_t m_hours{0}; // bits 0..23
std::uint32_t m_days{0}; // bits 1..31
std::uint32_t m_months{0}; // bits 1..12
std::uint32_t m_weekdays{0}; // bits 0..6 (0 = Sunday)
};
} // namespace Void::Scheduler
+100
View File
@@ -0,0 +1,100 @@
#pragma once
#include <Void/Scheduler/Calendar.hpp>
#include <Void/Scheduler/Store.hpp>
#include <Void/Scheduler/Types.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
struct SchedulerOptions {
std::string owner_id{"scheduler-default"};
std::shared_ptr<JobStore> store{};
const Void::Time::MonotonicClock* monotonic_clock{
&Void::Time::SystemMonotonicClock::instance()};
const Void::Time::CivilClock* civil_clock{
&Void::Time::SystemCivilClock::instance()};
TimezoneRegistry timezones{};
SchedulerLimits limits{};
RandomU64Fn rng{};
ObservationHook observer{};
};
/// Pure, thread-free timer/calendar job scheduler with pluggable durable
/// persistence (`InMemoryJobStore` or `SchedulerStorage::StorageJobStore`).
class Scheduler final
{
public:
[[nodiscard]] static Result<Scheduler>
create(SchedulerOptions options = {});
Scheduler(Scheduler&&) noexcept;
Scheduler& operator=(Scheduler&&) noexcept;
Scheduler(const Scheduler&) = delete;
Scheduler& operator=(const Scheduler&) = delete;
~Scheduler() noexcept;
[[nodiscard]] Result<void> register_handler(std::string handler_id,
HandlerFn handler);
[[nodiscard]] Result<std::uint64_t>
add_job(JobSpec spec,
Void::Async::OperationOptions options = {});
/// Increment revision and atomically record an old-revision
/// invalidation watermark. Failed updates leave prior policy intact.
[[nodiscard]] Result<std::uint64_t>
update_job(JobSpec spec,
Void::Async::OperationOptions options = {});
/// Write a job tombstone, stop new admission, and signal stop to
/// active handlers for the job.
[[nodiscard]] Result<void>
remove_job(std::string_view job_id,
Void::Async::OperationOptions options = {});
/// Run one bounded scheduling pass: materialize due occurrences
/// under misfire/catch-up/retention limits and dispatch ready
/// occurrences outside scheduler/store locks. Returns count of
/// occurrences executed in this pass.
[[nodiscard]] Result<std::size_t>
tick(Void::Async::OperationOptions options = {});
/// Execute at most one ready occurrence from the monotonic min-heap
/// outside scheduler/store locks.
[[nodiscard]] Result<bool>
dispatch_one(Void::Async::OperationOptions options = {});
/// Stop materialization/dispatch, signal stop to active handlers,
/// and wait up to `options.deadline` for live handlers to exit.
/// Never erases running records or abandons active frames.
[[nodiscard]] Result<ShutdownReport>
close_and_join(Void::Async::OperationOptions options = {});
[[nodiscard]] Result<std::vector<JobRecord>> list_jobs() const;
[[nodiscard]] Result<std::vector<OccurrenceRecord>>
list_occurrences() const;
[[nodiscard]] Result<void>
acknowledge_dead(const OccurrenceId& id);
[[nodiscard]] Result<std::size_t>
prune_completed(std::size_t max_count = 256);
[[nodiscard]] Result<std::size_t>
reclaim_invalidated(std::size_t max_count = 256);
[[nodiscard]] Result<StoreStats> stats() const;
private:
struct State;
explicit Scheduler(std::shared_ptr<State> state) noexcept;
std::shared_ptr<State> m_state;
};
} // namespace Void::Scheduler
+105
View File
@@ -0,0 +1,105 @@
#pragma once
#include <Void/Scheduler/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
/// Persistence port for Scheduler state transitions.
/// Implementations guarantee atomic conditional commits (in-memory mutex
/// or `Void::Storage::Engine` conditional batches).
class JobStore
{
public:
virtual ~JobStore() = default;
[[nodiscard]] virtual Result<void>
acquire_ownership(std::string_view owner_id) = 0;
[[nodiscard]] virtual Result<void> release_ownership() = 0;
[[nodiscard]] virtual Result<void> put_job(const JobRecord& job) = 0;
[[nodiscard]] virtual Result<void>
update_job(const JobRecord& updated,
std::uint64_t expected_revision) = 0;
[[nodiscard]] virtual Result<void>
tombstone_job(std::string_view job_id) = 0;
[[nodiscard]] virtual Result<std::vector<JobRecord>>
load_jobs() const = 0;
[[nodiscard]] virtual Result<std::vector<OccurrenceRecord>>
load_occurrences() const = 0;
/// Atomically insert new occurrences (enforcing unique
/// `(job, revision, intended_utc_ms, fold_index)` dedup and
/// retention cap) AND advance the job's cursor/sequence.
[[nodiscard]] virtual Result<std::size_t> materialize_occurrences(
std::string_view job_id, std::uint64_t expected_revision,
std::int64_t new_cursor_utc_ms,
std::int64_t new_cursor_monotonic_ns, bool cursor_initialized,
bool one_shot_materialized, std::uint64_t next_sequence,
const std::vector<OccurrenceRecord>& records) = 0;
/// Atomically verify job is not tombstoned, check old-revision
/// invalidation watermark, and transition `Pending -> Running`
/// bumping `attempt`.
[[nodiscard]] virtual Result<OccurrenceRecord>
claim_occurrence(const OccurrenceId& id,
std::uint32_t expected_attempt) = 0;
/// Atomically transition `Running -> Completed` and optionally
/// advance a FixedDelay job's monotonic cursor.
[[nodiscard]] virtual Result<void> complete_occurrence(
const OccurrenceId& id, std::uint32_t attempt,
std::int64_t completed_utc_ms,
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
std::nullopt) = 0;
/// Atomically transition `Running -> Pending` (retry) or
/// `Running -> Dead` (exhausted).
[[nodiscard]] virtual Result<void> fail_occurrence(
const OccurrenceId& id, std::uint32_t attempt,
std::int64_t next_due_monotonic_ns,
std::int64_t next_due_utc_ms, bool mark_dead,
std::string diagnostic_category) = 0;
/// Return a `Running` occurrence to `Pending` during host shutdown
/// without consuming a retry attempt.
[[nodiscard]] virtual Result<void>
requeue_on_shutdown(const OccurrenceId& id,
std::uint32_t attempt) = 0;
/// Startup recovery: return every `Running` record to `Pending`
/// preserving its exact `OccurrenceId` and attempt counter.
[[nodiscard]] virtual Result<std::size_t>
recover_running_occurrences() = 0;
[[nodiscard]] virtual Result<void>
acknowledge_dead(const OccurrenceId& id) = 0;
[[nodiscard]] virtual Result<std::size_t>
prune_completed(std::int64_t before_utc_ms,
std::size_t max_count) = 0;
[[nodiscard]] virtual Result<std::size_t>
reclaim_invalidated(std::size_t max_count) = 0;
[[nodiscard]] virtual Result<StoreStats> stats() const = 0;
};
/// Default in-memory `JobStore` implementation requiring zero `Storage`
/// dependency.
[[nodiscard]] std::shared_ptr<JobStore>
make_in_memory_job_store(SchedulerLimits limits = {});
} // namespace Void::Scheduler
+339
View File
@@ -0,0 +1,339 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class SchedulerErrorCode : std::int32_t {
None = 0,
InvalidArgument = 1,
InvalidRule = 2,
UnsupportedTimezone = 3,
NotFound = 4,
Conflict = 5,
Overloaded = 6,
RetentionFull = 7,
PersistenceError = 8,
UnknownOutcome = 9,
HandlerFailed = 10,
Cancelled = 11,
Closed = 12,
SelfJoin = 13,
OwnershipLocked = 14,
CorruptRecord = 15,
};
[[nodiscard]] inline Error make_scheduler_error(SchedulerErrorCode code,
std::string message)
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case SchedulerErrorCode::None:
case SchedulerErrorCode::HandlerFailed:
kind = ErrorKind::internal;
break;
case SchedulerErrorCode::InvalidArgument:
case SchedulerErrorCode::InvalidRule:
kind = ErrorKind::invalid_argument;
break;
case SchedulerErrorCode::UnsupportedTimezone:
kind = ErrorKind::unsupported;
break;
case SchedulerErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case SchedulerErrorCode::Conflict:
case SchedulerErrorCode::UnknownOutcome:
case SchedulerErrorCode::SelfJoin:
case SchedulerErrorCode::OwnershipLocked:
kind = ErrorKind::conflict;
break;
case SchedulerErrorCode::Overloaded:
kind = ErrorKind::overloaded;
break;
case SchedulerErrorCode::RetentionFull:
kind = ErrorKind::exhausted;
break;
case SchedulerErrorCode::PersistenceError:
kind = ErrorKind::io;
break;
case SchedulerErrorCode::CorruptRecord:
kind = ErrorKind::corrupt;
break;
case SchedulerErrorCode::Cancelled:
case SchedulerErrorCode::Closed:
kind = ErrorKind::cancelled;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kSchedulerErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct OccurrenceId {
std::string job_id{};
std::uint64_t revision{0};
std::uint64_t sequence{0};
[[nodiscard]] auto
operator<=>(const OccurrenceId&) const noexcept = default;
[[nodiscard]] std::string to_idempotency_key() const
{
return job_id + "#" + std::to_string(revision) + "#" +
std::to_string(sequence);
}
};
enum class MisfirePolicy : std::uint8_t {
Skip = 0,
CoalesceLatest = 1,
CatchUpBounded = 2,
};
enum class OverlapPolicy : std::uint8_t {
Forbid = 0,
QueueOne = 1,
AllowBounded = 2,
};
enum class DstGapPolicy : std::uint8_t {
Skip = 0,
NextValid = 1,
};
enum class DstFoldPolicy : std::uint8_t {
First = 0,
Second = 1,
Twice = 2,
};
enum class ScheduleKind : std::uint8_t {
OneShot = 0,
FixedDelay = 1,
FixedRate = 2,
Calendar = 3,
};
struct RetryPolicy {
std::uint32_t max_attempts{5};
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
std::chrono::milliseconds max_delay{std::chrono::minutes{5}};
std::uint32_t multiplier{2};
};
struct CalendarSpec {
std::string expression{};
std::string timezone{"UTC"};
std::uint32_t tz_data_version{1};
DstGapPolicy gap_policy{DstGapPolicy::Skip};
DstFoldPolicy fold_policy{DstFoldPolicy::First};
};
struct Schedule {
ScheduleKind kind{ScheduleKind::OneShot};
std::int64_t start_utc_ms{0};
std::optional<Void::Time::MonotonicClock::time_point>
due_monotonic{};
std::chrono::milliseconds interval{0};
CalendarSpec calendar{};
[[nodiscard]] static Schedule
one_shot_monotonic(Void::Time::MonotonicClock::time_point due)
{
Schedule s{};
s.kind = ScheduleKind::OneShot;
s.due_monotonic = due;
return s;
}
[[nodiscard]] static Schedule one_shot_utc(std::int64_t utc_ms)
{
Schedule s{};
s.kind = ScheduleKind::OneShot;
s.start_utc_ms = utc_ms;
return s;
}
[[nodiscard]] static Schedule fixed_delay(
std::chrono::milliseconds delay,
std::optional<Void::Time::MonotonicClock::time_point>
first_due = std::nullopt)
{
Schedule s{};
s.kind = ScheduleKind::FixedDelay;
s.interval = delay;
s.due_monotonic = first_due;
return s;
}
[[nodiscard]] static Schedule fixed_rate(
std::chrono::milliseconds period,
std::optional<Void::Time::MonotonicClock::time_point>
first_due = std::nullopt)
{
Schedule s{};
s.kind = ScheduleKind::FixedRate;
s.interval = period;
s.due_monotonic = first_due;
return s;
}
[[nodiscard]] static Schedule calendar_schedule(CalendarSpec spec)
{
Schedule s{};
s.kind = ScheduleKind::Calendar;
s.calendar = std::move(spec);
return s;
}
};
struct JobSpec {
std::string id{};
Schedule schedule{};
std::string handler_id{};
std::uint32_t payload_schema{1};
std::vector<std::byte> payload{};
MisfirePolicy misfire{MisfirePolicy::CoalesceLatest};
OverlapPolicy overlap{OverlapPolicy::Forbid};
std::uint32_t max_concurrent{1};
RetryPolicy retry{};
};
enum class OccurrenceStatus : std::uint8_t {
Pending = 0,
Running = 1,
Completed = 2,
Dead = 3,
Cancelled = 4,
};
struct JobRecord {
std::uint32_t format_version{1};
JobSpec spec{};
std::uint64_t revision{1};
/// Unstarted occurrences with `revision < invalidated_before_revision`
/// are logically cancelled and cannot be claimed.
std::uint64_t invalidated_before_revision{1};
bool tombstoned{false};
std::int64_t cursor_utc_ms{0};
std::int64_t cursor_monotonic_ns{0};
bool cursor_initialized{false};
bool one_shot_materialized{false};
std::uint64_t next_sequence{1};
};
struct OccurrenceRecord {
std::uint32_t format_version{1};
OccurrenceId id{};
std::int64_t intended_utc_ms{0};
std::int64_t due_monotonic_ns{0};
std::uint8_t fold_index{0};
OccurrenceStatus status{OccurrenceStatus::Pending};
std::uint32_t attempt{0};
std::string handler_id{};
std::uint32_t payload_schema{1};
std::vector<std::byte> payload{};
std::string diagnostic_category{};
std::int64_t completed_utc_ms{0};
bool dead_acknowledged{false};
};
struct SchedulerLimits {
std::size_t max_jobs{10000};
std::size_t max_retained_occurrences{100000};
std::size_t max_payload_bytes{64ULL * 1024};
std::size_t max_loaded_payload_bytes{16ULL * 1024 * 1024};
std::size_t max_ready_dispatches{256};
std::size_t max_active_handlers{32};
std::size_t max_catch_up_per_job_per_pass{100};
std::size_t max_retries_per_turn{64};
std::size_t max_durable_batch_bytes{1024ULL * 1024};
std::chrono::milliseconds completed_retention{
std::chrono::hours{24 * 7}};
};
struct ShutdownReport {
bool complete{true};
std::vector<OccurrenceId> live_occurrences{};
};
struct StoreStats {
std::size_t jobs{0};
std::size_t pending{0};
std::size_t running{0};
std::size_t completed{0};
std::size_t dead{0};
std::size_t cancelled{0};
std::size_t total_retained{0};
bool retention_saturated{false};
};
enum class ObservationKind : std::uint8_t {
Materialize = 0,
Dispatch = 1,
Complete = 2,
Retry = 3,
DeadLetter = 4,
RetentionPause = 5,
Recover = 6,
};
struct ObservationEvent {
ObservationKind kind{ObservationKind::Dispatch};
std::size_t count{1};
std::int64_t lag_ms{0};
};
using ObservationHook = std::function<void(const ObservationEvent&)>;
using RandomU64Fn = std::function<std::uint64_t()>;
struct OccurrenceContext {
OccurrenceId id{};
std::uint32_t attempt{1};
std::uint32_t payload_schema{1};
std::int64_t intended_utc_ms{0};
std::uint8_t fold_index{0};
};
using HandlerFn = std::function<Result<void>(
const OccurrenceContext&, std::span<const std::byte>,
Void::Async::OperationOptions)>;
[[nodiscard]] inline std::int64_t
to_ns(Void::Time::MonotonicClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
tp.time_since_epoch())
.count();
}
[[nodiscard]] inline std::int64_t
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch())
.count();
}
} // namespace Void::Scheduler
@@ -0,0 +1,111 @@
#pragma once
#include <Void/Scheduler/Store.hpp>
#include <Void/Storage/Engine.hpp>
#include <memory>
#include <string>
namespace Void::SchedulerStorage
{
struct StorageJobStoreOptions {
Void::Scheduler::SchedulerLimits limits{};
/// Key prefix namespace within the shared `Void::Storage::Engine`.
std::string key_prefix{"sched:v1:"};
/// Set true only when explicitly recovering after a process crash
/// where the previous owner exited without calling
/// `release_ownership()` (the underlying `Storage::Engine` OS lock
/// guarantees single-process directory ownership).
bool recover_stale_owner{false};
};
/// Durable `Void::Scheduler::JobStore` backed by `Void::Storage::Engine`
/// conditional `Batch` writes (`Durability::Sync`, 1 MiB batch cap,
/// exclusive logical owner lock, unique civil-slot dedup index, and
/// `UnknownOutcome` propagation).
class StorageJobStore final : public Void::Scheduler::JobStore
{
public:
StorageJobStore(Void::Storage::Engine& engine,
StorageJobStoreOptions options = {});
[[nodiscard]] Void::Scheduler::Result<void>
acquire_ownership(std::string_view owner_id) override;
[[nodiscard]] Void::Scheduler::Result<void>
release_ownership() override;
[[nodiscard]] Void::Scheduler::Result<void>
put_job(const Void::Scheduler::JobRecord& job) override;
[[nodiscard]] Void::Scheduler::Result<void>
update_job(const Void::Scheduler::JobRecord& updated,
std::uint64_t expected_revision) override;
[[nodiscard]] Void::Scheduler::Result<void>
tombstone_job(std::string_view job_id) override;
[[nodiscard]] Void::Scheduler::Result<
std::vector<Void::Scheduler::JobRecord>>
load_jobs() const override;
[[nodiscard]] Void::Scheduler::Result<
std::vector<Void::Scheduler::OccurrenceRecord>>
load_occurrences() const override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
materialize_occurrences(
std::string_view job_id, std::uint64_t expected_revision,
std::int64_t new_cursor_utc_ms,
std::int64_t new_cursor_monotonic_ns,
bool cursor_initialized, bool one_shot_materialized,
std::uint64_t next_sequence,
const std::vector<Void::Scheduler::OccurrenceRecord>&
records) override;
[[nodiscard]] Void::Scheduler::Result<
Void::Scheduler::OccurrenceRecord>
claim_occurrence(const Void::Scheduler::OccurrenceId& id,
std::uint32_t expected_attempt) override;
[[nodiscard]] Void::Scheduler::Result<void> complete_occurrence(
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
std::int64_t completed_utc_ms,
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
std::nullopt) override;
[[nodiscard]] Void::Scheduler::Result<void> fail_occurrence(
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
std::int64_t next_due_monotonic_ns,
std::int64_t next_due_utc_ms, bool mark_dead,
std::string diagnostic_category) override;
[[nodiscard]] Void::Scheduler::Result<void>
requeue_on_shutdown(const Void::Scheduler::OccurrenceId& id,
std::uint32_t attempt) override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
recover_running_occurrences() override;
[[nodiscard]] Void::Scheduler::Result<void>
acknowledge_dead(const Void::Scheduler::OccurrenceId& id) override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
prune_completed(std::int64_t before_utc_ms,
std::size_t max_count) override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
reclaim_invalidated(std::size_t max_count) override;
[[nodiscard]] Void::Scheduler::Result<Void::Scheduler::StoreStats>
stats() const override;
private:
Void::Storage::Engine* m_engine{nullptr};
StorageJobStoreOptions m_options{};
std::string m_owner_id{};
};
} // namespace Void::SchedulerStorage
+895
View File
@@ -0,0 +1,895 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/ShortUrl/ShortUrl.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::ShortUrl::V2
{
inline constexpr std::uint32_t kServiceVersionV2{2};
inline constexpr std::uint32_t kRecordSchemaVersion{1};
enum class V2ErrorCode : std::int32_t {
None = 0,
InvalidRequest = 1,
InvalidUrl = 2,
InvalidKey = 3,
InvalidExpiry = 4,
Conflict = 5,
NotFound = 6,
Expired = 7,
Revoked = 8,
Unsupported = 9,
Unauthorized = 10,
RateLimited = 11,
QuotaExceeded = 12,
IdentityExpired = 13,
StorageError = 14,
UnknownOutcome = 15,
ProviderError = 16,
Timeout = 17,
Unavailable = 18,
ResponseTooLarge = 19,
Internal = 20,
};
[[nodiscard]] inline Void::Result::Error
make_shorturl_error(V2ErrorCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case V2ErrorCode::None:
case V2ErrorCode::Internal:
case V2ErrorCode::ProviderError:
kind = ErrorKind::internal;
break;
case V2ErrorCode::InvalidRequest:
case V2ErrorCode::InvalidUrl:
case V2ErrorCode::InvalidKey:
case V2ErrorCode::InvalidExpiry:
case V2ErrorCode::Unauthorized:
kind = ErrorKind::invalid_argument;
break;
case V2ErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case V2ErrorCode::Conflict:
case V2ErrorCode::Expired:
case V2ErrorCode::Revoked:
case V2ErrorCode::IdentityExpired:
case V2ErrorCode::UnknownOutcome:
kind = ErrorKind::conflict;
break;
case V2ErrorCode::Unsupported:
kind = ErrorKind::unsupported;
break;
case V2ErrorCode::RateLimited:
case V2ErrorCode::Unavailable:
kind = ErrorKind::overloaded;
break;
case V2ErrorCode::QuotaExceeded:
case V2ErrorCode::ResponseTooLarge:
kind = ErrorKind::exhausted;
break;
case V2ErrorCode::StorageError:
kind = ErrorKind::io;
break;
case V2ErrorCode::Timeout:
kind = ErrorKind::timeout;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kShortUrlErrorDomain,
static_cast<std::int32_t>(code)}};
}
[[nodiscard]] inline V2ErrorCode
v2_error_code_from(const Void::Result::Error& err) noexcept
{
if (err.code().domain == Void::Result::kShortUrlErrorDomain) {
return static_cast<V2ErrorCode>(err.code().value);
}
switch (err.kind()) {
case Void::Result::ErrorKind::invalid_argument:
return V2ErrorCode::InvalidRequest;
case Void::Result::ErrorKind::not_found:
return V2ErrorCode::NotFound;
case Void::Result::ErrorKind::conflict:
return V2ErrorCode::Conflict;
case Void::Result::ErrorKind::timeout:
return V2ErrorCode::Timeout;
case Void::Result::ErrorKind::overloaded:
return V2ErrorCode::Unavailable;
case Void::Result::ErrorKind::unsupported:
return V2ErrorCode::Unsupported;
case Void::Result::ErrorKind::exhausted:
return V2ErrorCode::QuotaExceeded;
case Void::Result::ErrorKind::io:
return V2ErrorCode::StorageError;
default:
return V2ErrorCode::Internal;
}
}
[[nodiscard]] inline V1::ErrorCode
to_v1_error_code(V2ErrorCode code) noexcept
{
switch (code) {
case V2ErrorCode::None: return V1::ErrorCode::none;
case V2ErrorCode::InvalidRequest:
case V2ErrorCode::InvalidKey:
case V2ErrorCode::InvalidExpiry:
case V2ErrorCode::IdentityExpired:
return V1::ErrorCode::invalid_request;
case V2ErrorCode::InvalidUrl: return V1::ErrorCode::invalid_url;
case V2ErrorCode::Unsupported: return V1::ErrorCode::unsupported;
case V2ErrorCode::NotFound: return V1::ErrorCode::not_found;
case V2ErrorCode::Expired: return V1::ErrorCode::expired;
case V2ErrorCode::Revoked: return V1::ErrorCode::revoked;
case V2ErrorCode::Conflict: return V1::ErrorCode::conflict;
case V2ErrorCode::Unauthorized: return V1::ErrorCode::unauthorized;
case V2ErrorCode::RateLimited: return V1::ErrorCode::rate_limited;
case V2ErrorCode::Timeout: return V1::ErrorCode::timeout;
case V2ErrorCode::Unavailable:
case V2ErrorCode::QuotaExceeded:
return V1::ErrorCode::unavailable;
case V2ErrorCode::StorageError: return V1::ErrorCode::storage;
case V2ErrorCode::ResponseTooLarge:
return V1::ErrorCode::response_too_large;
case V2ErrorCode::ProviderError:
case V2ErrorCode::UnknownOutcome:
return V1::ErrorCode::provider_error;
case V2ErrorCode::Internal: return V1::ErrorCode::internal_error;
}
return V1::ErrorCode::internal_error;
}
enum class LinkState : std::uint8_t {
Active = 1,
Revoked = 2,
};
struct LinkRecord {
std::string key{};
std::string target_url{};
std::int64_t created_at_unix_seconds{0};
std::int64_t expires_at_unix_seconds{0}; // 0 = permanent
LinkState state{LinkState::Active};
std::string operation_id{};
std::uint32_t schema_version{kRecordSchemaVersion};
};
struct IdempotencyRecord {
std::string operation_id{};
std::string key{};
std::string target_url{};
std::int64_t created_at_unix_seconds{0};
std::int64_t retain_until_unix_seconds{0};
};
struct Link {
std::string key{};
std::string short_url{};
std::string target_url{};
std::int64_t expires_at_unix_seconds{0};
std::uint32_t retry_after_seconds{0};
};
struct CreateLink {
std::string target_url{};
std::string custom_key{};
std::int64_t expires_at_unix_seconds{0};
};
struct ShortenOptions {
std::string operation_id{};
std::chrono::seconds idempotency_retention{std::chrono::hours{24}};
};
struct LocalProviderLimits {
std::size_t max_url_bytes{8192};
std::size_t max_key_bytes{64};
std::size_t generated_key_length{16};
std::size_t max_collision_retries{8};
std::size_t max_entries{100'000};
std::size_t max_retained_identities{10'000};
std::size_t max_concurrent_ops{128};
};
using HostPolicy = std::function<bool(std::string_view host)>;
/// Validate target URL: absolute http/https, non-empty host, no userinfo,
/// no control chars, bounded length, and optional host policy check.
[[nodiscard]] inline Void::Result::Result<void>
validate_target_url(std::string_view url,
std::size_t max_url_bytes = 8192,
const HostPolicy& host_policy = {})
{
if (url.empty() || url.size() > max_url_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL empty or exceeds length limit")};
}
for (const unsigned char ch : url) {
if (ch <= 0x20 || ch >= 0x7F) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL contains control or whitespace "
"character")};
}
}
std::size_t rest_pos = 0;
if (url.starts_with("https://")) {
rest_pos = 8U;
} else if (url.starts_with("http://")) {
rest_pos = 7U;
} else {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL scheme must be http or https")};
}
const std::string_view after_scheme = url.substr(rest_pos);
const std::size_t auth_end = after_scheme.find_first_of("/?#");
const std::string_view authority = after_scheme.substr(0, auth_end);
if (authority.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl, "ShortUrl: missing URL authority")};
}
if (authority.find('@') != std::string_view::npos) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: userinfo in target URL is forbidden")};
}
std::string_view host = authority;
if (host.front() == '[') {
const std::size_t close_b = host.find(']');
if (close_b == std::string_view::npos || close_b == 1U) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: malformed IPv6 host in target URL")};
}
host = host.substr(1U, close_b - 1U);
} else if (const std::size_t colon = host.find(':');
colon != std::string_view::npos) {
const std::string_view port_sv = host.substr(colon + 1U);
if (port_sv.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: empty port in target URL")};
}
for (const char c : port_sv) {
if (c < '0' || c > '9') {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: non-numeric port in target URL")};
}
}
host = host.substr(0, colon);
}
if (host.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl, "ShortUrl: empty host")};
}
if (host_policy && !host_policy(host)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target host rejected by policy")};
}
return {};
}
/// Validate custom key: 1..max_key_bytes ASCII [A-Za-z0-9_-], rejecting
/// reserved route names.
[[nodiscard]] inline Void::Result::Result<void>
validate_custom_key(std::string_view key,
std::size_t max_key_bytes = 64)
{
if (key.empty() || key.size() > max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key length must be 1..64")};
}
for (const unsigned char ch : key) {
const bool ok = (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch == '-' || ch == '_';
if (!ok) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key contains invalid character")};
}
}
static const std::set<std::string_view> kReserved{
"health", "metrics", "admin", "api", "shorten",
"resolve", "revoke", "v1", "v2", "static",
"assets", "status", "robots", "favicon"};
std::string lower;
lower.reserve(key.size());
for (const char ch : key) {
lower.push_back(static_cast<char>(
ch >= 'A' && ch <= 'Z' ? (ch - 'A' + 'a') : ch));
}
if (kReserved.contains(lower)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key matches reserved route name")};
}
return {};
}
class RandomBytesPort
{
public:
virtual ~RandomBytesPort() = default;
[[nodiscard]] virtual Void::Result::Result<void>
fill(std::span<std::byte> out) = 0;
};
class SystemRandomBytesPort final : public RandomBytesPort
{
public:
[[nodiscard]] Void::Result::Result<void>
fill(std::span<std::byte> out) override
{
std::random_device rd;
std::size_t i = 0;
while (i < out.size()) {
const unsigned int v = rd();
for (int b = 0; b < 4 && i < out.size(); ++b, ++i) {
out[i] = static_cast<std::byte>((v >> (b * 8)) & 0xFFU);
}
}
return {};
}
};
enum class InsertStatus : std::uint8_t {
Inserted,
IdempotentReplay,
Conflict,
IdentityExpired,
QuotaExceeded,
};
struct InsertOutcome {
InsertStatus status{InsertStatus::Inserted};
LinkRecord record{};
};
class LinkRepositoryPort
{
public:
virtual ~LinkRepositoryPort() = default;
[[nodiscard]] virtual bool is_durable() const noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<InsertOutcome>
insert_conditional(const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds,
std::size_t max_entries,
std::size_t max_retained_identities) = 0;
[[nodiscard]] virtual Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const = 0;
[[nodiscard]] virtual Void::Result::Result<void>
revoke(std::string_view key,
std::int64_t now_unix_seconds) = 0;
};
/// Explicitly nondurable in-memory repository for unit tests and semantic
/// verification. Preserves conditional insert, tombstones, and idempotency.
class InMemoryLinkRepository final : public LinkRepositoryPort
{
public:
[[nodiscard]] bool is_durable() const noexcept override
{
return false;
}
[[nodiscard]] Void::Result::Result<InsertOutcome>
insert_conditional(const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds,
std::size_t max_entries,
std::size_t max_retained_identities) override
{
std::lock_guard lock{m_mutex};
if (idem.has_value() && !idem->operation_id.empty()) {
if (const auto iit = m_idempotency.find(idem->operation_id);
iit != m_idempotency.end()) {
if (iit->second.retain_until_unix_seconds <=
now_unix_seconds) {
return InsertOutcome{InsertStatus::IdentityExpired,
{}};
}
if (const auto lit = m_links.find(iit->second.key);
lit != m_links.end()) {
return InsertOutcome{
InsertStatus::IdempotentReplay, lit->second};
}
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (m_idempotency.size() >= max_retained_identities) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
}
if (m_links.contains(record.key)) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (m_links.size() >= max_entries) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
m_links.emplace(record.key, record);
if (idem.has_value() && !idem->operation_id.empty()) {
m_idempotency.emplace(idem->operation_id, *idem);
}
return InsertOutcome{InsertStatus::Inserted, record};
}
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const override
{
std::lock_guard lock{m_mutex};
if (const auto it = m_links.find(key); it != m_links.end()) {
return std::optional<LinkRecord>{it->second};
}
return std::optional<LinkRecord>{};
}
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key, std::int64_t) override
{
std::lock_guard lock{m_mutex};
const auto it = m_links.find(key);
if (it == m_links.end()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound,
"ShortUrl: cannot revoke unknown key")};
}
it->second.state = LinkState::Revoked;
return {};
}
private:
mutable std::mutex m_mutex;
std::map<std::string, LinkRecord, std::less<>> m_links;
std::map<std::string, IdempotencyRecord, std::less<>> m_idempotency;
};
/// Abstract V2 provider interface outside the frozen V1 ABI.
class Provider
{
public:
virtual ~Provider() = default;
[[nodiscard]] virtual std::string_view
provider_id() const noexcept = 0;
[[nodiscard]] virtual V1::Health health() const = 0;
[[nodiscard]] virtual bool supports_resolve() const noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) = 0;
[[nodiscard]] virtual Void::Result::Result<Link>
resolve(std::string_view key) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
revoke(std::string_view key) = 0;
};
struct LocalProviderOptions {
std::string public_base_url{"https://sho.rt"};
std::string provider_id{"void.local"};
LocalProviderLimits limits{};
HostPolicy host_policy{};
};
/// Native local ShortUrl V2 provider composing LinkRepositoryPort,
/// CivilClock, and RandomBytesPort with rejection-sampled base62 keys.
class LocalProvider final : public Provider
{
public:
using Options = LocalProviderOptions;
LocalProvider(std::shared_ptr<LinkRepositoryPort> repository,
Options options = Options{},
const Void::Time::CivilClock& clock =
Void::Time::SystemCivilClock::instance(),
std::shared_ptr<RandomBytesPort> rng =
std::make_shared<SystemRandomBytesPort>())
: m_repo(std::move(repository)), m_options(std::move(options)),
m_clock(&clock), m_rng(std::move(rng))
{
while (m_options.public_base_url.size() > 1U &&
m_options.public_base_url.back() == '/') {
m_options.public_base_url.pop_back();
}
}
[[nodiscard]] std::string_view
provider_id() const noexcept override
{
return m_options.provider_id;
}
[[nodiscard]] V1::Health health() const override
{
if (m_stopping.load(std::memory_order_acquire) || !m_repo) {
return {V1::HealthStatus::unhealthy,
"provider unavailable"};
}
return {V1::HealthStatus::healthy,
m_repo->is_durable() ? "durable local provider"
: "nondurable memory provider"};
}
[[nodiscard]] bool supports_resolve() const noexcept override
{
return true;
}
void shutdown() noexcept
{
m_stopping.store(true, std::memory_order_release);
}
[[nodiscard]] Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (auto u = validate_target_url(request.target_url,
m_options.limits.max_url_bytes,
m_options.host_policy);
!u.has_value()) {
return std::unexpected{std::move(u.error())};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
if (request.expires_at_unix_seconds < 0 ||
(request.expires_at_unix_seconds > 0 &&
request.expires_at_unix_seconds <= now_s)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidExpiry,
"ShortUrl: expiry must be 0 (permanent) or in the "
"future")};
}
const bool custom = !request.custom_key.empty();
if (custom) {
if (auto k = validate_custom_key(
request.custom_key, m_options.limits.max_key_bytes);
!k.has_value()) {
return std::unexpected{std::move(k.error())};
}
}
const std::size_t attempts =
custom ? 1U : m_options.limits.max_collision_retries;
for (std::size_t attempt = 0; attempt < attempts; ++attempt) {
std::string key;
if (custom) {
key = request.custom_key;
} else {
auto gen = generate_base62_key(
m_options.limits.generated_key_length);
if (!gen.has_value()) {
return std::unexpected{std::move(gen.error())};
}
key = std::move(*gen);
}
LinkRecord rec;
rec.key = key;
rec.target_url = request.target_url;
rec.created_at_unix_seconds = now_s;
rec.expires_at_unix_seconds =
request.expires_at_unix_seconds;
rec.state = LinkState::Active;
rec.operation_id = options.operation_id;
rec.schema_version = kRecordSchemaVersion;
std::optional<IdempotencyRecord> idem;
if (!options.operation_id.empty()) {
idem = IdempotencyRecord{
.operation_id = options.operation_id,
.key = key,
.target_url = request.target_url,
.created_at_unix_seconds = now_s,
.retain_until_unix_seconds =
now_s + options.idempotency_retention.count(),
};
}
auto ins = m_repo->insert_conditional(
rec, idem, now_s, m_options.limits.max_entries,
m_options.limits.max_retained_identities);
if (!ins.has_value()) {
return std::unexpected{std::move(ins.error())};
}
switch (ins->status) {
case InsertStatus::Inserted:
case InsertStatus::IdempotentReplay:
return make_link(ins->record);
case InsertStatus::Conflict:
if (custom) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Conflict,
"ShortUrl: custom key already exists")};
}
continue; // retry random key
case InsertStatus::IdentityExpired:
return std::unexpected{make_shorturl_error(
V2ErrorCode::IdentityExpired,
"ShortUrl: operation_id retention expired")};
case InsertStatus::QuotaExceeded:
return std::unexpected{make_shorturl_error(
V2ErrorCode::QuotaExceeded,
"ShortUrl: repository quota or retention "
"exhausted")};
}
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Conflict,
"ShortUrl: exhausted random key collision retries")};
}
[[nodiscard]] Void::Result::Result<Link>
resolve(std::string_view key) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
}
auto rec = m_repo->get(key);
if (!rec.has_value()) {
return std::unexpected{std::move(rec.error())};
}
if (!rec->has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound, "ShortUrl: key not found")};
}
const LinkRecord& r = **rec;
if (r.state == LinkState::Revoked) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Revoked, "ShortUrl: link revoked")};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
if (r.expires_at_unix_seconds > 0 &&
r.expires_at_unix_seconds <= now_s) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Expired, "ShortUrl: link expired")};
}
return make_link(r);
}
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
return m_repo->revoke(key, now_s);
}
private:
struct OpSlot {
std::atomic<std::size_t>* active{nullptr};
~OpSlot() noexcept
{
if (active != nullptr) {
active->fetch_sub(1, std::memory_order_acq_rel);
}
}
OpSlot(std::atomic<std::size_t>* a) noexcept : active(a) {}
OpSlot(OpSlot&& o) noexcept
: active(std::exchange(o.active, nullptr))
{
}
OpSlot(const OpSlot&) = delete;
OpSlot& operator=(const OpSlot&) = delete;
};
[[nodiscard]] Void::Result::Result<OpSlot> try_admit()
{
if (m_stopping.load(std::memory_order_acquire) || !m_repo ||
!m_rng) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
"ShortUrl: provider shut down or unconfigured")};
}
std::size_t cur = m_active_ops.load(std::memory_order_relaxed);
for (;;) {
if (cur >= m_options.limits.max_concurrent_ops) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::RateLimited,
"ShortUrl: max concurrent operations reached")};
}
if (m_active_ops.compare_exchange_weak(
cur, cur + 1U, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
return OpSlot{&m_active_ops};
}
}
}
[[nodiscard]] Void::Result::Result<std::string>
generate_base62_key(std::size_t len) const
{
static constexpr char kAlphabet[63] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"
"wxyz";
constexpr unsigned char kCutoff = 62U * 4U; // 248 (uniform)
std::string out;
out.reserve(len);
std::array<std::byte, 64> buf{};
while (out.size() < len) {
auto r = m_rng->fill(buf);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
for (const std::byte b : buf) {
const auto u = static_cast<unsigned char>(b);
if (u < kCutoff) {
out.push_back(kAlphabet[u % 62U]);
if (out.size() == len) {
break;
}
}
}
}
return out;
}
[[nodiscard]] Link make_link(const LinkRecord& r) const
{
return Link{
.key = r.key,
.short_url =
std::format("{}/{}", m_options.public_base_url, r.key),
.target_url = r.target_url,
.expires_at_unix_seconds = r.expires_at_unix_seconds,
};
}
std::shared_ptr<LinkRepositoryPort> m_repo;
Options m_options;
const Void::Time::CivilClock* m_clock;
std::shared_ptr<RandomBytesPort> m_rng;
std::atomic<bool> m_stopping{false};
std::atomic<std::size_t> m_active_ops{0};
};
/// Adapter implementing frozen `Void::ShortUrl::V1::IShortener` on top of
/// any V2 `Provider` without changing V1 layout or virtual table order.
class V1Adapter final : public V1::IShortener
{
public:
explicit V1Adapter(std::shared_ptr<Provider> provider)
: m_provider(std::move(provider))
{
}
[[nodiscard]] std::string_view
provider_id() const noexcept override
{
return m_provider ? m_provider->provider_id()
: std::string_view{"unconfigured"};
}
[[nodiscard]] V1::Health health() const override
{
return m_provider ? m_provider->health()
: V1::Health{V1::HealthStatus::unhealthy,
"null provider"};
}
[[nodiscard]] V1::ShortenResult
shorten(const V1::ShortenRequest& request) override
{
if (!m_provider) {
return {.error = {V1::ErrorCode::unavailable,
"null provider"}};
}
auto res = m_provider->shorten(CreateLink{
.target_url = request.target_url,
.custom_key = request.custom_key,
.expires_at_unix_seconds = request.expires_at_unix_seconds,
});
if (!res.has_value()) {
const auto code = v2_error_code_from(res.error());
return {.error = {to_v1_error_code(code),
std::string{res.error().message()}}};
}
return {
.short_url = std::move(res->short_url),
.key = std::move(res->key),
.expires_at_unix_seconds = res->expires_at_unix_seconds,
.error = {},
};
}
[[nodiscard]] bool supports_resolve() const noexcept override
{
return m_provider != nullptr && m_provider->supports_resolve();
}
[[nodiscard]] V1::ResolveResult
resolve(const V1::ResolveRequest& request) override
{
if (!m_provider) {
return {.error = {V1::ErrorCode::unavailable,
"null provider"}};
}
auto res = m_provider->resolve(request.key);
if (!res.has_value()) {
const auto code = v2_error_code_from(res.error());
return {.error = {to_v1_error_code(code),
std::string{res.error().message()}}};
}
return {
.target_url = std::move(res->target_url),
.expires_at_unix_seconds = res->expires_at_unix_seconds,
.error = {},
};
}
private:
std::shared_ptr<Provider> m_provider;
};
} // namespace Void::ShortUrl::V2
@@ -0,0 +1,67 @@
#pragma once
#include <Void/Net/Http.hpp>
#include <Void/ShortUrl/V2.hpp>
#include <chrono>
#include <cstdint>
#include <string>
#include <vector>
namespace Void::ShortUrl::V2
{
struct RemoteCapabilities {
bool supports_custom_key{true};
bool supports_expiry{true};
bool supports_resolve{true};
bool supports_revoke{true};
};
struct RemoteProviderOptions {
std::string base_url{};
std::string provider_id{"void.remote"};
RemoteCapabilities capabilities{};
Void::Net::HttpClientOptions http_options{
.verify_tls = true,
.max_body_size = 1024ULL * 1024,
};
std::chrono::seconds timeout{std::chrono::seconds{10}};
std::uint64_t max_response_bytes{1024ULL * 1024};
std::vector<Void::Net::Header> headers{};
};
/// Generic remote ShortUrl V2 provider over `Void::Net::HttpClient`.
/// Checks capability flags before network mutation, enforces response size
/// and deadline bounds, preserves Retry-After, and maps lost-reply
/// transport failures after send to `V2ErrorCode::UnknownOutcome`.
class RemoteProvider final : public Provider
{
public:
explicit RemoteProvider(RemoteProviderOptions options);
[[nodiscard]] std::string_view
provider_id() const noexcept override;
[[nodiscard]] V1::Health health() const override;
[[nodiscard]] bool supports_resolve() const noexcept override;
[[nodiscard]] Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) override;
[[nodiscard]] Void::Result::Result<Link>
resolve(std::string_view key) override;
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key) override;
/// Retry-After seconds from the most recent rate-limited/unavailable
/// remote response (0 if absent).
[[nodiscard]] std::uint32_t last_retry_after_seconds() const noexcept;
private:
RemoteProviderOptions m_options;
Void::Net::HttpClient m_client;
std::atomic<std::uint32_t> m_last_retry_after{0};
};
} // namespace Void::ShortUrl::V2
@@ -0,0 +1,58 @@
#pragma once
#include <Void/ShortUrl/V2.hpp>
#include <Void/Storage/Engine.hpp>
#include <cstdint>
#include <memory>
#include <mutex>
namespace Void::ShortUrl::V2
{
/// CSPRNG byte source backed by `Void::Security` (libsodium).
class SecurityRandomBytesPort final : public RandomBytesPort
{
public:
[[nodiscard]] Void::Result::Result<void>
fill(std::span<std::byte> out) override;
};
/// Durable `LinkRepositoryPort` backed by `Void::Storage::Engine`
/// conditional `Batch` writes, preserving tombstones, V2 idempotency
/// records, and quotas across crash/restart boundaries.
class StorageLinkRepository final : public LinkRepositoryPort
{
public:
explicit StorageLinkRepository(
std::shared_ptr<Void::Storage::Engine> engine,
std::uint64_t disk_quota_bytes = 1024ULL * 1024 * 1024);
[[nodiscard]] bool is_durable() const noexcept override
{
return true;
}
[[nodiscard]] Void::Result::Result<InsertOutcome>
insert_conditional(const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds,
std::size_t max_entries,
std::size_t max_retained_identities) override;
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const override;
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key,
std::int64_t now_unix_seconds) override;
private:
mutable std::mutex m_write_mutex;
std::shared_ptr<Void::Storage::Engine> m_engine;
std::uint64_t m_disk_quota_bytes;
};
} // namespace Void::ShortUrl::V2
+202 -9
View File
@@ -1,11 +1,15 @@
#pragma once
#include <Void/TestingMock/Matcher.hpp>
#include <Void/TestingMock/Session.hpp>
#include <concepts>
#include <cstddef>
#include <format>
#include <functional>
#include <limits>
#include <memory>
#include <optional>
#include <source_location>
#include <string>
#include <string_view>
@@ -24,8 +28,8 @@ namespace Void::TestingMock::Detail
using MatcherTuple =
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
/// Move-only function — supports unique_ptr-capturing lambdas
/// and other move-only callables.
/// Move-only function — supports unique_ptr-capturing lambdas,
/// move-only arguments, and move-only return values.
using Action = std::move_only_function<R(Args...)>;
Expectation(MatcherTuple matchers, std::source_location loc)
@@ -34,52 +38,200 @@ namespace Void::TestingMock::Detail
}
template <typename U = R>
requires(!std::is_void_v<U> && std::same_as<U, R>)
requires(!std::is_void_v<U> && std::same_as<U, R> &&
std::copy_constructible<U>)
Expectation& returns(U value)
{
m_once_action = false;
m_action = [val = std::move(value)](Args...) mutable -> R {
return val;
};
return *this;
}
/// Return a move-only (or copyable) value once, moving it out on
/// the reserved invocation. Automatically sets times(1).
template <typename U = R>
requires(!std::is_void_v<U> && std::convertible_to<U, R>)
Expectation& returns_once(U&& value)
{
m_once_action = true;
m_action = [val = std::forward<U>(value)](Args...) mutable -> R {
return std::move(val);
};
return times(1);
}
template <typename F>
requires std::invocable<F&, Args...>
Expectation& invokes(F action)
{
m_once_action = false;
m_action = std::move(action);
return *this;
}
/// Transfer a one-shot move-only callable to the single reserved
/// invocation. Automatically sets times(1).
template <typename F>
requires std::invocable<F&, Args...>
Expectation& invokes_once(F action)
{
m_once_action = true;
m_action = std::move(action);
return times(1);
}
Expectation& times(int n)
{
m_prohibited = (n == 0);
m_min_calls = n;
m_max_calls = n;
sync_sequence_bounds();
return *this;
}
Expectation& once() { return times(1); }
bool matches(Args... args) const
/// Explicit prohibition checked before ordinary expectations.
Expectation& never()
{
m_prohibited = true;
m_min_calls = 0;
m_max_calls = 0;
sync_sequence_bounds();
return *this;
}
Expectation& at_least(int n)
{
m_prohibited = false;
m_min_calls = n;
m_max_calls = std::numeric_limits<int>::max();
sync_sequence_bounds();
return *this;
}
Expectation& at_most(int n)
{
m_prohibited = (n == 0);
m_min_calls = 0;
m_max_calls = n;
sync_sequence_bounds();
return *this;
}
Expectation& between(int min_calls, int max_calls)
{
m_prohibited = (min_calls == 0 && max_calls == 0);
m_min_calls = min_calls;
m_max_calls = max_calls;
sync_sequence_bounds();
return *this;
}
Expectation& in_sequence(Sequence& seq)
{
m_seq_handle = seq.add_step(m_min_calls, m_max_calls);
return *this;
}
[[nodiscard]] bool valid_bounds() const noexcept
{
return m_min_calls >= 0 && m_max_calls >= 0 &&
m_min_calls <= m_max_calls;
}
[[nodiscard]] std::size_t max_matcher_depth() const noexcept
{
return max_depth_impl(std::index_sequence_for<Args...>{});
}
[[nodiscard]] bool is_prohibited() const noexcept
{
return m_prohibited;
}
[[nodiscard]] bool is_once_action() const noexcept
{
return m_once_action;
}
/// Inspect arguments by const reference without copying/moving.
[[nodiscard]] bool matches(const Args&... args) const
{
return match_impl(args..., std::index_sequence_for<Args...>{});
}
R execute(Args... args)
[[nodiscard]] bool sequence_eligible() const
{
if (!m_seq_handle.has_value() ||
m_seq_handle->seq == nullptr) {
return true;
}
return m_seq_handle->seq->is_eligible(m_seq_handle->index);
}
/// Attempt to reserve one call slot (and sequence position if any).
/// Must be called under the MockFunction reservation lock.
[[nodiscard]] bool try_reserve()
{
if (m_prohibited || m_call_count >= m_max_calls) {
return false;
}
if (m_seq_handle.has_value() && m_seq_handle->seq != nullptr) {
if (!m_seq_handle->seq->try_reserve(m_seq_handle->index)) {
return false;
}
}
++m_call_count;
return true;
}
/// Transfer one-shot action out upon reservation.
[[nodiscard]] Action take_once_action() noexcept
{
return std::move(m_action);
}
R execute(Args&&... args)
{
if (!m_action) {
if constexpr (std::is_same_v<R, void>) {
return;
} else {
} else if constexpr (std::is_default_constructible_v<R>) {
return R{};
} else {
throw InvocationAbortException(
"TestingMock: expectation matched without an "
"action for non-default-constructible return type");
}
}
return m_action(args...);
return m_action(std::forward<Args>(args)...);
}
static R execute_action(Action& action, Args&&... args)
{
if (!action) {
if constexpr (std::is_same_v<R, void>) {
return;
} else if constexpr (std::is_default_constructible_v<R>) {
return R{};
} else {
throw InvocationAbortException(
"TestingMock: expectation matched without an "
"action for non-default-constructible return type");
}
}
return action(std::forward<Args>(args)...);
}
void record_call() { ++m_call_count; }
bool is_saturated() const { return m_call_count >= m_max_calls; }
[[nodiscard]] bool is_saturated() const noexcept
{
return m_call_count >= m_max_calls;
}
void verify(std::string_view func_name)
{
@@ -91,6 +243,25 @@ namespace Void::TestingMock::Detail
}
}
void collect_verification(std::string_view func_name,
Verification& out) const
{
if (m_call_count < m_min_calls) {
out.unmet.push_back(std::format(
"unsatisfied expectation on {}: {} — {}/{} calls ({}:{})",
func_name, describe_matchers(), m_call_count,
m_min_calls, m_location.file_name(),
m_location.line()));
}
if (m_call_count > m_max_calls) {
out.excess.push_back(std::format(
"excess calls on {}: {} — {}/{} calls ({}:{})",
func_name, describe_matchers(), m_call_count,
m_max_calls, m_location.file_name(),
m_location.line()));
}
}
// -------- accessors used by failure-message construction --------
[[nodiscard]] int call_count() const noexcept
@@ -98,6 +269,8 @@ namespace Void::TestingMock::Detail
return m_call_count;
}
[[nodiscard]] int min_calls() const noexcept { return m_min_calls; }
[[nodiscard]] int max_calls() const noexcept { return m_max_calls; }
[[nodiscard]] std::source_location location() const noexcept
@@ -119,13 +292,33 @@ namespace Void::TestingMock::Detail
int m_min_calls{1};
int m_max_calls{1};
int m_call_count{0};
bool m_prohibited{false};
bool m_once_action{false};
std::optional<Sequence::StepHandle> m_seq_handle{};
void sync_sequence_bounds()
{
if (m_seq_handle.has_value() && m_seq_handle->seq != nullptr) {
m_seq_handle->seq->update_step_bounds(
m_seq_handle->index, m_min_calls, m_max_calls);
}
}
template <std::size_t... Is>
bool match_impl(Args... args, std::index_sequence<Is...>) const
bool match_impl(const Args&... args,
std::index_sequence<Is...>) const
{
return (std::get<Is>(m_matchers).matches(args) && ...);
}
template <std::size_t... Is>
std::size_t max_depth_impl(std::index_sequence<Is...>) const noexcept
{
std::size_t d = 0;
((d = std::max(d, std::get<Is>(m_matchers).depth())), ...);
return d;
}
template <std::size_t... Is>
std::string describe_impl(std::index_sequence<Is...>) const
{
+349 -5
View File
@@ -3,15 +3,20 @@
#include <Void/Testing/Assert.hpp>
#include <concepts>
#include <cstddef>
#include <format>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::TestingMock
{
inline constexpr std::size_t kMaxMatcherDepth = 32;
template <typename T> class Matcher
{
public:
@@ -19,6 +24,10 @@ namespace Void::TestingMock
virtual ~Matcher() = default;
virtual bool matches(const T& value) const = 0;
virtual std::string describe() const = 0;
[[nodiscard]] virtual std::size_t depth() const noexcept
{
return 1;
}
};
// ---------------------------------------------------------------------
@@ -42,6 +51,29 @@ namespace Void::TestingMock
}
};
template <typename T> class NeMatcher : public Matcher<T>
{
T m_unexpected;
public:
explicit NeMatcher(T unexpected)
: m_unexpected(std::move(unexpected))
{
}
bool matches(const T& v) const override
{
return v != m_unexpected;
}
std::string describe() const override
{
return std::format("Ne({})",
Void::Testing::Detail::repr(m_unexpected));
}
};
template <typename T> class AnyMatcher : public Matcher<T>
{
public:
@@ -171,6 +203,29 @@ namespace Void::TestingMock
}
};
template <typename T> class EndsWithMatcher : public Matcher<T>
{
std::string m_suffix;
public:
explicit EndsWithMatcher(std::string suffix)
: m_suffix(std::move(suffix))
{
}
bool matches(const T& v) const override
{
const std::string_view sv{v};
return sv.ends_with(m_suffix);
}
std::string describe() const override
{
return std::format("EndsWith(\"{}\")", m_suffix);
}
};
template <typename T> class ContainsMatcher : public Matcher<T>
{
std::string m_needle;
@@ -194,6 +249,155 @@ namespace Void::TestingMock
}
};
template <typename T> class IsNullMatcher : public Matcher<T>
{
public:
bool matches(const T& v) const override { return v == nullptr; }
std::string describe() const override { return "IsNull()"; }
};
template <typename T> class NotNullMatcher : public Matcher<T>
{
public:
bool matches(const T& v) const override { return v != nullptr; }
std::string describe() const override { return "NotNull()"; }
};
template <typename T> class NotMatcher : public Matcher<T>
{
std::shared_ptr<const Matcher<T>> m_inner;
std::size_t m_depth{2};
public:
explicit NotMatcher(std::shared_ptr<const Matcher<T>> inner)
: m_inner(std::move(inner)),
m_depth(m_inner ? (m_inner->depth() + 1U) : 1U)
{
}
bool matches(const T& v) const override
{
return m_inner ? !m_inner->matches(v) : false;
}
std::string describe() const override
{
if (m_depth > kMaxMatcherDepth) {
return "Not(<depth-limit>)";
}
return std::format("Not({})",
m_inner ? m_inner->describe() : "<null>");
}
[[nodiscard]] std::size_t depth() const noexcept override
{
return m_depth;
}
};
template <typename T> class AllOfMatcher : public Matcher<T>
{
std::vector<std::shared_ptr<const Matcher<T>>> m_matchers;
std::size_t m_depth{2};
public:
explicit AllOfMatcher(
std::vector<std::shared_ptr<const Matcher<T>>> matchers)
: m_matchers(std::move(matchers))
{
std::size_t max_child = 0;
for (const auto& m : m_matchers) {
if (m && m->depth() > max_child) {
max_child = m->depth();
}
}
m_depth = max_child + 1U;
}
bool matches(const T& v) const override
{
for (const auto& m : m_matchers) {
if (!m || !m->matches(v)) {
return false;
}
}
return true;
}
std::string describe() const override
{
if (m_depth > kMaxMatcherDepth) {
return "AllOf(<depth-limit>)";
}
std::string out{"AllOf("};
for (std::size_t i = 0; i < m_matchers.size(); ++i) {
if (i > 0) out += ", ";
out += m_matchers[i] ? m_matchers[i]->describe() : "<null>";
}
out += ")";
return out;
}
[[nodiscard]] std::size_t depth() const noexcept override
{
return m_depth;
}
};
template <typename T> class AnyOfMatcher : public Matcher<T>
{
std::vector<std::shared_ptr<const Matcher<T>>> m_matchers;
std::size_t m_depth{2};
public:
explicit AnyOfMatcher(
std::vector<std::shared_ptr<const Matcher<T>>> matchers)
: m_matchers(std::move(matchers))
{
std::size_t max_child = 0;
for (const auto& m : m_matchers) {
if (m && m->depth() > max_child) {
max_child = m->depth();
}
}
m_depth = max_child + 1U;
}
bool matches(const T& v) const override
{
for (const auto& m : m_matchers) {
if (m && m->matches(v)) {
return true;
}
}
return false;
}
std::string describe() const override
{
if (m_depth > kMaxMatcherDepth) {
return "AnyOf(<depth-limit>)";
}
std::string out{"AnyOf("};
for (std::size_t i = 0; i < m_matchers.size(); ++i) {
if (i > 0) out += ", ";
out += m_matchers[i] ? m_matchers[i]->describe() : "<null>";
}
out += ")";
return out;
}
[[nodiscard]] std::size_t depth() const noexcept override
{
return m_depth;
}
};
// ---------------------------------------------------------------------
// Factory functions
// ---------------------------------------------------------------------
@@ -203,6 +407,11 @@ namespace Void::TestingMock
return std::make_unique<EqMatcher<T>>(std::move(v));
}
template <typename T> auto Ne(T v)
{
return std::make_unique<NeMatcher<T>>(std::move(v));
}
template <typename T> auto _() { return std::make_unique<AnyMatcher<T>>(); }
template <typename T> auto Lt(T v)
@@ -243,37 +452,172 @@ namespace Void::TestingMock
return std::make_unique<StartsWithMatcher<T>>(std::move(prefix));
}
template <typename T = std::string> auto EndsWith(std::string suffix)
{
return std::make_unique<EndsWithMatcher<T>>(std::move(suffix));
}
template <typename T = std::string> auto Contains(std::string needle)
{
return std::make_unique<ContainsMatcher<T>>(std::move(needle));
}
template <typename T> auto IsNull()
{
return std::make_unique<IsNullMatcher<T>>();
}
template <typename T> auto NotNull()
{
return std::make_unique<NotNullMatcher<T>>();
}
template <typename T, typename Derived>
requires std::derived_from<Derived, Matcher<T>>
std::unique_ptr<Matcher<T>> Not(std::unique_ptr<Derived> inner)
{
return std::make_unique<NotMatcher<T>>(
std::shared_ptr<const Matcher<T>>(std::move(inner)));
}
template <typename Derived>
auto Not(std::unique_ptr<Derived> inner)
{
// Extract T from Matcher<T> via helper overload below if needed.
return std::unique_ptr<Derived>{std::move(inner)};
}
namespace Detail
{
template <typename T> struct MatcherValueType;
template <typename T> struct MatcherValueType<Matcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<EqMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<NeMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<AnyMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<LtMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<LeMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<GtMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<GeMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<RangeMatcher<T>> {
using type = T;
};
template <typename T, typename Fn>
struct MatcherValueType<PredMatcher<T, Fn>> {
using type = T;
};
template <typename T> struct MatcherValueType<StartsWithMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<EndsWithMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<ContainsMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<IsNullMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<NotNullMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<NotMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<AllOfMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<AnyOfMatcher<T>> {
using type = T;
};
} // namespace Detail
template <typename M>
requires requires { typename Detail::MatcherValueType<M>::type; }
auto NotOf(std::unique_ptr<M> inner)
{
using T = typename Detail::MatcherValueType<M>::type;
return std::make_unique<NotMatcher<T>>(
std::shared_ptr<const Matcher<T>>(std::move(inner)));
}
template <typename T, typename... Ms>
std::unique_ptr<Matcher<T>> AllOf(std::unique_ptr<Ms>... matchers)
{
std::vector<std::shared_ptr<const Matcher<T>>> vec;
vec.reserve(sizeof...(Ms));
(vec.emplace_back(std::shared_ptr<const Matcher<T>>(std::move(matchers))),
...);
return std::make_unique<AllOfMatcher<T>>(std::move(vec));
}
template <typename T, typename... Ms>
std::unique_ptr<Matcher<T>> AnyOf(std::unique_ptr<Ms>... matchers)
{
std::vector<std::shared_ptr<const Matcher<T>>> vec;
vec.reserve(sizeof...(Ms));
(vec.emplace_back(std::shared_ptr<const Matcher<T>>(std::move(matchers))),
...);
return std::make_unique<AnyOfMatcher<T>>(std::move(vec));
}
// ---------------------------------------------------------------------
// MatcherHolder — owns a Matcher<T> or wraps an exact value as Eq
// MatcherHolder — owns a shared immutable Matcher<T> or exact Eq value
// ---------------------------------------------------------------------
template <typename T> class MatcherHolder
{
std::unique_ptr<Matcher<T>> m_matcher;
std::shared_ptr<const Matcher<T>> m_matcher;
public:
MatcherHolder() : m_matcher(std::make_unique<AnyMatcher<T>>()) {}
MatcherHolder() : m_matcher(std::make_shared<AnyMatcher<T>>()) {}
MatcherHolder(std::unique_ptr<Matcher<T>> m)
template <typename Derived>
requires std::derived_from<Derived, Matcher<T>>
MatcherHolder(std::unique_ptr<Derived> m)
: m_matcher(std::shared_ptr<const Matcher<T>>(std::move(m)))
{
}
MatcherHolder(std::shared_ptr<const Matcher<T>> m)
: m_matcher(std::move(m))
{
}
template <typename U = T>
requires(std::same_as<std::decay_t<U>, T> &&
std::equality_comparable<T> && std::movable<T>)
MatcherHolder(T exact_value)
: m_matcher(
std::make_unique<EqMatcher<T>>(std::move(exact_value)))
std::make_shared<EqMatcher<T>>(std::move(exact_value)))
{
}
bool matches(const T& v) const { return m_matcher->matches(v); }
std::string describe() const { return m_matcher->describe(); }
[[nodiscard]] std::size_t depth() const noexcept
{
return m_matcher ? m_matcher->depth() : 0;
}
};
} // namespace Void::TestingMock
+347 -15
View File
@@ -3,12 +3,18 @@
#include <Void/Testing/Assert.hpp>
#include <Void/TestingMock/Expectation.hpp>
#include <Void/TestingMock/Mock.hpp>
#include <Void/TestingMock/Session.hpp>
#include <condition_variable>
#include <cstddef>
#include <exception>
#include <format>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::TestingMock
@@ -17,7 +23,8 @@ namespace Void::TestingMock
template <typename> class MockFunction;
template <typename R, typename... Args>
class MockFunction<R(Args...)> : public Detail::MockFunctionBase
class MockFunction<R(Args...)> : public Detail::MockFunctionBase,
public Detail::SessionParticipant
{
using Expectation = Detail::Expectation<R(Args...)>;
@@ -39,13 +46,84 @@ namespace Void::TestingMock
owner.register_function(this);
}
~MockFunction() override { verify(); }
/// Session-backed constructor — registers dynamically with
/// `session` via RAII RegistrationToken and uses action-outside-lock
/// reservation with bounded structured diagnostics.
MockFunction(MockSession& session,
std::string name = "unnamed_mock")
: m_name(std::move(name)), m_session_state(session.state()),
m_token(session.register_participant(*this))
{
}
~MockFunction() override
{
if (m_session_state) {
m_token.unregister();
} else {
verify();
}
}
MockFunction(const MockFunction&) = delete;
MockFunction& operator=(const MockFunction&) = delete;
MockFunction(MockFunction&&) = delete;
MockFunction& operator=(MockFunction&&) = delete;
/// Checked expectation registration for session-backed mocks:
/// rejects mutations after `freeze()` and enforces `MockLimits`.
template <typename... MArgs>
[[nodiscard]] Void::Result::Result<Expectation*>
try_expect(std::source_location loc, MArgs&&... matchers)
{
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
if (m_session_state->frozen || m_session_state->closed) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidState,
"TestingMock: cannot register expectation on "
"frozen or closed session")};
}
if (sizeof...(MArgs) >
m_session_state->limits.max_matchers) {
return std::unexpected{make_mock_error(
MockErrorCode::LimitExceeded,
"TestingMock: matcher count exceeds MockLimits")};
}
if (m_session_state->expectation_count >=
m_session_state->limits.max_expectations) {
return std::unexpected{make_mock_error(
MockErrorCode::LimitExceeded,
"TestingMock: expectation count exceeds "
"MockLimits")};
}
++m_session_state->expectation_count;
}
auto exp = std::make_shared<Expectation>(
typename Expectation::MatcherTuple{
MatcherHolder<std::decay_t<Args>>(
std::forward<MArgs>(matchers))...},
loc);
if (exp->max_matcher_depth() > kMaxMatcherDepth) {
return std::unexpected{make_mock_error(
MockErrorCode::LimitExceeded,
"TestingMock: matcher nesting depth exceeds 32")};
}
std::lock_guard lock{m_mutex};
m_expectations.push_back(exp);
return exp.get();
}
template <typename... MArgs>
[[nodiscard]] Void::Result::Result<Expectation*>
try_expect(MArgs&&... matchers)
{
return try_expect(std::source_location::current(),
std::forward<MArgs>(matchers)...);
}
template <typename... MArgs>
Expectation& expect(std::source_location loc, MArgs&&... matchers)
{
@@ -54,6 +132,11 @@ namespace Void::TestingMock
MatcherHolder<std::decay_t<Args>>(
std::forward<MArgs>(matchers))...},
loc);
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
++m_session_state->expectation_count;
}
std::lock_guard lock{m_mutex};
m_expectations.push_back(exp);
return *exp;
}
@@ -67,37 +150,276 @@ namespace Void::TestingMock
R operator()(Args... args)
{
std::lock_guard lock{m_mutex};
for (auto& exp : m_expectations) {
if (!exp->is_saturated() && exp->matches(args...)) {
exp->record_call();
return exp->execute(args...);
// 1. Check session concurrency/admission & increment in-flight.
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
if (m_session_state->closed) {
m_session_state->append_bounded(
m_session_state->report.unmatched,
std::format("call to {}({}) after session closed",
m_name, render_args(args...)));
return handle_unmatched_return("session closed");
}
if (m_session_state->frozen &&
m_session_state->concurrency ==
Concurrency::SingleThread &&
std::this_thread::get_id() !=
m_session_state->owner_thread) {
const std::string err = std::format(
"concurrent cross-thread call to {}({}) under "
"Concurrency::SingleThread",
m_name, render_args(args...));
m_session_state->append_bounded(
m_session_state->report.threading_errors, err);
return handle_unmatched_return(err);
}
++m_session_state->in_flight_calls;
}
struct InFlightGuard {
MockFunction* self;
bool local_admitted{false};
~InFlightGuard() noexcept
{
if (local_admitted) {
std::lock_guard lock{self->m_mutex};
if (self->m_local_in_flight > 0) {
--self->m_local_in_flight;
}
if (self->m_local_in_flight == 0) {
self->m_local_cv.notify_all();
}
}
if (self->m_session_state) {
std::lock_guard slock{
self->m_session_state->mutex};
if (self->m_session_state->in_flight_calls >
0) {
--self->m_session_state->in_flight_calls;
}
if (self->m_session_state->in_flight_calls ==
0) {
self->m_session_state->cv.notify_all();
}
}
}
} guard{this, false};
// 2. Snapshot candidate expectations under short lock.
std::vector<std::shared_ptr<Expectation>> candidates;
{
std::lock_guard lock{m_mutex};
if (m_stopped) {
const std::string err = std::format(
"call to {}({}) after mock unregistered", m_name,
render_args(args...));
record_unmatched_diagnostic(err);
return handle_unmatched_return(err);
}
++m_local_in_flight;
guard.local_admitted = true;
candidates = m_expectations;
}
// 3. Evaluate explicit prohibitions (never()) FIRST outside
// lock so zero-count prohibitions cannot be silently skipped.
for (const auto& exp : candidates) {
if (!exp->is_prohibited()) {
continue;
}
bool matched = false;
try {
matched = exp->matches(args...);
} catch (const std::exception& e) {
record_matcher_failure(e.what(), args...);
return handle_unmatched_return(e.what());
} catch (...) {
record_matcher_failure("unknown matcher exception",
args...);
return handle_unmatched_return("matcher exception");
}
if (matched) {
const std::string msg = std::format(
"prohibited call (never()) matched on {}({}): {}",
m_name, render_args(args...),
exp->describe_matchers());
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->append_bounded(
m_session_state->report.prohibited, msg);
m_session_state->record_event_locked(msg);
} else {
Void::Testing::fail(msg);
}
return handle_unmatched_return(msg);
}
}
Void::Testing::fail(build_unmatched_message(args...));
if constexpr (!std::is_same_v<R, void>) {
return R{};
// 4. Evaluate ordinary matchers outside lock, then reacquire
// lock to reserve the winning unsaturated candidate. Retry
// remaining candidates if another thread saturated it first.
std::shared_ptr<Expectation> reserved;
typename Expectation::Action once_action;
bool use_once_action = false;
for (const auto& exp : candidates) {
if (exp->is_prohibited()) {
continue;
}
bool matched = false;
try {
matched = exp->matches(args...);
} catch (const std::exception& e) {
record_matcher_failure(e.what(), args...);
return handle_unmatched_return(e.what());
} catch (...) {
record_matcher_failure("unknown matcher exception",
args...);
return handle_unmatched_return("matcher exception");
}
if (!matched) {
continue;
}
std::lock_guard lock{m_mutex};
if (exp->try_reserve()) {
reserved = exp;
if (exp->is_once_action()) {
once_action = exp->take_once_action();
use_once_action = true;
}
break;
}
}
if (!reserved) {
std::string msg;
{
std::lock_guard lock{m_mutex};
msg = build_unmatched_message_locked(args...);
}
record_unmatched_diagnostic(msg);
return handle_unmatched_return(msg);
}
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->record_event_locked(std::format(
"{}({}) -> matched {}", m_name, render_args(args...),
reserved->describe_matchers()));
}
// 5. Execute action strictly OUTSIDE locks so reentrant and
// concurrent actions never deadlock on MockFunction::m_mutex.
Detail::ActionDepthGuard depth_guard;
if (use_once_action) {
return Expectation::execute_action(
once_action, std::forward<Args>(args)...);
}
return reserved->execute(std::forward<Args>(args)...);
}
void verify() override
{
for (auto& exp : m_expectations) {
std::vector<std::shared_ptr<Expectation>> snap;
{
std::lock_guard lock{m_mutex};
snap = std::move(m_expectations);
m_expectations.clear();
}
for (auto& exp : snap) {
exp->verify(m_name);
}
m_expectations.clear();
}
// -------- SessionParticipant implementation --------
[[nodiscard]] Void::Result::Result<void>
validate_for_freeze() const override
{
std::lock_guard lock{m_mutex};
for (const auto& exp : m_expectations) {
if (!exp->valid_bounds()) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidRange,
std::format("TestingMock: invalid call bounds "
"(min={} > max={}) on {}",
exp->min_calls(), exp->max_calls(),
m_name))};
}
}
return {};
}
void collect_verification(Verification& out) override
{
std::lock_guard lock{m_mutex};
for (const auto& exp : m_expectations) {
exp->collect_verification(m_name, out);
}
}
void stop_admission_and_join() noexcept override
{
std::unique_lock lock{m_mutex};
m_stopped = true;
m_local_cv.wait(lock, [this] { return m_local_in_flight == 0; });
}
private:
std::string m_name;
mutable std::mutex m_mutex;
std::condition_variable m_local_cv;
std::vector<std::shared_ptr<Expectation>> m_expectations;
std::mutex m_mutex;
std::size_t m_local_in_flight{0};
bool m_stopped{false};
std::shared_ptr<Detail::SessionState> m_session_state{};
RegistrationToken m_token{};
void record_unmatched_diagnostic(const std::string& msg)
{
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->append_bounded(
m_session_state->report.unmatched, msg);
m_session_state->record_event_locked(msg);
} else {
Void::Testing::fail(msg);
}
}
void record_matcher_failure(std::string_view what,
const Args&... args)
{
const std::string msg = std::format(
"matcher threw on {}({}): {}", m_name, render_args(args...),
what);
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->append_bounded(
m_session_state->report.matcher_errors, msg);
m_session_state->record_event_locked(msg);
} else {
Void::Testing::fail(msg);
}
}
R handle_unmatched_return(const std::string& msg)
{
if constexpr (std::is_same_v<R, void>) {
return;
} else if constexpr (std::is_default_constructible_v<R>) {
return R{};
} else {
throw InvocationAbortException(msg);
}
}
/// Build a multi-line error message that names the actual
/// arguments and lists every registered expectation with its
/// matcher tuple and call counts.
std::string build_unmatched_message(const Args&... args) const
std::string
build_unmatched_message_locked(const Args&... args) const
{
std::string msg =
std::format("no expectation matched call to {}({})", m_name,
@@ -115,6 +437,16 @@ namespace Void::TestingMock
return msg;
}
template <typename T>
static std::string render_one_arg(const T& a)
{
if constexpr (requires { Void::Testing::Detail::repr(a); }) {
return Void::Testing::Detail::repr(a);
} else {
return "<non-printable>";
}
}
static std::string render_args(const Args&... args)
{
std::string out;
@@ -123,7 +455,7 @@ namespace Void::TestingMock
if (!first) {
out += ", ";
}
out += Void::Testing::Detail::repr(a);
out += render_one_arg(a);
first = false;
};
(append(args), ...);
+531
View File
@@ -0,0 +1,531 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace Void::TestingMock
{
enum class MockErrorCode : std::int32_t {
None = 0,
InvalidState = 1,
LimitExceeded = 2,
InvalidRange = 3,
WouldDeadlock = 4,
ThreadingViolation = 5,
MatcherFailure = 6,
ProhibitedCall = 7,
UnmatchedCall = 8,
};
[[nodiscard]] inline Void::Result::Error
make_mock_error(MockErrorCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case MockErrorCode::None:
kind = ErrorKind::internal;
break;
case MockErrorCode::InvalidState:
case MockErrorCode::InvalidRange:
case MockErrorCode::WouldDeadlock:
case MockErrorCode::ThreadingViolation:
kind = ErrorKind::invalid_argument;
break;
case MockErrorCode::LimitExceeded:
kind = ErrorKind::exhausted;
break;
case MockErrorCode::MatcherFailure:
case MockErrorCode::ProhibitedCall:
case MockErrorCode::UnmatchedCall:
kind = ErrorKind::conflict;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kTestingMockErrorDomain,
static_cast<std::int32_t>(code)}};
}
enum class Concurrency : std::uint8_t {
SingleThread,
ConcurrentActions,
};
struct MockLimits {
std::size_t max_expectations{1024};
std::size_t max_matchers{64};
std::size_t max_events{4096};
std::size_t max_diagnostic_bytes{4ULL * 1024 * 1024};
std::size_t max_arg_render_bytes{4ULL * 1024};
};
/// Thrown when an unmatched or prohibited invocation occurs on a mock with
/// a non-default-constructible return type, after recording the failure.
class InvocationAbortException : public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};
/// Explicit call-order group shared across one or more expectations.
/// Independent of global expectation registration order.
class Sequence final
{
public:
Sequence() = default;
Sequence(const Sequence&) = delete;
Sequence& operator=(const Sequence&) = delete;
struct StepHandle {
Sequence* seq{nullptr};
std::size_t index{0};
};
StepHandle add_step(int min_calls, int max_calls)
{
std::lock_guard lock{m_mutex};
const std::size_t idx = m_steps.size();
m_steps.push_back(Step{min_calls, max_calls, 0});
return StepHandle{this, idx};
}
void update_step_bounds(std::size_t index, int min_calls,
int max_calls)
{
std::lock_guard lock{m_mutex};
if (index < m_steps.size()) {
m_steps[index].min_calls = min_calls;
m_steps[index].max_calls = max_calls;
}
}
[[nodiscard]] bool is_eligible(std::size_t index) const
{
std::lock_guard lock{m_mutex};
if (index < m_cursor || index >= m_steps.size()) {
return false;
}
for (std::size_t j = m_cursor; j < index; ++j) {
if (m_steps[j].reserved < m_steps[j].min_calls) {
return false;
}
}
return m_steps[index].reserved < m_steps[index].max_calls;
}
[[nodiscard]] bool try_reserve(std::size_t index)
{
std::lock_guard lock{m_mutex};
if (index < m_cursor || index >= m_steps.size()) {
return false;
}
for (std::size_t j = m_cursor; j < index; ++j) {
if (m_steps[j].reserved < m_steps[j].min_calls) {
return false;
}
}
if (m_steps[index].reserved >= m_steps[index].max_calls) {
return false;
}
m_cursor = index;
++m_steps[index].reserved;
if (m_steps[index].reserved >= m_steps[index].max_calls) {
m_cursor = index + 1U;
}
return true;
}
[[nodiscard]] std::size_t cursor() const
{
std::lock_guard lock{m_mutex};
return m_cursor;
}
private:
struct Step {
int min_calls{1};
int max_calls{1};
int reserved{0};
};
mutable std::mutex m_mutex;
std::vector<Step> m_steps;
std::size_t m_cursor{0};
};
struct Verification {
std::vector<std::string> unmet{};
std::vector<std::string> excess{};
std::vector<std::string> unmatched{};
std::vector<std::string> prohibited{};
std::vector<std::string> matcher_errors{};
std::vector<std::string> threading_errors{};
std::vector<std::string> events{};
std::uint64_t total_events{0};
bool events_truncated{false};
[[nodiscard]] bool ok() const noexcept
{
return unmet.empty() && excess.empty() && unmatched.empty() &&
prohibited.empty() && matcher_errors.empty() &&
threading_errors.empty();
}
[[nodiscard]] std::string format() const
{
if (ok()) {
return std::format("MockSession OK ({} events)",
total_events);
}
std::string out = "MockSession verification failed:";
auto append_group = [&](std::string_view label,
const std::vector<std::string>& items) {
for (const auto& s : items) {
out += std::format("\n [{}] {}", label, s);
}
};
append_group("unmet", unmet);
append_group("excess", excess);
append_group("unmatched", unmatched);
append_group("prohibited", prohibited);
append_group("matcher", matcher_errors);
append_group("threading", threading_errors);
if (events_truncated) {
out += std::format("\n (event log truncated; {} total)",
total_events);
}
return out;
}
};
namespace Detail
{
inline thread_local std::size_t g_active_mock_action_depth = 0;
struct ActionDepthGuard {
ActionDepthGuard() noexcept { ++g_active_mock_action_depth; }
~ActionDepthGuard() noexcept { --g_active_mock_action_depth; }
};
class SessionParticipant
{
public:
virtual ~SessionParticipant() = default;
[[nodiscard]] virtual Void::Result::Result<void>
validate_for_freeze() const = 0;
virtual void collect_verification(Verification& out) = 0;
virtual void stop_admission_and_join() noexcept = 0;
};
struct SessionState {
MockLimits limits{};
mutable std::mutex mutex{};
std::condition_variable cv{};
bool frozen{false};
bool closed{false};
Concurrency concurrency{Concurrency::SingleThread};
std::thread::id owner_thread{std::this_thread::get_id()};
std::size_t expectation_count{0};
std::size_t in_flight_calls{0};
std::size_t diagnostic_bytes{0};
std::uint64_t next_reg_id{1};
struct RegisteredEntry {
std::uint64_t id{0};
SessionParticipant* participant{nullptr};
};
std::vector<RegisteredEntry> participants{};
Verification report{};
bool verified{false};
void append_bounded(std::vector<std::string>& vec,
std::string msg)
{
if (msg.size() > limits.max_arg_render_bytes &&
limits.max_arg_render_bytes > 16) {
msg.resize(limits.max_arg_render_bytes - 3U);
msg += "...";
}
if (diagnostic_bytes + msg.size() <=
limits.max_diagnostic_bytes) {
diagnostic_bytes += msg.size();
vec.push_back(std::move(msg));
} else {
report.events_truncated = true;
}
}
void record_event_locked(std::string ev)
{
++report.total_events;
if (limits.max_events == 0) {
report.events_truncated = true;
return;
}
if (report.events.size() < limits.max_events &&
diagnostic_bytes + ev.size() <=
limits.max_diagnostic_bytes) {
diagnostic_bytes += ev.size();
report.events.push_back(std::move(ev));
} else {
report.events_truncated = true;
// Keep bounded last sample when truncated.
if (!report.events.empty()) {
report.events.back() = std::move(ev);
}
}
}
};
} // namespace Detail
/// Move-only RAII registration handle for dynamic mocks attached to a
/// MockSession. Unregistering stops new admission and waits for in-flight
/// calls before returning so destroyed dynamic mocks cannot dangle.
class RegistrationToken final
{
public:
RegistrationToken() noexcept = default;
RegistrationToken(std::shared_ptr<Detail::SessionState> state,
std::uint64_t id,
Detail::SessionParticipant* participant) noexcept
: m_state(std::move(state)), m_id(id),
m_participant(participant)
{
}
~RegistrationToken() noexcept { unregister(); }
RegistrationToken(RegistrationToken&& other) noexcept
: m_state(std::move(other.m_state)),
m_id(std::exchange(other.m_id, 0)),
m_participant(std::exchange(other.m_participant, nullptr))
{
}
RegistrationToken& operator=(RegistrationToken&& other) noexcept
{
if (this != &other) {
unregister();
m_state = std::move(other.m_state);
m_id = std::exchange(other.m_id, 0);
m_participant = std::exchange(other.m_participant, nullptr);
}
return *this;
}
RegistrationToken(const RegistrationToken&) = delete;
RegistrationToken& operator=(const RegistrationToken&) = delete;
[[nodiscard]] bool active() const noexcept
{
return m_state != nullptr && m_id != 0;
}
void unregister() noexcept
{
if (!m_state || m_id == 0) {
return;
}
Detail::SessionParticipant* p =
std::exchange(m_participant, nullptr);
const std::uint64_t id = std::exchange(m_id, 0);
auto state = std::move(m_state);
if (p != nullptr) {
p->stop_admission_and_join();
}
std::lock_guard lock{state->mutex};
std::erase_if(state->participants,
[id](const auto& e) { return e.id == id; });
}
private:
std::shared_ptr<Detail::SessionState> m_state{};
std::uint64_t m_id{0};
Detail::SessionParticipant* m_participant{nullptr};
};
/// Explicit mock lifecycle controller owning limits, freeze state,
/// concurrency policy, dynamic registration tokens, and idempotent
/// structured verification.
class MockSession final
{
public:
explicit MockSession(MockLimits limits = {})
: m_state(std::make_shared<Detail::SessionState>())
{
m_state->limits = limits;
m_state->owner_thread = std::this_thread::get_id();
}
~MockSession() noexcept
{
if (m_state && Detail::g_active_mock_action_depth == 0) {
(void)verify_and_close();
}
}
MockSession(const MockSession&) = delete;
MockSession& operator=(const MockSession&) = delete;
MockSession(MockSession&&) noexcept = default;
MockSession& operator=(MockSession&&) noexcept = default;
[[nodiscard]] const MockLimits& limits() const noexcept
{
return m_state->limits;
}
[[nodiscard]] bool is_frozen() const
{
std::lock_guard lock{m_state->mutex};
return m_state->frozen;
}
[[nodiscard]] bool is_closed() const
{
std::lock_guard lock{m_state->mutex};
return m_state->closed;
}
[[nodiscard]] RegistrationToken
register_participant(Detail::SessionParticipant& participant)
{
std::lock_guard lock{m_state->mutex};
const std::uint64_t id = m_state->next_reg_id++;
m_state->participants.push_back({id, &participant});
return RegistrationToken{m_state, id, &participant};
}
/// Freeze expectation registration and lock in the concurrency mode.
[[nodiscard]] Void::Result::Result<void>
freeze(Concurrency mode = Concurrency::SingleThread)
{
std::vector<Detail::SessionParticipant*> snapshot;
{
std::lock_guard lock{m_state->mutex};
if (m_state->closed) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidState,
"TestingMock::MockSession: session already closed")};
}
if (m_state->frozen) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidState,
"TestingMock::MockSession: session already frozen")};
}
for (const auto& e : m_state->participants) {
if (e.participant != nullptr) {
snapshot.push_back(e.participant);
}
}
}
for (auto* p : snapshot) {
auto vr = p->validate_for_freeze();
if (!vr.has_value()) {
return vr;
}
}
{
std::lock_guard lock{m_state->mutex};
m_state->frozen = true;
m_state->concurrency = mode;
m_state->owner_thread = std::this_thread::get_id();
}
return {};
}
/// Stop admission, wait for active calls to finish, and return an
/// idempotent structured Verification report.
[[nodiscard]] Void::Result::Result<Verification> verify_and_close()
{
if (Detail::g_active_mock_action_depth > 0) {
return std::unexpected{make_mock_error(
MockErrorCode::WouldDeadlock,
"TestingMock::MockSession::verify_and_close cannot be "
"called synchronously from inside an active mock "
"action")};
}
std::vector<Detail::SessionParticipant*> snapshot;
{
std::unique_lock lock{m_state->mutex};
if (m_state->verified) {
return m_state->report;
}
m_state->closed = true;
m_state->frozen = true;
for (const auto& e : m_state->participants) {
if (e.participant != nullptr) {
snapshot.push_back(e.participant);
}
}
}
for (auto* p : snapshot) {
p->stop_admission_and_join();
}
std::unique_lock lock{m_state->mutex};
m_state->cv.wait(
lock, [&] { return m_state->in_flight_calls == 0; });
if (!m_state->verified) {
for (auto* p : snapshot) {
p->collect_verification(m_state->report);
}
m_state->verified = true;
}
return m_state->report;
}
[[nodiscard]] const std::shared_ptr<Detail::SessionState>&
state() const noexcept
{
return m_state;
}
private:
std::shared_ptr<Detail::SessionState> m_state;
};
[[nodiscard]] inline Void::Result::Result<void>
freeze(MockSession& session,
Concurrency mode = Concurrency::SingleThread)
{
return session.freeze(mode);
}
[[nodiscard]] inline Void::Result::Result<Verification>
verify_and_close(MockSession& session)
{
return session.verify_and_close();
}
} // namespace Void::TestingMock
+44
View File
@@ -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
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Discovery
INTERNAL_DEPS Core Functional Time Async
)
+144
View File
@@ -0,0 +1,144 @@
#include <Void/DiscoveryRpc/EndpointAdapter.hpp>
#include <algorithm>
#include <utility>
namespace Void::DiscoveryRpc
{
namespace
{
struct OutstandingGuard {
std::atomic<std::size_t>& counter;
~OutstandingGuard() noexcept
{
counter.fetch_sub(1, std::memory_order_acq_rel);
}
};
} // namespace
EndpointResolverClient::EndpointResolverClient(
const Void::Discovery::Catalog& catalog,
EndpointResolverOptions options)
: m_catalog(&catalog), m_options(std::move(options))
{
if (m_options.clock == nullptr) {
m_options.clock = &Void::Time::SystemMonotonicClock::instance();
}
if (m_options.require_tls) {
m_options.http_options.verify_tls = true;
}
}
Void::Discovery::Result<SelectedEndpoint>
EndpointResolverClient::select_endpoint(
std::optional<std::string_view> affinity_key)
{
if (m_catalog == nullptr) {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::InvalidArgument,
"EndpointResolverClient: null catalog"));
}
auto snap =
m_catalog->resolve(m_options.service, m_options.resolve_policy);
if (!snap.has_value()) {
return Void::Result::fail(snap.error());
}
auto selected =
affinity_key.has_value()
? Void::Discovery::AffinitySelector::select(*snap, *affinity_key)
: m_rr.select(*snap);
if (!selected.has_value()) {
return Void::Result::fail(selected.error());
}
if (m_options.require_tls && selected->endpoint.scheme != "https") {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::TlsIdentityMismatch,
"EndpointResolverClient: refusing non-TLS endpoint when "
"require_tls is enabled"));
}
const std::string effective_tls{
selected->endpoint.effective_tls_name()};
if (!m_options.expected_tls_name.empty() &&
effective_tls != m_options.expected_tls_name) {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::TlsIdentityMismatch,
"EndpointResolverClient: endpoint TLS identity mismatch "
"(expected '" +
m_options.expected_tls_name + "', got '" + effective_tls +
"')"));
}
SelectedEndpoint out{};
out.origin_url = selected->endpoint.to_origin_url();
out.effective_tls_name = effective_tls;
out.record = std::move(*selected);
return out;
}
Void::Result::Result<Void::RPC::OwnedBytes>
EndpointResolverClient::call(
Void::RPC::MethodId method, Void::RPC::OwnedBytes payload,
Void::RPC::CallOptions options,
std::optional<std::string_view> affinity_key)
{
// Enforce bounded outstanding operations.
std::size_t cur = m_outstanding.load(std::memory_order_acquire);
for (;;) {
if (cur >= m_options.max_outstanding_ops) {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::LimitExceeded,
"EndpointResolverClient: max_outstanding_ops reached"));
}
if (m_outstanding.compare_exchange_weak(
cur, cur + 1, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
OutstandingGuard guard{m_outstanding};
auto selected = select_endpoint(affinity_key);
if (!selected.has_value()) {
return Void::Result::fail(selected.error());
}
Void::RPC::ClientOptions copts{};
copts.endpoint_base_url = selected->origin_url;
copts.http_options = m_options.http_options;
if (m_options.require_tls) {
copts.http_options.verify_tls = true;
}
copts.limits = m_options.rpc_limits;
copts.clock = m_options.clock;
if (options.timeout <= std::chrono::milliseconds{0} ||
options.timeout > m_options.total_deadline) {
options.timeout = m_options.total_deadline;
}
// Retain peer identity header when address refreshes to an IP while
// expected_tls_name preserves the logical authority.
if (!selected->record.endpoint.expected_tls_name.empty()) {
bool has_authority = false;
for (const auto& m : options.metadata) {
if (m.key == "void-expected-authority") {
has_authority = true;
break;
}
}
if (!has_authority) {
options.metadata.push_back(Void::RPC::MetadataEntry{
.key = "void-expected-authority",
.value = selected->effective_tls_name,
});
}
}
Void::RPC::Client client{std::move(copts)};
return client.call(method, std::move(payload), options);
}
} // namespace Void::DiscoveryRpc
+3
View File
@@ -0,0 +1,3 @@
void_add_module(DiscoveryRpc
INTERNAL_DEPS Discovery RPC
)
+1567 -355
View File
File diff suppressed because it is too large. Load diff
+743
View File
@@ -0,0 +1,743 @@
#include "FileWorkers.hpp"
#include <Void/IO/Driver.hpp>
#include <cerrno>
#include <cstdio>
#include <exception>
#include <iterator>
#include <string>
#include <system_error>
#include <utility>
#if defined(__unix__) || defined(__APPLE__)
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#define VOID_IO_POSIX_FILES 1
#endif
namespace Void::IO
{
namespace
{
thread_local const detail::FileWorkerShared* tl_io_worker_owner = nullptr;
} // namespace
bool is_io_worker_thread() noexcept
{
return tl_io_worker_owner != nullptr;
}
// ── FileSyscalls (native) ────────────────────────────────────────────────────
FileSyscallResult FileSyscalls::pread(int fd, std::span<std::byte> buf, std::uint64_t offset) noexcept
{
#ifdef VOID_IO_POSIX_FILES
const ssize_t n = ::pread(fd, buf.data(), buf.size(), static_cast<off_t>(offset));
if (n < 0) {
return FileSyscallResult{-1, errno};
}
return FileSyscallResult{static_cast<std::int64_t>(n), 0};
#else
(void)fd;
(void)buf;
(void)offset;
return FileSyscallResult{-1, ENOSYS};
#endif
}
FileSyscallResult FileSyscalls::pwrite(int fd,
std::span<const std::byte> buf,
std::uint64_t offset) noexcept
{
#ifdef VOID_IO_POSIX_FILES
const ssize_t n = ::pwrite(fd, buf.data(), buf.size(), static_cast<off_t>(offset));
if (n < 0) {
return FileSyscallResult{-1, errno};
}
return FileSyscallResult{static_cast<std::int64_t>(n), 0};
#else
(void)fd;
(void)buf;
(void)offset;
return FileSyscallResult{-1, ENOSYS};
#endif
}
FileSyscallResult FileSyscalls::sync(int fd, SyncMode mode) noexcept
{
#ifdef VOID_IO_POSIX_FILES
int rc = 0;
#if defined(__linux__)
rc = (mode == SyncMode::data) ? ::fdatasync(fd) : ::fsync(fd);
#else
(void)mode;
rc = ::fsync(fd);
#endif
if (rc != 0) {
return FileSyscallResult{-1, errno};
}
return FileSyscallResult{0, 0};
#else
(void)fd;
(void)mode;
return FileSyscallResult{-1, ENOSYS};
#endif
}
FileSyscallResult FileSyscalls::close(int fd) noexcept
{
#ifdef VOID_IO_POSIX_FILES
if (::close(fd) != 0) {
return FileSyscallResult{-1, errno};
}
return FileSyscallResult{0, 0};
#else
(void)fd;
return FileSyscallResult{-1, ENOSYS};
#endif
}
FileSyscalls& FileSyscalls::native() noexcept
{
static FileSyscalls instance;
return instance;
}
} // namespace Void::IO
namespace Void::IO::detail
{
namespace
{
[[nodiscard]] std::error_code errno_code(int err) noexcept
{
return std::error_code{err, std::generic_category()};
}
void worker_main(std::shared_ptr<FileWorkerShared> shared) noexcept
{
tl_io_worker_owner = shared.get();
FileWorkerShared& p = *shared;
std::unique_lock lk{p.mu};
for (;;) {
p.work_cv.wait(lk, [&p] {
return p.exit_requested || p.rollback_requested || p.has_runnable_locked();
});
if (p.exit_requested || p.rollback_requested) {
break;
}
bool settled = false;
std::shared_ptr<FileRequest> req = p.take_next_locked(settled);
if (!req) {
if (settled) {
lk.unlock();
p.wake();
lk.lock();
}
continue;
}
lk.unlock();
const FileSyscallResult result = execute_file_request(*req);
lk.lock();
p.finish_locked(*req, result);
const bool idle = p.active.empty();
// `completions` still owns the request, so this never destroys it.
req.reset();
lk.unlock();
p.work_cv.notify_all();
if (idle) {
p.idle_cv.notify_all();
}
p.wake();
lk.lock();
}
if (p.running_workers > 0) {
--p.running_workers;
}
p.publish_counts_locked();
lk.unlock();
p.idle_cv.notify_all();
tl_io_worker_owner = nullptr;
}
} // namespace
const FileWorkerShared* current_io_worker_owner() noexcept
{
return tl_io_worker_owner;
}
// ── FileState ────────────────────────────────────────────────────────────────
FileState::FileState(std::shared_ptr<FileWorkerShared> pool_in,
std::weak_ptr<DriverBackend> backend_in,
FileSyscalls* syscalls_in,
int fd_in,
DescriptorId id_in)
: pool(std::move(pool_in))
, backend(std::move(backend_in))
, syscalls(syscalls_in)
, id(id_in)
, fd(fd_in)
{
auto close_req = std::make_shared<FileRequest>();
close_req->kind = FileRequestKind::close;
close_node.push_back(std::move(close_req));
}
// ── FileWorkerShared ─────────────────────────────────────────────────────────
void FileWorkerShared::publish_counts_locked() noexcept
{
queued_count.store(queued.size(), std::memory_order_release);
active_count.store(active.size(), std::memory_order_release);
running_count.store(running_workers, std::memory_order_release);
}
bool FileWorkerShared::has_runnable_locked() const noexcept
{
if (!close_queued.empty()) {
return true;
}
for (const auto& r : queued) {
if (r->stop_requested || r->expired) {
return true;
}
if (!r->serialized() || !r->file->serial_active) {
return true;
}
}
return false;
}
std::shared_ptr<FileRequest> FileWorkerShared::take_next_locked(bool& settled_without_syscall) noexcept
{
settled_without_syscall = false;
if (exit_requested || rollback_requested) {
return nullptr;
}
if (!close_queued.empty()) {
auto it = close_queued.begin();
std::shared_ptr<FileRequest> req = *it;
active.splice(active.end(), close_queued, it);
req->phase = FileRequestPhase::active;
req->exec_fd = req->file ? req->file->fd : -1;
publish_counts_locked();
return req;
}
for (auto it = queued.begin(); it != queued.end();) {
FileRequest& r = **it;
auto next = std::next(it);
if (r.stop_requested || r.expired) {
// S3: decided under the mutex from flags set by the stop callback or
// by the last poll turn; the clock is never read on a worker.
settle_queued_locked(r, r.expired ? FileSettle::timeout : FileSettle::cancelled);
settled_without_syscall = true;
it = next;
continue;
}
if (r.serialized() && r.file->serial_active) {
it = next;
continue;
}
if (r.serialized()) {
r.file->serial_active = true;
}
std::shared_ptr<FileRequest> req = *it;
active.splice(active.end(), queued, it);
r.phase = FileRequestPhase::active;
r.exec_fd = r.file->fd;
publish_counts_locked();
return req;
}
return nullptr;
}
void FileWorkerShared::finish_locked(FileRequest& req, FileSyscallResult result) noexcept
{
req.result = result;
req.settle = FileSettle::syscall;
req.phase = FileRequestPhase::done;
if (req.file) {
FileState& f = *req.file;
if (req.serialized()) {
f.serial_active = false;
}
if (req.kind == FileRequestKind::close) {
// Whoever closes the fd marks the file closed. Linux closes the fd
// even when close() reports EINTR, so that is not an error.
f.status = FileState::Status::closed;
f.fd = -1;
f.close_error = (result.error == EINTR) ? 0 : result.error;
}
}
completions.splice(completions.end(), active, req.pos);
publish_counts_locked();
}
void FileWorkerShared::settle_queued_locked(FileRequest& req, FileSettle settle) noexcept
{
FileRequestList& from = (req.kind == FileRequestKind::close) ? close_queued : queued;
req.settle = settle;
req.phase = FileRequestPhase::done;
if (settle == FileSettle::timeout) {
req.expired = true;
}
completions.splice(completions.end(), from, req.pos);
publish_counts_locked();
}
void FileWorkerShared::enqueue_close_locked(FileState& file) noexcept
{
if (file.close_enqueued || file.close_node.empty()) {
return;
}
std::shared_ptr<FileState> self = file.weak_from_this().lock();
if (!self) {
return;
}
file.close_enqueued = true;
file.close_pending = false;
auto it = file.close_node.begin();
FileRequest& req = **it;
req.file = std::move(self);
req.phase = FileRequestPhase::queued;
close_queued.splice(close_queued.end(), file.close_node, it);
req.pos = it;
publish_counts_locked();
}
// ── Forwarders ───────────────────────────────────────────────────────────────
void FileCancelForwarder::operator()() const noexcept
{
auto req = request.lock();
if (!req || !req->file) {
return;
}
FileWorkerShared& pool = *req->file->pool;
bool removed = false;
{
std::lock_guard lk{pool.mu};
req->stop_requested = true;
if (req->phase == FileRequestPhase::queued && req->kind != FileRequestKind::close) {
pool.settle_queued_locked(*req, FileSettle::cancelled);
removed = true;
}
}
if (removed) {
if (auto b = req->file->backend.lock()) {
b->wake();
}
}
}
void FileWakeForwarder::operator()() const noexcept
{
if (auto b = backend.lock()) {
b->wake();
}
}
// ── Execution ────────────────────────────────────────────────────────────────
FileSyscallResult execute_file_request(const FileRequest& req) noexcept
{
FileSyscalls& sys = (req.file && req.file->syscalls != nullptr) ? *req.file->syscalls
: FileSyscalls::native();
const int fd = req.exec_fd;
for (;;) {
FileSyscallResult r{};
switch (req.kind) {
case FileRequestKind::read:
r = sys.pread(fd, std::span<std::byte>{req.read_ptr, req.len}, req.offset);
break;
case FileRequestKind::write:
r = sys.pwrite(fd, std::span<const std::byte>{req.write_ptr, req.len}, req.offset);
break;
case FileRequestKind::sync:
r = sys.sync(fd, req.mode);
break;
case FileRequestKind::close:
// Never retried: the descriptor is released even on EINTR.
return sys.close(fd);
}
if (r.error == EINTR) {
continue;
}
return r;
}
}
std::optional<std::size_t> run_file_requests_inline(FileWorkerShared& shared,
std::size_t max_requests)
{
std::unique_lock lk{shared.mu};
if (shared.running_workers > 0) {
return std::nullopt;
}
std::size_t done = 0;
while (done < max_requests) {
bool settled = false;
std::shared_ptr<FileRequest> req = shared.take_next_locked(settled);
if (!req) {
break;
}
lk.unlock();
const FileSyscallResult result = execute_file_request(*req);
lk.lock();
shared.finish_locked(*req, result);
req.reset();
++done;
}
const bool idle = shared.active.empty();
lk.unlock();
if (idle) {
shared.idle_cv.notify_all();
}
return done;
}
void file_handle_dropped(FileState& file) noexcept
{
FileWorkerShared& pool = *file.pool;
bool enqueued = false;
{
std::lock_guard lk{pool.mu};
if (file.status == FileState::Status::closed) {
return;
}
if (file.status == FileState::Status::open) {
file.status = FileState::Status::closing;
}
if (!file.close_enqueued) {
if (file.in_flight == 0) {
pool.enqueue_close_locked(file);
enqueued = true;
} else {
file.close_pending = true;
}
}
}
if (enqueued) {
pool.work_cv.notify_one();
if (auto b = file.backend.lock()) {
b->wake();
}
}
}
// ── Open helpers ─────────────────────────────────────────────────────────────
Void::Result::Result<void> validate_file_open_options(const FileOpenOptions& options)
{
if (!options.read && !options.write) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument, "FileOpenOptions needs read or write access")};
}
if (options.truncate && !options.write) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument, "FileOpenOptions::truncate requires write")};
}
if (options.exclusive && !options.create) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument, "FileOpenOptions::exclusive requires create")};
}
return {};
}
Void::Result::Result<int> open_file_native(const std::filesystem::path& path,
const FileOpenOptions& options)
{
#ifdef VOID_IO_POSIX_FILES
int flags = O_CLOEXEC;
if (options.read && options.write) {
flags |= O_RDWR;
} else if (options.write) {
flags |= O_WRONLY;
} else {
flags |= O_RDONLY;
}
if (options.create) {
flags |= O_CREAT;
}
if (options.truncate) {
flags |= O_TRUNC;
}
if (options.exclusive) {
flags |= O_EXCL;
}
int fd = -1;
for (;;) {
fd = ::open(path.c_str(), flags, static_cast<mode_t>(options.mode));
if (fd < 0 && errno == EINTR) {
continue;
}
break;
}
if (fd < 0) {
return std::unexpected{make_io_error(
IoErrorCode::os_error, "open failed for " + path.string(), errno_code(errno))};
}
return fd;
#else
(void)path;
(void)options;
return std::unexpected{make_io_error(
IoErrorCode::unsupported, "Positional files require a POSIX platform")};
#endif
}
// ── FileWorkers ──────────────────────────────────────────────────────────────
FileWorkers::~FileWorkers()
{
for (const auto& t : threads_) {
if (t.joinable()) {
std::fputs(
"Void::IO: file worker still running at backend destruction "
"(Driver teardown did not join it)\n",
stderr);
std::terminate();
}
}
}
Void::Result::Result<void> FileWorkers::start(
std::size_t count,
const std::function<Void::Result::Result<void>(std::size_t)>& hook)
{
std::lock_guard tl{threads_mu_};
if (started_) {
return std::unexpected{make_io_error(
IoErrorCode::invalid_argument, "start_file_workers was already called")};
}
{
std::lock_guard lk{shared_->mu};
if (!shared_->accepting || shared_->exit_requested) {
return std::unexpected{make_io_error(
IoErrorCode::closed, "IO Driver is shutting down")};
}
}
if (count == 0) {
started_ = true;
return {};
}
try {
threads_.reserve(count);
} catch (...) {
return std::unexpected{make_io_error(
IoErrorCode::os_error, "Cannot allocate file worker table",
std::make_error_code(std::errc::not_enough_memory))};
}
for (std::size_t i = 0; i < count; ++i) {
if (hook) {
Void::Result::Result<void> hr{};
try {
hr = hook(i);
} catch (const std::system_error& e) {
hr = std::unexpected{make_io_error(IoErrorCode::os_error, e.what(), e.code())};
} catch (...) {
rollback_locked();
throw;
}
if (!hr.has_value()) {
rollback_locked();
return std::unexpected{make_io_error(
IoErrorCode::os_error,
"before_file_worker_start failed for worker " + std::to_string(i) + ": " +
std::string{hr.error().message()},
hr.error().system_code())};
}
}
{
std::lock_guard lk{shared_->mu};
++shared_->running_workers;
shared_->publish_counts_locked();
}
try {
threads_.emplace_back(&worker_main, shared_);
} catch (const std::system_error& e) {
{
std::lock_guard lk{shared_->mu};
--shared_->running_workers;
shared_->publish_counts_locked();
}
rollback_locked();
return std::unexpected{make_io_error(
IoErrorCode::os_error, "Cannot create file worker thread", e.code())};
}
}
started_ = true;
return {};
}
void FileWorkers::rollback_locked() noexcept
{
{
std::lock_guard lk{shared_->mu};
shared_->rollback_requested = true;
}
shared_->work_cv.notify_all();
for (auto& t : threads_) {
if (t.joinable()) {
t.join();
}
}
threads_.clear();
{
std::lock_guard lk{shared_->mu};
shared_->rollback_requested = false;
}
// Requests queued meanwhile stay queued for a retried start or run_file_work.
shared_->work_cv.notify_all();
}
void FileWorkers::join_for_shutdown() noexcept
{
std::lock_guard tl{threads_mu_};
shared_->work_cv.notify_all();
for (auto& t : threads_) {
if (t.joinable()) {
t.join();
}
}
threads_.clear();
}
} // namespace Void::IO::detail
// ── File ─────────────────────────────────────────────────────────────────────
namespace Void::IO
{
File::File() noexcept = default;
File::File(std::shared_ptr<detail::FileState> state) noexcept
: state_(std::move(state))
{
}
File::File(File&& other) noexcept
: state_(std::move(other.state_))
{
}
File& File::operator=(File&& other) noexcept
{
if (this != &other) {
release_handle();
state_ = std::move(other.state_);
}
return *this;
}
File::~File()
{
release_handle();
}
void File::release_handle() noexcept
{
std::shared_ptr<detail::FileState> st = std::move(state_);
if (st) {
detail::file_handle_dropped(*st);
}
}
DescriptorId File::id() const noexcept
{
return state_ ? state_->id : DescriptorId{};
}
Coro::Task<Void::Result::Result<Transfer>> File::read_at(std::uint64_t offset,
std::span<std::byte> buf,
Async::OperationOptions options)
{
auto st = state_;
if (!st) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "File is closed or moved-from")};
}
auto backend = st->backend.lock();
if (!backend) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "IO Driver no longer alive")};
}
auto submitted = backend->submit_file_read(st, offset, buf, std::move(options));
if (!submitted.has_value()) {
co_return std::unexpected{std::move(submitted.error())};
}
auto op = std::move(*submitted);
co_return co_await op->awaitable(&backend->executor());
}
Coro::Task<Void::Result::Result<Transfer>> File::write_at(std::uint64_t offset,
std::span<const std::byte> buf,
Async::OperationOptions options)
{
auto st = state_;
if (!st) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "File is closed or moved-from")};
}
auto backend = st->backend.lock();
if (!backend) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "IO Driver no longer alive")};
}
auto submitted = backend->submit_file_write(st, offset, buf, std::move(options));
if (!submitted.has_value()) {
co_return std::unexpected{std::move(submitted.error())};
}
auto op = std::move(*submitted);
co_return co_await op->awaitable(&backend->executor());
}
Coro::Task<Void::Result::Result<void>> File::sync(SyncMode mode, Async::OperationOptions options)
{
auto st = state_;
if (!st) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "File is closed or moved-from")};
}
auto backend = st->backend.lock();
if (!backend) {
co_return std::unexpected{make_io_error(
IoErrorCode::closed, "IO Driver no longer alive")};
}
auto submitted = backend->submit_file_sync(st, mode, std::move(options));
if (!submitted.has_value()) {
co_return std::unexpected{std::move(submitted.error())};
}
auto op = std::move(*submitted);
co_return co_await op->awaitable(&backend->executor());
}
Coro::Task<Void::Result::Result<void>> File::close_and_join(Async::OperationOptions options)
{
auto st = state_;
if (!st) {
co_return Void::Result::Result<void>{};
}
Void::Result::Result<void> res{};
if (auto backend = st->backend.lock()) {
auto submitted = backend->submit_file_close(st, std::move(options));
if (!submitted.has_value()) {
co_return std::unexpected{std::move(submitted.error())};
}
auto op = std::move(*submitted);
res = co_await op->awaitable(&backend->executor());
}
// Without a backend the Driver was torn down, which closed the fd.
if (res.has_value() && state_ == st) {
release_handle();
}
co_return res;
}
} // namespace Void::IO
+267
View File
@@ -0,0 +1,267 @@
#pragma once
// Private to the IO module: the bounded positional-file worker pool shared by
// every backend. Nothing here is installed.
//
// Ownership (S6/F1):
// - FileWorkerShared holds the queues, the mutex/condvars, the completion
// queue and a raw waker (function pointer + backend context). Workers hold
// only shared_ptr<FileWorkerShared>; the raw waker is called only by workers
// and run_file_work, which are finished or joined before the backend dies.
// - FileState holds shared_ptr<FileWorkerShared> and weak_ptr<DriverBackend>.
// - A FileRequest lives in exactly one FileWorkerShared list (queued,
// close_queued, active, completions) from admission until a poll turn
// retires it; nodes move between lists with splice, so workers never
// allocate.
//
// Lock order: backend poll_mu_ -> backend mu_ -> FileWorkerShared::mu, and
// poll_mu_ -> FileWorkers::threads_mu_ -> FileWorkerShared::mu. Workers take
// only FileWorkerShared::mu. No stop_callback is constructed or destroyed and
// no clock is read while FileWorkerShared::mu is held.
#include <Void/Async/Operation.hpp>
#include <Void/IO/Detail/Backend.hpp>
#include <Void/IO/File.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <thread>
#include <utility>
#include <vector>
namespace Void::IO::detail
{
struct FileRequest;
struct FileWorkerShared;
using FileRequestList = std::list<std::shared_ptr<FileRequest>>;
enum class FileRequestKind : std::uint8_t {
read,
write,
sync,
close
};
enum class FileRequestPhase : std::uint8_t {
queued, // in queued / close_queued
active, // in active, syscall running
done, // in completions, awaiting poll-turn retirement
retired // delivered by a poll turn
};
enum class FileSettle : std::uint8_t {
syscall, // result holds the syscall outcome
cancelled, // stopped while queued (no syscall)
timeout // expired while queued (no syscall)
};
struct FileCancelForwarder {
std::weak_ptr<FileRequest> request;
void operator()() const noexcept;
};
struct FileWakeForwarder {
std::weak_ptr<DriverBackend> backend;
void operator()() const noexcept;
};
class FileState;
struct FileRequest {
FileRequestKind kind{FileRequestKind::read};
// Guarded by FileWorkerShared::mu.
FileRequestPhase phase{FileRequestPhase::queued};
FileSettle settle{FileSettle::syscall};
bool stop_requested{false};
bool expired{false};
int exec_fd{-1};
FileSyscallResult result{};
FileRequestList::iterator pos{};
// Immutable after admission (a close request's `file` is set under mu
// when it is enqueued).
std::shared_ptr<FileState> file{};
std::byte* read_ptr{nullptr};
const std::byte* write_ptr{nullptr};
std::size_t len{0};
std::uint64_t offset{0};
SyncMode mode{SyncMode::full};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
std::shared_ptr<Async::OperationState<Transfer>> transfer_op{};
std::shared_ptr<Async::OperationState<void>> void_op{};
// MUST stay LAST: synchronized teardown with external stop callbacks.
std::optional<std::stop_callback<FileCancelForwarder>> cancel_cb{};
[[nodiscard]] bool serialized() const noexcept
{
return kind == FileRequestKind::write || kind == FileRequestKind::sync;
}
};
class FileState : public std::enable_shared_from_this<FileState>
{
public:
enum class Status : std::uint8_t {
open,
closing,
closed
};
// Allocates the preallocated close request node (so ~File never allocates).
FileState(std::shared_ptr<FileWorkerShared> pool_in,
std::weak_ptr<DriverBackend> backend_in,
FileSyscalls* syscalls_in,
int fd_in,
DescriptorId id_in);
FileState(const FileState&) = delete;
FileState& operator=(const FileState&) = delete;
const std::shared_ptr<FileWorkerShared> pool;
const std::weak_ptr<DriverBackend> backend;
FileSyscalls* const syscalls;
const DescriptorId id;
// Guarded by pool->mu.
int fd{-1};
Status status{Status::open};
bool close_pending{false};
bool close_enqueued{false};
bool serial_active{false};
std::size_t in_flight{0};
int close_error{0};
FileRequestList close_node{};
};
struct FileCloseWaiter {
std::shared_ptr<FileState> file{};
std::shared_ptr<Async::OperationState<void>> op{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
// MUST stay LAST.
std::optional<std::stop_callback<FileWakeForwarder>> stop_cb{};
};
struct FileWorkerShared {
FileWorkerShared(std::size_t max_queue_in, FileSyscalls* syscalls_in) noexcept
: max_queue(max_queue_in)
, syscalls(syscalls_in)
{
}
FileWorkerShared(const FileWorkerShared&) = delete;
FileWorkerShared& operator=(const FileWorkerShared&) = delete;
std::mutex mu{};
std::condition_variable work_cv{};
std::condition_variable idle_cv{};
// Guarded by mu.
FileRequestList queued{}; // admitted read/write/sync, admission order
FileRequestList close_queued{}; // internal close requests (reserved capacity)
FileRequestList active{}; // syscall running
FileRequestList completions{}; // finished, awaiting poll-turn retirement
std::vector<std::shared_ptr<FileCloseWaiter>> close_waiters{};
bool accepting{true};
bool exit_requested{false};
bool rollback_requested{false};
std::size_t running_workers{0};
const std::size_t max_queue;
FileSyscalls* const syscalls;
void (*waker)(void*) noexcept {nullptr};
void* waker_ctx{nullptr};
// Lock-free telemetry mirrors (written under mu).
std::atomic<std::size_t> queued_count{0};
std::atomic<std::size_t> active_count{0};
std::atomic<std::size_t> running_count{0};
void wake() const noexcept
{
if (waker != nullptr) {
waker(waker_ctx);
}
}
// All *_locked members require `mu`.
void publish_counts_locked() noexcept;
[[nodiscard]] bool has_runnable_locked() const noexcept;
// Moves the next eligible request to `active` (close requests first; a
// write/sync only when its file has no serialized request active). A
// queued request already stopped/expired is settled without a syscall and
// `settled_without_syscall` is set.
[[nodiscard]] std::shared_ptr<FileRequest> take_next_locked(
bool& settled_without_syscall) noexcept;
void finish_locked(FileRequest& req, FileSyscallResult result) noexcept;
// queued -> completions with `settle` (cancelled/timeout).
void settle_queued_locked(FileRequest& req, FileSettle settle) noexcept;
void enqueue_close_locked(FileState& file) noexcept;
};
// Runs one request's syscall through the shim (EINTR retried except close).
[[nodiscard]] FileSyscallResult execute_file_request(const FileRequest& req) noexcept;
// Executes up to `max_requests` requests on the calling thread. Returns
// nullopt (busy) while workers are running.
[[nodiscard]] std::optional<std::size_t> run_file_requests_inline(
FileWorkerShared& shared, std::size_t max_requests);
// Handle-drop transition for ~File and File move-assignment (noexcept, never
// allocates; wakes only through the worker condvar or a weak->strong lock).
void file_handle_dropped(FileState& file) noexcept;
[[nodiscard]] const FileWorkerShared* current_io_worker_owner() noexcept;
[[nodiscard]] Void::Result::Result<void> validate_file_open_options(
const FileOpenOptions& options);
[[nodiscard]] Void::Result::Result<int> open_file_native(
const std::filesystem::path& path, const FileOpenOptions& options);
// Owns the worker threads. Never blocks in its destructor: a joinable thread
// left at destruction is a programmer error (diagnostic + std::terminate).
class FileWorkers
{
public:
explicit FileWorkers(std::shared_ptr<FileWorkerShared> shared) noexcept
: shared_(std::move(shared))
{
}
~FileWorkers();
FileWorkers(const FileWorkers&) = delete;
FileWorkers& operator=(const FileWorkers&) = delete;
// invalid_argument when already started, closed once shutdown began,
// os_error (with the system code when present) on a hook or thread
// creation failure after joining the workers already started.
[[nodiscard]] Void::Result::Result<void> start(
std::size_t count,
const std::function<Void::Result::Result<void>(std::size_t)>& hook);
// FileWorkerShared::exit_requested must already be set.
void join_for_shutdown() noexcept;
private:
void rollback_locked() noexcept;
std::shared_ptr<FileWorkerShared> shared_{};
std::mutex threads_mu_{};
std::vector<std::thread> threads_{};
bool started_{false};
};
} // namespace Void::IO::detail
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Messaging
INTERNAL_DEPS Core Functional Binary Time Async
)
+513
View File
@@ -0,0 +1,513 @@
#include <Void/MessagingRpc/RpcAdapter.hpp>
#include <cstring>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::MessagingRpc
{
using namespace Void::Messaging;
using Void::Messaging::Result;
namespace
{
void put_u8(Void::RPC::OwnedBytes& out, std::uint8_t v)
{
out.push_back(static_cast<std::byte>(v));
}
void put_u32(Void::RPC::OwnedBytes& out, std::uint32_t v)
{
out.push_back(static_cast<std::byte>((v >> 24U) & 0xFFU));
out.push_back(static_cast<std::byte>((v >> 16U) & 0xFFU));
out.push_back(static_cast<std::byte>((v >> 8U) & 0xFFU));
out.push_back(static_cast<std::byte>(v & 0xFFU));
}
void put_u64(Void::RPC::OwnedBytes& out, std::uint64_t v)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((v >> shift) & 0xFFU));
}
}
void put_i64(Void::RPC::OwnedBytes& out, std::int64_t v)
{
put_u64(out, static_cast<std::uint64_t>(v));
}
void put_str(Void::RPC::OwnedBytes& out, std::string_view s)
{
put_u32(out, static_cast<std::uint32_t>(s.size()));
for (char c : s) {
out.push_back(static_cast<std::byte>(c));
}
}
void put_bytes(Void::RPC::OwnedBytes& out,
const std::vector<std::byte>& b)
{
put_u32(out, static_cast<std::uint32_t>(b.size()));
out.insert(out.end(), b.begin(), b.end());
}
void put_message(Void::RPC::OwnedBytes& out, const Message& m)
{
put_str(out, m.id);
put_u32(out, m.schema_version);
put_bytes(out, m.payload);
put_u32(out, static_cast<std::uint32_t>(m.headers.size()));
for (const auto& [k, v] : m.headers) {
put_str(out, k);
put_str(out, v);
}
}
void put_receipt(Void::RPC::OwnedBytes& out, const Receipt& r)
{
put_str(out, r.queue);
put_str(out, r.group);
put_str(out, r.message_id);
put_u64(out, r.sequence);
put_u64(out, r.generation);
}
struct Cursor {
std::span<const std::byte> data{};
std::size_t pos{0};
[[nodiscard]] bool read_u8(std::uint8_t& v) noexcept
{
if (pos + 1U > data.size()) return false;
v = std::to_integer<std::uint8_t>(data[pos++]);
return true;
}
[[nodiscard]] bool read_u32(std::uint32_t& v) noexcept
{
if (pos + 4U > data.size()) return false;
v = (static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos]))
<< 24U) |
(static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos + 1]))
<< 16U) |
(static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos + 2]))
<< 8U) |
static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos + 3]));
pos += 4U;
return true;
}
[[nodiscard]] bool read_u64(std::uint64_t& v) noexcept
{
if (pos + 8U > data.size()) return false;
v = 0;
for (std::size_t i = 0; i < 8U; ++i) {
v = (v << 8U) |
static_cast<std::uint64_t>(
std::to_integer<std::uint8_t>(data[pos + i]));
}
pos += 8U;
return true;
}
[[nodiscard]] bool read_i64(std::int64_t& v) noexcept
{
std::uint64_t u = 0;
if (!read_u64(u)) return false;
v = static_cast<std::int64_t>(u);
return true;
}
[[nodiscard]] bool read_str(std::string& s)
{
std::uint32_t len = 0;
if (!read_u32(len) || pos + len > data.size()) return false;
s.resize(len);
if (len > 0U) {
std::memcpy(s.data(), data.data() + pos, len);
}
pos += len;
return true;
}
[[nodiscard]] bool read_bytes(std::vector<std::byte>& b)
{
std::uint32_t len = 0;
if (!read_u32(len) || pos + len > data.size()) return false;
b.resize(len);
if (len > 0U) {
std::memcpy(b.data(), data.data() + pos, len);
}
pos += len;
return true;
}
[[nodiscard]] bool read_message(Message& m)
{
std::uint32_t hcount = 0;
if (!read_str(m.id) || !read_u32(m.schema_version) ||
!read_bytes(m.payload) || !read_u32(hcount)) {
return false;
}
m.headers.clear();
for (std::uint32_t i = 0; i < hcount; ++i) {
std::string k, v;
if (!read_str(k) || !read_str(v)) return false;
m.headers.emplace(std::move(k), std::move(v));
}
return true;
}
[[nodiscard]] bool read_receipt(Receipt& r)
{
return read_str(r.queue) && read_str(r.group) &&
read_str(r.message_id) && read_u64(r.sequence) &&
read_u64(r.generation);
}
[[nodiscard]] bool eof() const noexcept
{
return pos == data.size();
}
};
[[nodiscard]] Void::Result::Error
map_rpc_err(const Void::Result::Error& err)
{
if (err.code().domain == Void::Result::kMessagingErrorDomain) {
return err;
}
const auto status = Void::RPC::rpc_status_from_error(err);
if (status == Void::RPC::RpcStatusCode::UnknownOutcome) {
return make_messaging_error(MessagingErrorCode::UnknownOutcome,
err.message());
}
if (status == Void::RPC::RpcStatusCode::FailedPrecondition) {
return make_messaging_error(MessagingErrorCode::StaleReceipt,
err.message());
}
if (status == Void::RPC::RpcStatusCode::NotFound) {
return make_messaging_error(MessagingErrorCode::NotFound,
err.message());
}
if (status == Void::RPC::RpcStatusCode::ResourceExhausted) {
return make_messaging_error(MessagingErrorCode::QuotaExceeded,
err.message());
}
if (status == Void::RPC::RpcStatusCode::DeadlineExceeded) {
return make_messaging_error(MessagingErrorCode::Timeout,
err.message());
}
if (status == Void::RPC::RpcStatusCode::Cancelled) {
return make_messaging_error(MessagingErrorCode::Cancelled,
err.message());
}
return make_messaging_error(MessagingErrorCode::PersistenceError,
err.message());
}
} // namespace
RpcQueueServer::~RpcQueueServer() noexcept { unmount_and_drain(); }
void RpcQueueServer::unmount_and_drain() noexcept
{
for (auto& reg : m_registrations) {
reg.unregister_and_drain();
}
m_registrations.clear();
}
Result<void> RpcQueueServer::mount(Void::RPC::Server& server, Queue& queue)
{
auto bind_one = [&](Void::RPC::MethodId id, std::string name,
Void::RPC::UnaryHandler handler) -> Result<void> {
auto reg = server.bind(
Void::RPC::MethodDescriptor{
.id = id,
.service_name = "void.messaging.v1",
.method_name = std::move(name),
.schema_version = 1,
},
std::move(handler));
if (!reg.has_value()) {
return Void::Result::fail(reg.error());
}
m_registrations.push_back(std::move(*reg));
return {};
};
if (auto r = bind_one(
kPublishMethod, "publish",
[&queue](const Void::RPC::CallContext& ctx,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
std::string qname;
std::uint8_t dur = 0;
Message msg{};
if (!c.read_str(qname) || !c.read_u8(dur) ||
!c.read_message(msg) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed publish request"));
}
Void::Async::OperationOptions opts{.stop = ctx.stop};
auto res = queue.publish(
qname, std::move(msg),
static_cast<PublishDurability>(dur), opts);
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
Void::RPC::OwnedBytes out;
put_str(out, res->queue);
put_str(out, res->message_id);
put_u64(out, res->sequence);
put_u8(out, static_cast<std::uint8_t>(res->durability));
put_u8(out, res->deduplicated ? 1U : 0U);
return out;
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kTryReceiveMethod, "try_receive",
[&queue](const Void::RPC::CallContext&,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
std::string qname, gname;
if (!c.read_str(qname) || !c.read_str(gname) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed try_receive request"));
}
auto res = queue.try_receive(qname, gname);
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
Void::RPC::OwnedBytes out;
if (!res->has_value()) {
put_u8(out, 0U);
return out;
}
put_u8(out, 1U);
put_message(out, (*res)->message);
put_receipt(out, (*res)->receipt);
put_u32(out, (*res)->attempt);
put_i64(out, to_mono_ns((*res)->visibility_deadline));
return out;
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kAckMethod, "ack",
[&queue](const Void::RPC::CallContext& ctx,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
Receipt rec{};
if (!c.read_receipt(rec) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed ack request"));
}
auto res =
queue.ack(rec, Void::Async::OperationOptions{.stop = ctx.stop});
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
return Void::RPC::OwnedBytes{};
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kNackMethod, "nack",
[&queue](const Void::RPC::CallContext& ctx,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
Receipt rec{};
std::uint8_t has_delay = 0;
std::int64_t delay_ms = 0;
if (!c.read_receipt(rec) || !c.read_u8(has_delay) ||
!c.read_i64(delay_ms) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed nack request"));
}
std::optional<std::chrono::milliseconds> d{};
if (has_delay != 0U) {
d = std::chrono::milliseconds{delay_ms};
}
auto res = queue.nack(
rec, d, Void::Async::OperationOptions{.stop = ctx.stop});
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
return Void::RPC::OwnedBytes{};
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kQueryReceiptMethod, "query_receipt",
[&queue](const Void::RPC::CallContext&,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
Receipt rec{};
if (!c.read_receipt(rec) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed query_receipt request"));
}
auto res = queue.query_receipt(rec);
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
Void::RPC::OwnedBytes out;
put_u8(out, static_cast<std::uint8_t>(*res));
return out;
});
!r.has_value()) {
return r;
}
return {};
}
// ── RpcQueueClient ────────────────────────────────────────────────────────
RpcQueueClient::RpcQueueClient(Void::RPC::ClientOptions options)
: m_client(std::move(options))
{
}
Result<PublishReceipt> RpcQueueClient::publish(
std::string_view queue, const Message& message,
PublishDurability durability, const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_str(req, queue);
put_u8(req, static_cast<std::uint8_t>(durability));
put_message(req, message);
auto resp = m_client.call(kPublishMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
Cursor c{*resp, 0};
PublishReceipt pr{};
std::uint8_t dur = 0, dedup = 0;
if (!c.read_str(pr.queue) || !c.read_str(pr.message_id) ||
!c.read_u64(pr.sequence) || !c.read_u8(dur) || !c.read_u8(dedup) ||
!c.eof()) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt publish response"));
}
pr.durability = static_cast<PublishDurability>(dur);
pr.deduplicated = (dedup != 0U);
return pr;
}
Result<std::optional<Delivery>>
RpcQueueClient::try_receive(std::string_view queue,
std::string_view group,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_str(req, queue);
put_str(req, group);
auto resp = m_client.call(kTryReceiveMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
Cursor c{*resp, 0};
std::uint8_t present = 0;
if (!c.read_u8(present)) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt try_receive response"));
}
if (present == 0U) {
return std::optional<Delivery>{std::nullopt};
}
Delivery d{};
std::int64_t dl_ns = 0;
if (!c.read_message(d.message) || !c.read_receipt(d.receipt) ||
!c.read_u32(d.attempt) || !c.read_i64(dl_ns) || !c.eof()) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt delivery response"));
}
d.visibility_deadline = Void::Time::MonotonicClock::time_point{
std::chrono::duration_cast<
Void::Time::MonotonicClock::time_point::duration>(
std::chrono::nanoseconds{dl_ns})};
return std::optional<Delivery>{std::move(d)};
}
Result<void> RpcQueueClient::ack(const Receipt& receipt,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_receipt(req, receipt);
auto resp = m_client.call(kAckMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
return {};
}
Result<void>
RpcQueueClient::nack(const Receipt& receipt,
std::optional<std::chrono::milliseconds> delay,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_receipt(req, receipt);
put_u8(req, delay.has_value() ? 1U : 0U);
put_i64(req, delay.has_value() ? delay->count() : 0LL);
auto resp = m_client.call(kNackMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
return {};
}
Result<DeliveryState>
RpcQueueClient::query_receipt(const Receipt& receipt,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_receipt(req, receipt);
auto resp = m_client.call(kQueryReceiptMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
Cursor c{*resp, 0};
std::uint8_t st = 0;
if (!c.read_u8(st) || !c.eof() ||
st > static_cast<std::uint8_t>(DeliveryState::DeadLetter)) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt query_receipt response"));
}
return static_cast<DeliveryState>(st);
}
} // namespace Void::MessagingRpc
+3
View File
@@ -0,0 +1,3 @@
void_add_module(MessagingRpc
INTERNAL_DEPS Messaging RPC
)
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(MessagingStorage
INTERNAL_DEPS Messaging Storage
)
+54 -15
View File
@@ -917,9 +917,15 @@ namespace Void::Net
HttpClient::send(const Request& req) const
{
std::string target_url = req.url;
Method active_method = req.method;
std::optional<std::string> active_body = req.body;
std::vector<Header> active_headers = req.headers;
int redirects = 0;
const auto overall_start = std::chrono::steady_clock::now();
const bool has_deadline = req.timeout > std::chrono::seconds::zero();
const auto overall_deadline = overall_start + req.timeout;
while (true) {
const auto url = Url::parse(target_url);
if (!url) {
@@ -928,11 +934,25 @@ namespace Void::Net
std::format("Net: invalid URL '{}'",
sanitize_url_for_log(target_url)))};
}
std::chrono::seconds remaining_timeout = req.timeout;
if (has_deadline) {
const auto now = std::chrono::steady_clock::now();
if (now >= overall_deadline) {
return std::unexpected{make_net_error(
NetErrorCode::timeout,
std::format("Net: request to '{}' timed out across "
"redirects",
sanitize_url_for_log(target_url)))};
}
const auto rem_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
overall_deadline - now);
remaining_timeout = std::chrono::seconds{
std::max<long long>(1, (rem_ms.count() + 999) / 1000)};
}
bool cancelled = false;
bool timed_out = false;
try {
const auto start = std::chrono::steady_clock::now();
asio::io_context ioc;
ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file);
@@ -945,26 +965,26 @@ namespace Void::Net
asio::connect(socket, resolver.resolve(
m_proxy.host,
std::to_string(m_proxy.port)));
DeadlineGuard deadline{socket, req.timeout};
DeadlineGuard deadline{socket, remaining_timeout};
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
socks5_connect(socket, *url, m_proxy);
response = finish(socket, tls, ctx, *url, req.method,
active_headers, req.body,
response = finish(socket, tls, ctx, *url, active_method,
active_headers, active_body,
m_user_agent, m_max_body,
m_verify_tls);
} else {
if (url->is_tls) {
http_connect_tunnel(socket, *url, m_proxy);
response = finish(socket, tls, ctx, *url,
req.method, active_headers,
req.body, m_user_agent,
active_method, active_headers,
active_body, m_user_agent,
m_max_body, m_verify_tls);
} else {
const std::string absolute = std::format(
"{}://{}{}", url->scheme, url->host,
url->target);
auto rq = build_request(*url, req.method,
active_headers, req.body,
auto rq = build_request(*url, active_method,
active_headers, active_body,
m_user_agent, absolute);
if (m_proxy.has_auth()) {
const auto enc = Void::Encoding::Base64::encode(
@@ -981,17 +1001,21 @@ namespace Void::Net
} else {
asio::connect(socket,
resolver.resolve(url->host, url->port));
DeadlineGuard deadline{socket, req.timeout};
DeadlineGuard deadline{socket, remaining_timeout};
response =
finish(socket, tls, ctx, *url, req.method,
active_headers, req.body, m_user_agent,
finish(socket, tls, ctx, *url, active_method,
active_headers, active_body, m_user_agent,
m_max_body, m_verify_tls);
timed_out = deadline.timed_out();
cancelled = deadline.cancelled();
}
if (m_max_redirects > 0 && response.status >= 300 &&
response.status < 400 && redirects < m_max_redirects) {
const bool is_redirect_status =
response.status == 301 || response.status == 302 ||
response.status == 303 || response.status == 307 ||
response.status == 308;
if (m_max_redirects > 0 && is_redirect_status &&
redirects < m_max_redirects) {
if (auto loc = response.header("location")) {
const std::string next_url =
resolve_redirect(*url, *loc);
@@ -1011,6 +1035,21 @@ namespace Void::Net
if (!same_origin(*url, *next_parsed)) {
strip_sensitive_headers(active_headers);
}
// RFC 9110 §15.4.4: 303 changes non-HEAD to GET and
// drops body + representation headers.
if (response.status == 303 &&
active_method != Method::Head) {
active_method = Method::Get;
active_body.reset();
std::erase_if(active_headers, [](const Header& h) {
return equal_ascii_ci(h.name,
"Content-Length") ||
equal_ascii_ci(h.name,
"Content-Type") ||
equal_ascii_ci(h.name,
"Transfer-Encoding");
});
}
target_url = next_url;
++redirects;
continue;
@@ -1019,7 +1058,7 @@ namespace Void::Net
response.elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start);
std::chrono::steady_clock::now() - overall_start);
return response;
} catch (const TlsError& e) {
return std::unexpected{make_net_error(
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more