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
41 changed files with 19701 additions and 716 deletions

No files matched your search

+1
View File
@@ -92,3 +92,4 @@ execution without pausing between waves). They are not new user approvals.
| 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 |
+22 -26
View File
@@ -1,9 +1,9 @@
# Workflow state
Updated: 2026-11-29.
Updated: 2026-12-01.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave11` (from `main` at `38436b1`;
Waves 1–10 + `VL-001`..`VL-013` merged into `main` at `7d7d23e` and pushed to `origin/main`).
Current wave: **Wave 11 — execution-path backfill** (see D-033..D-036 and `TASKS.md`).
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
@@ -363,30 +363,26 @@ while leaving local untracked files untouched.
- Full Debug ASan+UBSan (`/tmp/void-w10-asan`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB.
- Debug TSan (`/tmp/void-w10-tsan`, `Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`, 23 modules, `-Werror`): `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings.
### Wave 11 — Execution-path backfill (`feat/roadmap-p2-wave11`, in progress)
### Wave 11 — Execution-path backfill (`feat/roadmap-p2-wave11`, verified & merged to `main`)
Checkpoint 2026-11-29 (branch pushed to `origin/feat/roadmap-p2-wave11`; `main` untouched at `38436b1`):
- Baseline `38436b1` full RelWithDebInfo `-Werror` (`/tmp/void-w11-base`, 55 modules): 1,484 tests
(1,480 ✔, 4 ⊘), `ctest` 2/2.
- Planning: `tasks/W11-PLAN-OUTPUT.md` → PREFLIGHT 1 (CHANGES_REQUIRED, F1 P1 + F2–F13) →
`tasks/W11-PLAN-REV1-OUTPUT.md` → PREFLIGHT 2 (CHANGES_REQUIRED, N1–N6) → `tasks/W11-CONTRACT-R2.md`
→ spec review (S1–S9, A1–A3) adopted into specs (D-038, D-040, D-042).
- Commits: `7f95f89` prep (error codes, area plans), `a8a9249`/`99203ce`/`c6789e7` docs/specs,
`26edf65` M-FUNCTIONAL-03 (VERIFIED).
- In flight: M-TIME-03 B1 TimerQueue diff applied UNCOMMITTED in the main checkout (root-verified:
681 tests 678 ✔ 3 ⊘, TSan 28/28 ×3, ASan 468 ✔; fresh review pending); S-IO-03 (B2) implementer
in an agent worktree. Specs ready: M-ASYNC-04 (A2, after B1 commit), M-TIME-03-B1b (`retry_async`,
after B1 commit), M-ASYNC-05 (A3, after A2). Still to specify: S-IO-04 (A4), S-RUNTIME-02 (B3),
S-RUNTIME-03 (B4).
- Dispatch rule (X-WF-01): agent worktrees start at `main`; each prompt fast-forwards to the stated HEAD.
- Note: a 5-hour usage limit interrupted two agents once; they were resumed with SendMessage.
- **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–10 (`P0`, `P1` except `M-FUNCTIONAL-03`/`M-TIME-03`, the P2 operations/storage/
lifecycle/network modules, `VL-001`..`VL-013`, and P3 core subsystems `Discovery`,
`Scheduler`, `Messaging`) are complete, verified, merged and pushed. A 2026-11-29 audit
(D-033) found 2 P1 and 40 P2 roadmap tasks still open. **Wave 11** backfills the
execution path (`M-FUNCTIONAL-03`, `M-TIME-03`, `M-ASYNC-04/05`, `S-IO-03/04`,
`S-RUNTIME-02/03`) that gates `P-NETWORKED-02`/`P-RELOADABLE-02`. Then: foundation P2
leftovers (D-036), then P3 platforms + `S-RPC-04/05`, then P4.
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.
+12 -10
View File
@@ -146,19 +146,20 @@ verified by the available spawn response.
Baseline: `main` at `38436b1`; full RelWithDebInfo `-Werror` (`/tmp/void-w11-base`, 55 modules):
`VoidTests` 1,484 discovered (1,480 ✔, 4 ⊘, 0 ✘) in 26.99 s; `ctest` 2/2 (111.68 s).
Decisions: D-033..D-036.
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 | [W11-PLAN](tasks/W11-PLAN.md), [output](tasks/W11-PLAN-OUTPUT.md), [REV1](tasks/W11-PLAN-REV1-OUTPUT.md) | DONE | PREFLIGHT 1 CHANGES_REQUIRED ([findings](tasks/W11-PREFLIGHT-OUTPUT.md)); resolved in REV1/D-038; PREFLIGHT 2 running |
| M-FUNCTIONAL-03 | Pure retry decisions + named blocking adapter (A1) | [spec](tasks/M-FUNCTIONAL-03.md) | VERIFIED (`26edf65`) | Review W11-REVIEW-A1 READY (P3 1/2/5 fixed by root); ResilienceAsync subset 475 (472 ✔, 3 ⊘), filtered 43/43, ctest 2/2, TSan 40/40 0 races, ASan+UBSan 40/40, `-Werror` syntax checks clean |
| M-TIME-03 | Injected-deadline domains: TimerQueue + clock saturation (B1); `retry_async` (B1b) | [spec](tasks/M-TIME-03.md), [B1b](tasks/M-TIME-03-B1b.md) | B1 VERIFIED; B1b IN PROGRESS | B1: review W11-REVIEW-B1 F1–F3 fixed by root; Runtime;SystemAsync;ResilienceAsync 681 (678 ✔, 3 ⊘), TSan 28/28 ×3, ASan 468 ✔, post-fix 18/18 + TSan 15/15 |
| M-ASYNC-04 | ThreadExecutor, FuturePool, AsyncChannel, bounded ParallelFor (A2) | [spec](tasks/M-ASYNC-04.md) | READY (waits for B1 commit, G2) | — |
| M-ASYNC-05 | EventBus/Observable snapshot dispatch, joined subscriptions | — | PLANNED | — |
| S-IO-03 | Bounded positional file workers, sync, active-cancel, shutdown core, D1 fixes (B2) | [spec](tasks/S-IO-03.md) | IN PROGRESS | opus-implementer, worktree |
| S-IO-04 | Embedded pumping, joined shutdown, optional adapters | — | PLANNED | — |
| S-RUNTIME-02 | Explicit start, readiness, reverse failed-start cleanup | — | PLANNED | — |
| S-RUNTIME-03 | Structured shutdown, repeated join, exporter-before-executor ordering | — | PLANNED | — |
| 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.
@@ -201,3 +202,4 @@ specs' observed baselines (D-035); not separately scheduled.
| 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 |
+5
View File
@@ -304,3 +304,8 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
| 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 |
+4 -2
View File
@@ -50,8 +50,10 @@ MANDATORY semantics:
`Coro::Task<std::expected<T,E>>` (co_await it). Success → return `T` (also when stop was requested
during the attempt). Failure → `next(now, classify(error), stop_requested)`.
- On `wait_until(at)`: `co_await timers.sleep_until(at, OperationOptions{options.stop, options.deadline})`.
Then ALWAYS call `resume(now, options.stop.stop_requested())` — it re-checks stop itself, which covers
the TimerQueue choice where a late stop yields `{}`. Sleep result mapping: `{}` → resume;
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).
+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,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.
+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
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
+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
+30
View File
@@ -7,6 +7,7 @@
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <memory_resource>
#include <new>
@@ -120,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 {};
}
@@ -129,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 {
@@ -150,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
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
+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
File diff suppressed because it is too large. Load diff
+146
View File
@@ -2,15 +2,21 @@
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/Functional/Retry.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <random>
#include <stop_token>
#include <utility>
#include <vector>
namespace
{
@@ -77,6 +83,51 @@ void start(Void::Coro::Task<void>& task)
task.handle().resume();
}
// retry_blocking's only notion of time: `now` reads the ManualClock and the
// sleeper advances it by the requested wait (plus an optional overshoot).
struct ManualNow {
const ManualClock* clock{nullptr};
[[nodiscard]] Void::Retry::SteadyTimePoint operator()() const noexcept { return clock->now(); }
};
struct ManualAdvanceSleep {
ManualClock* clock{nullptr};
std::vector<std::chrono::nanoseconds>* waits{nullptr};
std::chrono::nanoseconds overshoot{0};
bool operator()(std::chrono::nanoseconds wait, std::stop_token) const
{
waits->push_back(wait);
return clock->advance(wait + overshoot).has_value();
}
};
using ManualBlockingOptions = Void::Retry::
BlockingRetryOptions<ManualNow, ManualAdvanceSleep, Void::Retry::RetryEveryError, std::mt19937_64>;
// Constant backoff of `delay`, no jitter, no time budget.
Void::Retry::RetrySpec constant_retry_spec(std::chrono::nanoseconds delay, std::uint32_t attempts)
{
Void::Retry::RetrySpec spec;
spec.max_attempts = attempts;
spec.budget = Void::Retry::no_deadline;
spec.backoff.initial = delay;
spec.backoff.cap = delay;
spec.backoff.multiplier = 1.0;
spec.backoff.jitter = std::nullopt;
return spec;
}
// Fails every attempt with its 1-based index and records when it ran.
auto failing_attempt(const ManualClock* clock, std::vector<TimePoint>* times)
{
return [clock, times]() -> std::expected<int, int> {
times->push_back(clock->now());
return std::unexpected{static_cast<int>(times->size())};
};
}
} // namespace
Void::Testing::Test deadline_domain_schedule_on_and_scope_admission_injected_clock()
@@ -242,3 +293,98 @@ Void::Testing::Test deadline_domain_timer_and_operation_deadline_same_manual_clo
Void::Testing::require(later.result.has_value());
Void::Testing::expect(later.result->has_value());
}
Void::Testing::Test deadline_domain_blocking_retry_manual_clock()
{
namespace R = Void::Retry;
using Ns = std::chrono::nanoseconds;
// The host steady clock is far past the manual-domain deadline below, so
// any host-clock comparison would stop the retry before its first attempt.
Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms);
// Admission deadline in the ManualClock domain (epoch 0): attempts at 0,
// 10 and 20ms; the wake-up at 30ms would overshoot 25ms, so it stops.
{
ManualClock clock;
const OperationOptions opts{.deadline = at(25ms)};
Void::Testing::expect(is_deadline_expired(opts));
Void::Testing::expect(!is_deadline_expired(opts, clock));
std::vector<TimePoint> attempts;
std::vector<Ns> waits;
const auto r = R::retry_blocking(constant_retry_spec(10ms, 10),
failing_attempt(&clock, &attempts),
ManualBlockingOptions{.now = ManualNow{&clock},
.sleep = ManualAdvanceSleep{&clock, &waits},
.classify = {},
.urbg = std::mt19937_64{1},
.stop = {},
.deadline = opts.deadline});
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(static_cast<int>(r.error().reason),
static_cast<int>(R::RetryStopReason::deadline_exceeded));
Void::Testing::expect_eq(r.error().attempts, std::uint32_t{3});
Void::Testing::require(r.error().last_error.has_value());
Void::Testing::expect_eq(*r.error().last_error, 3);
Void::Testing::require(attempts.size() == 3);
Void::Testing::expect(attempts[0] == at(0ns));
Void::Testing::expect(attempts[1] == at(10ms));
Void::Testing::expect(attempts[2] == at(20ms));
Void::Testing::require(waits.size() == 2);
Void::Testing::expect_eq(waits[0], Ns{10ms});
Void::Testing::expect_eq(waits[1], Ns{10ms});
// Only the injected sleeper moved time.
Void::Testing::expect(clock.now() == at(20ms));
}
// The budget is measured from the start the manual clock reports, here
// a century past epoch, far from any host uptime.
{
const TimePoint start = at(std::chrono::hours{24 * 365 * 100});
ManualClock clock{start};
auto spec = constant_retry_spec(10ms, 10);
spec.budget = Ns{25ms};
std::vector<TimePoint> attempts;
std::vector<Ns> waits;
const auto r = R::retry_blocking(spec,
failing_attempt(&clock, &attempts),
ManualBlockingOptions{.now = ManualNow{&clock},
.sleep = ManualAdvanceSleep{&clock, &waits},
.classify = {},
.urbg = std::mt19937_64{1},
.stop = {},
.deadline = std::nullopt});
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(static_cast<int>(r.error().reason),
static_cast<int>(R::RetryStopReason::deadline_exceeded));
Void::Testing::expect_eq(r.error().attempts, std::uint32_t{3});
Void::Testing::require(attempts.size() == 3);
Void::Testing::expect(attempts[0] == start);
Void::Testing::expect(attempts[2] == start + std::chrono::duration_cast<TimePoint::duration>(20ms));
Void::Testing::expect_eq(waits.size(), std::size_t{2});
}
// Advancing manual time past the deadline during one sleep expires the
// operation exactly once: resume() observes it and no attempt follows.
{
ManualClock clock;
std::vector<TimePoint> attempts;
std::vector<Ns> waits;
const auto r = R::retry_blocking(constant_retry_spec(10ms, 10),
failing_attempt(&clock, &attempts),
ManualBlockingOptions{.now = ManualNow{&clock},
.sleep = ManualAdvanceSleep{&clock, &waits, 30ms},
.classify = {},
.urbg = std::mt19937_64{1},
.stop = {},
.deadline = at(25ms)});
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(static_cast<int>(r.error().reason),
static_cast<int>(R::RetryStopReason::deadline_exceeded));
Void::Testing::expect_eq(r.error().attempts, std::uint32_t{1});
Void::Testing::expect_eq(attempts.size(), std::size_t{1});
Void::Testing::require(waits.size() == 1);
Void::Testing::expect_eq(waits[0], Ns{10ms});
Void::Testing::expect(clock.now() == at(40ms));
}
}
+769
View File
@@ -0,0 +1,769 @@
#include <Void/Async/EventBus.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <coroutine>
#include <cstdint>
#include <filesystem>
#include <future>
#include <latch>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace
{
struct Ping {
int value{0};
};
[[nodiscard]] std::size_t current_thread_count()
{
std::size_t count = 0;
std::error_code ec;
for (const auto& _ :
std::filesystem::directory_iterator("/proc/self/task", ec)) {
(void)_;
++count;
}
return count;
}
[[nodiscard]] std::int32_t async_code(const Void::Result::Error& err) noexcept
{
return err.code().value;
}
} // namespace
Void::Testing::Test bus_injected_no_private_thread_manual_pumping()
{
using namespace Void::EventBus;
const std::size_t threads_before = current_thread_count();
Void::Async::ManualExecutor manual;
EventBus bus{manual};
const std::size_t threads_after = current_thread_count();
Void::Testing::expect_eq(threads_after, threads_before);
Void::Testing::expect(bus.mode() == Mode::Injected);
int sum = 0;
std::thread::id caller_id = std::this_thread::get_id();
std::thread::id seen_id{};
auto sub = bus.try_subscribe<Ping>([&](const Ping& p) {
seen_id = std::this_thread::get_id();
sum += p.value;
});
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{10}).has_value());
Void::Testing::require(bus.try_publish(Ping{25}).has_value());
Void::Testing::expect_eq(sum, 0);
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(sum, 35);
Void::Testing::expect(seen_id == caller_id);
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_injected_subscription_limit_overloaded()
{
using namespace Void::EventBus;
Void::Async::ManualExecutor manual;
EventBus bus{manual, BusOptions{.max_subscriptions = 2}};
auto s1 = bus.try_subscribe<Ping>([](const Ping&) {});
auto s2 = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::require(s1.has_value());
Void::Testing::require(s2.has_value());
auto s3 = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::require(!s3.has_value());
Void::Testing::expect_eq(
async_code(s3.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::overloaded));
s1->reset();
auto s4 = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::expect(s4.has_value());
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_injected_dispatch_limit_overloaded()
{
using namespace Void::EventBus;
Void::Async::ManualExecutor manual;
EventBus bus{manual, BusOptions{.max_admitted_dispatches = 2}};
int hits = 0;
auto sub = bus.try_subscribe<Ping>([&](const Ping& p) { hits += p.value; });
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
Void::Testing::require(bus.try_publish(Ping{2}).has_value());
auto third = bus.try_publish(Ping{3});
Void::Testing::require(!third.has_value());
Void::Testing::expect_eq(
async_code(third.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::overloaded));
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(hits, 3);
Void::Testing::require(bus.try_publish(Ping{4}).has_value());
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(hits, 7);
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_close_and_join_waits_inflight_releases_capture_tsan()
{
using namespace Void::EventBus;
auto exec_res = Void::Async::ThreadExecutor::create(
Void::Async::ThreadExecutorOptions{.workers = 2, .max_admitted = 32});
Void::Testing::require(exec_res.has_value());
auto exec = std::move(*exec_res);
Void::Testing::require(exec->start().has_value());
{
EventBus bus{*exec};
auto sentinel = std::make_shared<int>(99);
std::latch started{1};
std::promise<void> release_promise;
auto release_future = release_promise.get_future().share();
std::atomic<bool> finished{false};
auto sub = bus.try_subscribe<Ping>(
[&, sentinel](const Ping&) {
started.count_down();
release_future.wait();
finished.store(true, std::memory_order_release);
});
Void::Testing::require(sub.has_value());
Void::Testing::expect(sentinel.use_count() >= 2);
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
started.wait();
std::atomic<bool> join_done{false};
Void::Result::Result<void> join_res;
std::thread joiner([&]() {
join_res = sub->close_and_join();
join_done.store(true, std::memory_order_release);
});
std::this_thread::sleep_for(std::chrono::milliseconds{15});
Void::Testing::expect(!join_done.load(std::memory_order_acquire));
release_promise.set_value();
joiner.join();
Void::Testing::expect(join_res.has_value());
Void::Testing::expect(finished.load(std::memory_order_acquire));
Void::Testing::expect_eq(sentinel.use_count(), 1L);
Void::Testing::require(bus.close_and_join().has_value());
}
exec->close();
Void::Testing::require(exec->join().has_value());
}
Void::Testing::Test bus_unsubscribe_during_dispatch_prevents_later_admission()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
int first_hits = 0;
int second_hits = 0;
HandlerId id2 = 0;
bus.subscribe<Ping>([&](const Ping&) {
++first_hits;
bus.unsubscribe(id2);
});
id2 = bus.subscribe<Ping>([&](const Ping&) { ++second_hits; });
bus.publish(Ping{1});
Void::Testing::expect_eq(first_hits, 1);
Void::Testing::expect_eq(second_hits, 0);
bus.publish(Ping{2});
Void::Testing::expect_eq(first_hits, 2);
Void::Testing::expect_eq(second_hits, 0);
}
Void::Testing::Test bus_self_unsubscribe_ok_self_join_rejected()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
EventBus::Subscription sub;
Void::Result::Result<void> join_res;
int calls = 0;
auto sub_res = bus.try_subscribe<Ping>([&](const Ping&) {
++calls;
join_res = sub.close_and_join();
sub.reset();
});
Void::Testing::require(sub_res.has_value());
sub = std::move(*sub_res);
bus.publish(Ping{1});
bus.publish(Ping{2});
Void::Testing::expect_eq(calls, 1);
Void::Testing::require(!join_res.has_value());
Void::Testing::expect_eq(
async_code(join_res.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
Void::Testing::expect(!static_cast<bool>(sub));
}
Void::Testing::Test bus_callback_throw_to_error_sink_others_run()
{
using namespace Void::EventBus;
Void::Async::ManualExecutor manual;
std::vector<std::string> errors;
EventBus bus{
manual,
BusOptions{.error_sink = [&](std::exception_ptr ex) {
try {
if (ex) {
std::rethrow_exception(ex);
}
} catch (const std::exception& e) {
errors.emplace_back(e.what());
}
}}};
int second_hits = 0;
auto s1 = bus.try_subscribe<Ping>([](const Ping&) {
throw std::runtime_error("boom_injected");
});
auto s2 = bus.try_subscribe<Ping>([&](const Ping& p) { second_hits += p.value; });
Void::Testing::require(s1.has_value() && s2.has_value());
Void::Testing::require(bus.try_publish(Ping{9}).has_value());
Void::Testing::require(bus.flush_pumping(manual).has_value());
Void::Testing::expect_eq(second_hits, 9);
Void::Testing::expect_eq(bus.callback_failures(), std::uint64_t{1});
Void::Testing::require(errors.size() == 1);
Void::Testing::expect_eq(errors[0], std::string{"boom_injected"});
// Legacy Sync publish retains exception propagation.
EventBus sync_bus{Mode::Sync};
sync_bus.subscribe<Ping>([](const Ping&) { throw std::runtime_error("sync_boom"); });
bool caught = false;
try {
sync_bus.publish(Ping{1});
} catch (const std::runtime_error&) {
caught = true;
}
Void::Testing::expect(caught);
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_error_sink_throw_caught_and_counted()
{
using namespace Void::EventBus;
EventBus bus{
Mode::Async,
BusOptions{.error_sink = [](std::exception_ptr) {
throw std::runtime_error("sink_boom");
}}};
std::atomic<int> second_hits{0};
bus.subscribe<Ping>([](const Ping&) {
throw std::runtime_error("cb_boom");
});
bus.subscribe<Ping>([&](const Ping& p) {
second_hits.fetch_add(p.value, std::memory_order_relaxed);
});
Void::Testing::require(bus.try_publish(Ping{7}).has_value());
Void::Testing::require(bus.flush_blocking().has_value());
Void::Testing::expect_eq(second_hits.load(), 7);
// 1 for handler throw + 1 for throwing error_sink
Void::Testing::expect_eq(bus.callback_failures(), std::uint64_t{2});
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_legacy_async_unsubscribe_keeps_queued_copy()
{
using namespace Void::EventBus;
struct Unblock {};
EventBus bus{Mode::Async};
std::latch blocker_entered{1};
std::promise<void> release_blocker;
auto release_future = release_blocker.get_future().share();
bus.subscribe<Unblock>([&](const Unblock&) {
blocker_entered.count_down();
release_future.wait();
});
std::atomic<int> target_hits{0};
const HandlerId target_id = bus.subscribe<Ping>([&](const Ping& p) {
target_hits.fetch_add(p.value, std::memory_order_relaxed);
});
bus.publish(Unblock{});
blocker_entered.wait();
bus.publish(Ping{13});
bus.unsubscribe(target_id);
bus.publish(Ping{100});
release_blocker.set_value();
bus.flush();
Void::Testing::expect_eq(target_hits.load(), 13);
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_sync_reentrant_subscribe_unsubscribe_asan()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
int late_hits = 0;
int primary_hits = 0;
HandlerId removable_id = 0;
bus.subscribe<Ping>([&](const Ping& p) {
++primary_hits;
if (p.value == 1) {
bus.subscribe<Ping>([&](const Ping&) { ++late_hits; });
bus.unsubscribe(removable_id);
}
});
int removed_hits = 0;
removable_id = bus.subscribe<Ping>([&](const Ping&) { ++removed_hits; });
bus.publish(Ping{1});
Void::Testing::expect_eq(primary_hits, 1);
Void::Testing::expect_eq(removed_hits, 0);
Void::Testing::expect_eq(late_hits, 0);
bus.publish(Ping{2});
Void::Testing::expect_eq(primary_hits, 2);
Void::Testing::expect_eq(removed_hits, 0);
Void::Testing::expect_eq(late_hits, 1);
}
Void::Testing::Test bus_publish_after_close_closed()
{
using namespace Void::EventBus;
EventBus bus{Mode::Async};
Void::Testing::require(bus.close_and_join().has_value());
auto sub_res = bus.try_subscribe<Ping>([](const Ping&) {});
Void::Testing::require(!sub_res.has_value());
Void::Testing::expect_eq(
async_code(sub_res.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::closed));
auto pub_res = bus.try_publish(Ping{42});
Void::Testing::require(!pub_res.has_value());
Void::Testing::expect_eq(
async_code(pub_res.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::closed));
}
Void::Testing::Test bus_sync_unsubscribe_releases_captured_state()
{
using namespace Void::EventBus;
EventBus bus{Mode::Sync};
auto s1 = std::make_shared<int>(1);
const HandlerId id = bus.subscribe<Ping>([s1](const Ping&) { (void)s1; });
Void::Testing::expect_eq(s1.use_count(), 2L);
bus.unsubscribe(id);
Void::Testing::expect_eq(s1.use_count(), 1L);
auto s2 = std::make_shared<int>(2);
auto scoped = bus.try_subscribe<Ping>([s2](const Ping&) { (void)s2; });
Void::Testing::require(scoped.has_value());
Void::Testing::expect_eq(s2.use_count(), 2L);
scoped->reset();
Void::Testing::expect_eq(s2.use_count(), 1L);
}
Void::Testing::Test bus_legacy_async_unsubscribe_then_flush_releases_captured_state()
{
using namespace Void::EventBus;
struct Hold {};
EventBus bus{Mode::Async};
std::latch entered{1};
std::promise<void> rel;
auto rel_fut = rel.get_future().share();
bus.subscribe<Hold>([&](const Hold&) {
entered.count_down();
rel_fut.wait();
});
auto sentinel = std::make_shared<int>(77);
const HandlerId id = bus.subscribe<Ping>([sentinel](const Ping&) { (void)sentinel; });
bus.publish(Hold{});
entered.wait();
bus.publish(Ping{1});
bus.unsubscribe(id);
Void::Testing::expect(sentinel.use_count() >= 2L);
rel.set_value();
bus.flush();
Void::Testing::expect_eq(sentinel.use_count(), 1L);
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_legacy_async_close_and_join_releases_capture_with_queued_copies()
{
using namespace Void::EventBus;
struct Hold {};
EventBus bus{Mode::Async};
std::latch entered{1};
std::promise<void> rel;
auto rel_fut = rel.get_future().share();
bus.subscribe<Hold>([&](const Hold&) {
entered.count_down();
rel_fut.wait();
});
auto sentinel = std::make_shared<int>(88);
auto sub = bus.try_subscribe<Ping>([sentinel](const Ping&) { (void)sentinel; });
Void::Testing::require(sub.has_value());
bus.publish(Hold{});
entered.wait();
// Queue copies on the worker queue while Hold keeps worker busy.
bus.publish(Ping{1});
bus.publish(Ping{2});
Void::Testing::expect(sentinel.use_count() >= 3L);
// Must purge queued copies for sub and release captured state immediately
// without blocking on Hold or executing queued Ping callbacks.
Void::Testing::require(sub->close_and_join().has_value());
Void::Testing::expect_eq(sentinel.use_count(), 1L);
rel.set_value();
Void::Testing::require(bus.close_and_join().has_value());
}
Void::Testing::Test bus_destructor_gates_admitted_deliveries()
{
using namespace Void::EventBus;
// 1. Queued ManualExecutor deliveries are gated when ~EventBus destroys.
{
Void::Async::ManualExecutor manual;
int delivered = 0;
{
EventBus bus{manual};
auto sub = bus.try_subscribe<Ping>([&](const Ping&) { ++delivered; });
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
Void::Testing::require(bus.try_publish(Ping{2}).has_value());
}
manual.drain();
Void::Testing::expect_eq(delivered, 0);
}
// 2. Destruction on a thread waits for OTHER thread's in-flight callback,
// gates queued unstarted work, and self-destruction in callback doesn't deadlock.
{
auto exec_res = Void::Async::ThreadExecutor::create(
Void::Async::ThreadExecutorOptions{.workers = 1, .max_admitted = 32});
Void::Testing::require(exec_res.has_value());
auto exec = std::move(*exec_res);
Void::Testing::require(exec->start().has_value());
std::atomic<int> started_count{0};
std::atomic<int> gated_count{0};
std::latch first_in_flight{1};
std::promise<void> allow_first_finish;
auto finish_fut = allow_first_finish.get_future().share();
{
std::optional<EventBus> bus{std::in_place, *exec};
auto s1 = bus->try_subscribe<Ping>([&](const Ping& p) {
if (p.value == 1) {
started_count.fetch_add(1, std::memory_order_relaxed);
first_in_flight.count_down();
finish_fut.wait();
} else {
gated_count.fetch_add(1, std::memory_order_relaxed);
}
});
Void::Testing::require(s1.has_value());
Void::Testing::require(bus->try_publish(Ping{1}).has_value());
first_in_flight.wait();
Void::Testing::require(bus->try_publish(Ping{2}).has_value());
std::atomic<bool> destroyed{false};
std::thread destroyer([&]() {
bus.reset();
destroyed.store(true, std::memory_order_release);
});
std::this_thread::sleep_for(std::chrono::milliseconds{15});
Void::Testing::expect(!destroyed.load(std::memory_order_acquire));
allow_first_finish.set_value();
destroyer.join();
}
exec->close();
Void::Testing::require(exec->join().has_value());
Void::Testing::expect_eq(started_count.load(), 1);
Void::Testing::expect_eq(gated_count.load(), 0);
}
// 3. Destroying EventBus from inside its own Sync callback doesn't deadlock.
{
std::optional<EventBus> bus{std::in_place, Mode::Sync};
int ran = 0;
bus->subscribe<Ping>([&](const Ping&) {
++ran;
bus.reset();
});
bus->publish(Ping{1});
Void::Testing::expect_eq(ran, 1);
Void::Testing::expect(!bus.has_value());
}
}
Void::Testing::Test bus_flush_blocking_self_join_and_manual_invalid()
{
using namespace Void::EventBus;
// ManualExecutor rejects flush_blocking and close_and_join with invalid_argument.
{
Void::Async::ManualExecutor manual;
EventBus bus{manual};
auto fb = bus.flush_blocking();
Void::Testing::require(!fb.has_value());
Void::Testing::expect_eq(
async_code(fb.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::invalid_argument));
auto cj = bus.close_and_join();
Void::Testing::require(!cj.has_value());
Void::Testing::expect_eq(
async_code(cj.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::invalid_argument));
}
// Executor worker thread calling flush_blocking or close_and_join gets self_join.
{
auto exec_res = Void::Async::ThreadExecutor::create(
Void::Async::ThreadExecutorOptions{.workers = 1, .max_admitted = 16});
Void::Testing::require(exec_res.has_value());
auto exec = std::move(*exec_res);
Void::Testing::require(exec->start().has_value());
EventBus bus{*exec};
std::optional<Void::Result::Result<void>> fb_res;
std::optional<Void::Result::Result<void>> cj_res;
auto sub = bus.try_subscribe<Ping>([&](const Ping&) {
fb_res = bus.flush_blocking();
cj_res = bus.close_and_join();
});
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
Void::Testing::require(bus.flush_blocking().has_value());
Void::Testing::require(fb_res.has_value() && !fb_res->has_value());
Void::Testing::expect_eq(
async_code(fb_res->error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
Void::Testing::require(cj_res.has_value() && !cj_res->has_value());
Void::Testing::expect_eq(
async_code(cj_res->error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
// Wrong executor passed to flush_pumping returns invalid_argument.
Void::Async::ManualExecutor other_manual;
auto fp = bus.flush_pumping(other_manual);
Void::Testing::require(!fp.has_value());
Void::Testing::expect_eq(
async_code(fp.error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::invalid_argument));
Void::Testing::require(bus.close_and_join().has_value());
exec->close();
Void::Testing::require(exec->join().has_value());
}
}
Void::Testing::Test bus_pumping_self_join_returns_self_join()
{
using namespace Void::EventBus;
Void::Async::ManualExecutor manual;
EventBus bus{manual};
std::optional<Void::Result::Result<void>> fp_res;
std::optional<Void::Result::Result<void>> cj_res;
auto sub = bus.try_subscribe<Ping>([&](const Ping&) {
fp_res = bus.flush_pumping(manual);
cj_res = bus.close_and_join_pumping(manual);
});
Void::Testing::require(sub.has_value());
Void::Testing::require(bus.try_publish(Ping{7}).has_value());
(void)manual.drain();
Void::Testing::require(fp_res.has_value() && !fp_res->has_value());
Void::Testing::expect_eq(
async_code(fp_res->error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
Void::Testing::require(cj_res.has_value() && !cj_res->has_value());
Void::Testing::expect_eq(
async_code(cj_res->error()),
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::self_join));
Void::Testing::require(bus.close_and_join_pumping(manual).has_value());
}
Void::Testing::Test bus_close_and_join_waits_for_slow_capture_destructor()
{
using namespace Void::EventBus;
struct SlowGuard {
explicit SlowGuard(std::atomic<bool>* p) : destroyed(p) {}
std::atomic<bool>* destroyed{nullptr};
~SlowGuard()
{
if (destroyed != nullptr) {
std::this_thread::sleep_for(std::chrono::milliseconds{15});
destroyed->store(true, std::memory_order_release);
}
}
};
// 1. ThreadExecutor subscription::close_and_join waits until slow capture dtor finishes.
{
auto exec_res = Void::Async::ThreadExecutor::create(
Void::Async::ThreadExecutorOptions{.workers = 2, .max_admitted = 16});
Void::Testing::require(exec_res.has_value());
auto exec = std::move(*exec_res);
Void::Testing::require(exec->start().has_value());
EventBus bus{*exec};
std::atomic<bool> destroyed{false};
std::latch entered{1};
std::promise<void> rel;
auto rel_fut = rel.get_future().share();
auto guard = std::make_shared<SlowGuard>(&destroyed);
auto sub = bus.try_subscribe<Ping>([&, guard](const Ping&) {
(void)guard;
entered.count_down();
rel_fut.wait();
});
Void::Testing::require(sub.has_value());
guard.reset();
Void::Testing::require(bus.try_publish(Ping{1}).has_value());
entered.wait();
std::thread releaser([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds{5});
rel.set_value();
});
Void::Testing::require(sub->close_and_join().has_value());
// Must ALREADY be destroyed when close_and_join returns!
Void::Testing::expect(destroyed.load(std::memory_order_acquire));
releaser.join();
Void::Testing::require(bus.close_and_join().has_value());
exec->close();
Void::Testing::require(exec->join().has_value());
}
// 2. Mode::Async EventBus::close_and_join waits until slow capture dtor finishes.
{
EventBus bus{Mode::Async};
std::atomic<bool> destroyed{false};
std::latch entered{1};
std::promise<void> rel;
auto rel_fut = rel.get_future().share();
auto guard = std::make_shared<SlowGuard>(&destroyed);
auto sub = bus.try_subscribe<Ping>([&, guard](const Ping&) {
(void)guard;
entered.count_down();
rel_fut.wait();
});
Void::Testing::require(sub.has_value());
guard.reset();
bus.publish(Ping{2});
entered.wait();
std::thread releaser([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds{5});
rel.set_value();
});
Void::Testing::require(bus.close_and_join().has_value());
Void::Testing::expect(destroyed.load(std::memory_order_acquire));
releaser.join();
}
}
Void::Testing::Test bus_legacy_async_purged_drop_outside_lock()
{
using namespace Void::EventBus;
struct MuLockingDtor {
EventBus* bus{nullptr};
std::atomic<bool>* dropped{nullptr};
std::atomic<int>* calls{nullptr};
~MuLockingDtor()
{
if (bus != nullptr) {
bus->unsubscribe(0); // Acquires BusCore::mu; would deadlock under lock.
}
if (dropped != nullptr) {
dropped->store(true, std::memory_order_release);
}
if (calls != nullptr) {
calls->fetch_add(1, std::memory_order_relaxed);
}
}
};
EventBus bus{Mode::Async};
std::atomic<bool> dropped{false};
std::atomic<int> dtor_calls{0};
std::atomic<int> b_ran{0};
std::optional<Void::Result::Result<void>> sub_b_join_res;
auto sub_b_ptr = std::make_shared<std::optional<EventBus::Subscription>>();
// Subscribe A before B so run_worker visits A first for the same queued item.
auto sub_a = bus.try_subscribe<Ping>([&](const Ping&) {
if (*sub_b_ptr) {
sub_b_join_res = (*sub_b_ptr)->close_and_join();
}
});
Void::Testing::require(sub_a.has_value());
{
auto guard = std::shared_ptr<MuLockingDtor>(
new MuLockingDtor{&bus, &dropped, &dtor_calls});
auto sb = bus.try_subscribe<Ping>([&, guard](const Ping&) {
(void)guard;
b_ran.fetch_add(1, std::memory_order_relaxed);
});
Void::Testing::require(sb.has_value());
*sub_b_ptr = std::move(*sb);
}
bus.publish(Ping{1});
bus.flush();
Void::Testing::require(sub_b_join_res.has_value());
Void::Testing::expect(sub_b_join_res->has_value());
Void::Testing::expect_eq(b_ran.load(), 0);
Void::Testing::expect(dropped.load(std::memory_order_acquire));
Void::Testing::expect_eq(dtor_calls.load(), 1);
Void::Testing::require(bus.close_and_join().has_value());
}
+245
View File
@@ -0,0 +1,245 @@
#include <Void/Async/FuturePool.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <future>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
// All assertions run on the test thread; callables executed by workers only
// touch atomics (the assertion context is thread_local).
namespace
{
using namespace Void::Async;
using namespace std::chrono_literals;
class Gate
{
public:
void open()
{
{
std::lock_guard lk{mu_};
open_ = true;
}
cv_.notify_all();
}
void wait()
{
std::unique_lock lk{mu_};
cv_.wait(lk, [this] { return open_; });
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
};
template <class Pred>
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
{
const auto end = std::chrono::steady_clock::now() + timeout;
while (!pred()) {
if (std::chrono::steady_clock::now() >= end) {
return false;
}
std::this_thread::sleep_for(1ms);
}
return true;
}
// Opens the gate before the executor is destroyed, so a failed assertion can
// never leave a blocked callable hanging ~ThreadExecutor.
struct Fixture {
Gate gate{};
std::unique_ptr<ThreadExecutor> exec{};
Fixture(std::size_t workers, std::size_t max_admitted)
{
auto created = ThreadExecutor::create(
ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted});
Void::Testing::require(created.has_value());
exec = std::move(*created);
Void::Testing::require(exec->start().has_value());
}
~Fixture() { gate.open(); }
Fixture(const Fixture&) = delete;
Fixture& operator=(const Fixture&) = delete;
};
// Move-only callable that records every move: proves a rejected submission
// never consumed it.
struct TrackedCallable {
std::shared_ptr<std::atomic<int>> moves{std::make_shared<std::atomic<int>>(0)};
std::unique_ptr<int> payload{std::make_unique<int>(41)};
std::atomic<bool>* ran{nullptr};
TrackedCallable() = default;
explicit TrackedCallable(std::atomic<bool>* ran_flag) : ran(ran_flag) {}
TrackedCallable(TrackedCallable&& other) noexcept
: moves(other.moves)
, payload(std::move(other.payload))
, ran(other.ran)
{
moves->fetch_add(1);
}
TrackedCallable& operator=(TrackedCallable&&) = delete;
TrackedCallable(const TrackedCallable&) = delete;
TrackedCallable& operator=(const TrackedCallable&) = delete;
int operator()()
{
if (ran != nullptr) {
ran->store(true);
}
return payload ? *payload + 1 : -1;
}
};
} // namespace
Void::Testing::Test future_pool_overloaded_does_not_consume_callable()
{
std::atomic<bool> blocker_running{false};
std::atomic<bool> ran{false};
Fixture fx{1, 1};
FuturePool pool{*fx.exec};
auto blocker = pool.try_submit([&] {
blocker_running.store(true);
fx.gate.wait();
return 7;
});
Void::Testing::require(blocker.has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
TrackedCallable callable{&ran};
const auto rejected = pool.try_submit(std::move(callable));
Void::Testing::require(!rejected.has_value());
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
// Reserve-then-transfer: the callable was not even moved from.
Void::Testing::expect_eq(callable.moves->load(), 0);
Void::Testing::require(callable.payload != nullptr);
Void::Testing::expect_eq(*callable.payload, 41);
Void::Testing::expect(!ran.load());
fx.gate.open();
Void::Testing::expect_eq(blocker->get(), 7);
Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; }));
// The very same callable is still usable.
auto accepted = pool.try_submit(std::move(callable));
Void::Testing::require(accepted.has_value());
Void::Testing::expect_eq(accepted->get(), 42);
Void::Testing::expect(ran.load());
}
Void::Testing::Test future_pool_stopped_after_close()
{
Fixture fx{1, 4};
FuturePool pool{*fx.exec};
auto before = pool.try_submit([] { return 1; });
Void::Testing::require(before.has_value());
Void::Testing::expect_eq(before->get(), 1);
fx.exec->close();
std::atomic<bool> ran{false};
TrackedCallable callable{&ran};
const auto stopped = pool.try_submit(std::move(callable));
Void::Testing::require(!stopped.has_value());
Void::Testing::expect(stopped.error() == AdmissionError::stopped);
Void::Testing::expect_eq(callable.moves->load(), 0);
Void::Testing::expect(callable.payload != nullptr);
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{0});
Void::Testing::require(fx.exec->join().has_value());
Void::Testing::expect(!ran.load());
}
Void::Testing::Test future_pool_exception_in_future()
{
Fixture fx{2, 8};
FuturePool pool{*fx.exec};
auto failing = pool.try_submit([]() -> int { throw std::runtime_error{"boom"}; });
Void::Testing::require(failing.has_value());
bool caught = false;
try {
(void)failing->get();
} catch (const std::runtime_error& error) {
caught = std::string{error.what()} == "boom";
}
Void::Testing::expect(caught);
// void callables work, and a thrown exception does not poison the pool.
std::atomic<int> ran{0};
auto void_job = pool.try_submit([&ran] { ran.fetch_add(1); });
Void::Testing::require(void_job.has_value());
void_job->get();
Void::Testing::expect_eq(ran.load(), 1);
auto after = pool.try_submit([] { return 5; });
Void::Testing::require(after.has_value());
Void::Testing::expect_eq(after->get(), 5);
// Slots are released even when the callable threw.
Void::Testing::expect(wait_until([&] { return fx.exec->admitted() == 0; }));
}
Void::Testing::Test future_pool_bound_includes_running()
{
std::atomic<bool> first_running{false};
std::atomic<int> started{0};
Fixture fx{1, 2};
FuturePool pool{*fx.exec};
auto running = pool.try_submit([&] {
first_running.store(true);
started.fetch_add(1);
fx.gate.wait();
return 1;
});
Void::Testing::require(running.has_value());
Void::Testing::require(wait_until([&] { return first_running.load(); }));
// The running callable still counts against the bound.
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{1});
auto queued = pool.try_submit([&] {
started.fetch_add(1);
return 2;
});
Void::Testing::require(queued.has_value());
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{2});
const auto rejected = pool.try_submit([] { return 3; });
Void::Testing::require(!rejected.has_value());
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
Void::Testing::expect_eq(fx.exec->stats().rejected, std::uint64_t{1});
fx.gate.open();
Void::Testing::expect_eq(running->get(), 1);
Void::Testing::expect_eq(queued->get(), 2);
Void::Testing::expect_eq(started.load(), 2);
Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; }));
auto again = pool.try_submit([] { return 4; });
Void::Testing::require(again.has_value());
Void::Testing::expect_eq(again->get(), 4);
}
@@ -0,0 +1,236 @@
#include <Void/Async/Observable.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <utility>
#include <vector>
namespace
{
struct MoveOnlyVal {
int id{0};
MoveOnlyVal() = default;
explicit MoveOnlyVal(int v) noexcept : id{v} {}
MoveOnlyVal(const MoveOnlyVal&) = delete;
MoveOnlyVal& operator=(const MoveOnlyVal&) = delete;
MoveOnlyVal(MoveOnlyVal&&) noexcept = default;
MoveOnlyVal& operator=(MoveOnlyVal&&) noexcept = default;
[[nodiscard]] bool operator==(const MoveOnlyVal& other) const noexcept
{
return id == other.id;
}
};
} // namespace
Void::Testing::Test observable_nested_set_fifo()
{
using namespace Void::Observable;
Observable<int> obs{0};
std::vector<std::pair<int, int>> seen;
obs.on_change([&](const int& old_v, const int& new_v) {
seen.emplace_back(old_v, new_v);
if (new_v == 1) {
obs.set(2);
Void::Testing::expect_eq(obs.get(), 2);
obs.set(3);
Void::Testing::expect_eq(obs.get(), 3);
}
});
obs.set(1);
Void::Testing::expect_eq(obs.get(), 3);
Void::Testing::require(seen.size() == 3);
Void::Testing::expect_eq(seen[0].first, 0);
Void::Testing::expect_eq(seen[0].second, 1);
Void::Testing::expect_eq(seen[1].first, 1);
Void::Testing::expect_eq(seen[1].second, 2);
Void::Testing::expect_eq(seen[2].first, 2);
Void::Testing::expect_eq(seen[2].second, 3);
}
Void::Testing::Test observable_unsubscribe_in_listener_skips_rest()
{
using namespace Void::Observable;
Observable<int> obs{0};
int second_hits = 0;
Handle second_h{};
obs.on_change([&](const int&, const int&) { obs.unsubscribe(second_h); });
second_h = obs.on_change([&](const int&, const int&) { ++second_hits; });
obs.set(1);
Void::Testing::expect_eq(second_hits, 0);
obs.set(2);
Void::Testing::expect_eq(second_hits, 0);
}
Void::Testing::Test observable_subscribe_in_listener_not_current_pass()
{
using namespace Void::Observable;
Observable<int> obs{0};
int late_hits = 0;
bool added = false;
obs.on_change([&](const int&, const int&) {
if (!added) {
added = true;
obs.on_change([&](const int&, const int&) { ++late_hits; });
}
});
obs.set(1);
Void::Testing::expect_eq(late_hits, 0);
obs.set(2);
Void::Testing::expect_eq(late_hits, 1);
}
Void::Testing::Test observable_try_set_overloaded_when_pending_full()
{
using namespace Void::Observable;
Observable<int> obs{0};
Void::Result::Result<void> overflow_res{};
bool overflow_checked = false;
obs.on_change([&](const int&, const int& new_v) {
if (new_v == 1) {
for (std::size_t i = 0; i < kMaxPendingNotifications; ++i) {
auto r = obs.try_set(static_cast<int>(i + 2));
if (!r.has_value()) {
overflow_checked = false;
return;
}
}
const int val_before_overload = obs.get();
overflow_res = obs.try_set(999999);
Void::Testing::expect_eq(obs.get(), val_before_overload);
// Overflow via set() updates value and increments dropped_notifications.
obs.set(888888);
Void::Testing::expect_eq(obs.get(), 888888);
overflow_checked = true;
}
});
obs.set(1);
Void::Testing::expect(overflow_checked);
Void::Testing::require(!overflow_res.has_value());
Void::Testing::expect_eq(
overflow_res.error().code().value,
static_cast<std::int32_t>(Void::Async::AsyncErrorCode::overloaded));
Void::Testing::expect_eq(obs.get(), 888888);
Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{1});
}
Void::Testing::Test observable_listener_throw_restores_state()
{
using namespace Void::Observable;
Observable<int> obs{0};
int normal_hits = 0;
obs.on_change([&](const int&, const int& new_v) {
if (new_v == 1) {
obs.set(2);
obs.set(3);
throw std::runtime_error("listener_boom");
}
++normal_hits;
});
bool caught = false;
try {
obs.set(1);
} catch (const std::runtime_error&) {
caught = true;
}
Void::Testing::expect(caught);
Void::Testing::expect_eq(obs.get(), 3);
Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{2});
// Subsequent set operates cleanly with depth restored to 0.
obs.set(4);
Void::Testing::expect_eq(obs.get(), 4);
Void::Testing::expect_eq(normal_hits, 1);
}
Void::Testing::Test observable_self_unsubscribe_releases_capture()
{
using namespace Void::Observable;
Observable<int> obs{0};
auto sentinel = std::make_shared<int>(55);
Handle h{};
h = obs.on_change([&, sentinel](const int&, const int&) {
(void)sentinel;
Void::Testing::expect(obs.unsubscribe(h));
});
Void::Testing::expect_eq(sentinel.use_count(), 2L);
obs.set(1);
Void::Testing::expect_eq(sentinel.use_count(), 1L);
Void::Testing::expect_eq(obs.listener_count(), std::size_t{0});
}
Void::Testing::Test observable_move_only_immediate_notification_compat()
{
using namespace Void::Observable;
Observable<MoveOnlyVal> obs{MoveOnlyVal{0}};
std::vector<std::pair<int, int>> trace;
obs.on_change([&](const MoveOnlyVal& ov, const MoveOnlyVal& nv) {
trace.emplace_back(ov.id, nv.id);
if (nv.id == 1) {
obs.set(MoveOnlyVal{2});
}
});
obs.on_change([&](const MoveOnlyVal& ov, const MoveOnlyVal& nv) {
trace.emplace_back(ov.id * 10, nv.id * 10);
});
obs.set(MoveOnlyVal{1});
// Immediate recursive delivery matches 1.x notify(old, value_) aliasing.
Void::Testing::require(trace.size() == 4);
Void::Testing::expect_eq(trace[0].first, 0);
Void::Testing::expect_eq(trace[0].second, 1);
Void::Testing::expect_eq(trace[1].first, 1);
Void::Testing::expect_eq(trace[1].second, 2);
Void::Testing::expect_eq(trace[2].first, 10);
Void::Testing::expect_eq(trace[2].second, 20);
Void::Testing::expect_eq(trace[3].first, 0);
Void::Testing::expect_eq(trace[3].second, 20);
Void::Testing::expect_eq(obs.dropped_notifications(), std::size_t{0});
}
Void::Testing::Test signal_reentrant_connect_disconnect_during_emit()
{
using namespace Void::Observable;
Signal<int> sig;
std::vector<int> log;
Handle second_h{};
Handle third_h{};
sig.connect([&](const int& v) {
log.push_back(v);
if (v == 1) {
Void::Testing::expect(sig.disconnect(second_h));
third_h = sig.connect([&](const int& x) { log.push_back(x * 100); });
sig.emit(2);
}
});
second_h = sig.connect([&](const int& v) { log.push_back(v * 10); });
sig.emit(1);
// First emit skips disconnected second_h and skips newly added third_h;
// queued emit(2) runs first slot and third_h FIFO.
Void::Testing::require(log.size() == 3);
Void::Testing::expect_eq(log[0], 1);
Void::Testing::expect_eq(log[1], 2);
Void::Testing::expect_eq(log[2], 200);
Void::Testing::expect(third_h.id != 0);
}
@@ -0,0 +1,626 @@
#include <Void/Async/ParallelFor.hpp>
#include <Void/Async/ThreadPool.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <expected>
#include <limits>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
// Assertions run on the test thread only (the assertion context is
// thread_local); the loop bodies executed by pool workers only touch atomics or
// distinct array elements.
namespace
{
using namespace Void::Concurrency;
using namespace std::chrono_literals;
using Kind = ParallelForError::Kind;
class Gate
{
public:
void open()
{
{
std::lock_guard lk{mu_};
open_ = true;
}
cv_.notify_all();
}
void wait()
{
std::unique_lock lk{mu_};
cv_.wait(lk, [this] { return open_; });
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
};
template <class Pred>
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
{
const auto end = std::chrono::steady_clock::now() + timeout;
while (!pred()) {
if (std::chrono::steady_clock::now() >= end) {
return false;
}
std::this_thread::sleep_for(1ms);
}
return true;
}
// Tracks the maximum number of concurrently running loop bodies.
struct ConcurrencyMeter {
std::atomic<int> active{0};
std::atomic<int> peak{0};
void enter()
{
const int now = active.fetch_add(1) + 1;
int seen = peak.load();
while (now > seen && !peak.compare_exchange_weak(seen, now)) {
}
}
void leave() { active.fetch_sub(1); }
};
std::string what(const std::exception_ptr& error)
{
if (!error) {
return "<none>";
}
try {
std::rethrow_exception(error);
} catch (const std::exception& e) {
return e.what();
} catch (...) {
return "<non-std>";
}
}
// Opens the gate on destruction so a failed assertion cannot leave a blocked
// pool task hanging ~ThreadPool. Declare it AFTER the pool it protects.
struct GateGuard {
Gate& gate;
~GateGuard() { gate.open(); }
};
// Opens the gate and joins a helper thread on every exit path.
struct ThreadJoiner {
Gate& gate;
std::thread& thread;
~ThreadJoiner()
{
gate.open();
if (thread.joinable()) {
thread.join();
}
}
};
} // namespace
Void::Testing::Test parallel_for_bounded_grain_and_concurrency_limit()
{
constexpr int kCount = 40;
ThreadPool pool{4};
// grain = 3 over [0, 40): 14 chunks, at most 2 running at once.
{
ConcurrencyMeter meter;
std::vector<std::atomic<int>> hits(kCount);
std::vector<std::thread::id> owner(kCount);
std::vector<std::uint64_t> order(kCount, 0);
std::atomic<std::uint64_t> sequence{0};
const auto result = parallel_for(
0, kCount,
[&](int i) {
meter.enter();
owner[static_cast<std::size_t>(i)] = std::this_thread::get_id();
order[static_cast<std::size_t>(i)] = sequence.fetch_add(1);
hits[static_cast<std::size_t>(i)].fetch_add(1);
std::this_thread::sleep_for(1ms);
meter.leave();
},
pool, ParallelForOptions{.grain = 3, .max_concurrency = 2});
Void::Testing::expect(result.has_value());
int bad_hits = 0;
int chunk_not_on_one_thread = 0;
int chunk_not_ordered = 0;
for (int i = 0; i < kCount; ++i) {
if (hits[static_cast<std::size_t>(i)].load() != 1) {
++bad_hits;
}
if (i % 3 != 0) {
if (owner[static_cast<std::size_t>(i)] != owner[static_cast<std::size_t>(i - 1)]) {
++chunk_not_on_one_thread;
}
if (order[static_cast<std::size_t>(i)] <= order[static_cast<std::size_t>(i - 1)]) {
++chunk_not_ordered;
}
}
}
Void::Testing::expect_eq(bad_hits, 0);
Void::Testing::expect_eq(chunk_not_on_one_thread, 0);
Void::Testing::expect_eq(chunk_not_ordered, 0);
Void::Testing::expect(meter.peak.load() >= 1);
Void::Testing::expect(meter.peak.load() <= 2);
}
// max_concurrency == 0 means the pool's thread count.
{
ConcurrencyMeter meter;
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 64,
[&](int) {
meter.enter();
calls.fetch_add(1);
std::this_thread::sleep_for(1ms);
meter.leave();
},
pool, ParallelForOptions{});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 64);
Void::Testing::expect(meter.peak.load() <= 4);
}
// The error report carries the chunk geometry: 40 indices / grain 3 = 14.
{
std::atomic<int> calls{0};
const auto result = parallel_for(
0, kCount,
[&](int i) {
calls.fetch_add(1);
if (i == 7) {
throw std::runtime_error{"seven"};
}
},
pool, ParallelForOptions{.grain = 3, .max_concurrency = 2, .stop_on_error = false});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{14});
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{14});
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1});
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{2});
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"seven"});
// The throwing chunk [6, 9) stops at index 7; every other chunk ran fully.
Void::Testing::expect_eq(calls.load(), kCount - 1);
}
}
Void::Testing::Test parallel_for_bounded_signed_and_unsigned_ranges()
{
ThreadPool pool{3};
// Signed range crossing zero.
{
std::atomic<int> sum{0};
std::atomic<int> calls{0};
const auto result = parallel_for(
-5, 5, [&](int i) { sum.fetch_add(i); calls.fetch_add(1); }, pool,
ParallelForOptions{.grain = 4});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 10);
Void::Testing::expect_eq(sum.load(), -5);
}
// The whole int8 range: 255 indices computed in the unsigned type.
{
std::vector<std::atomic<int>> hits(256);
const auto result = parallel_for(
std::int8_t{-128}, std::int8_t{127},
[&](std::int8_t i) { hits[static_cast<std::size_t>(i + 128)].fetch_add(1); }, pool,
ParallelForOptions{.grain = 7});
Void::Testing::expect(result.has_value());
int wrong = 0;
for (std::size_t k = 0; k < 255; ++k) {
if (hits[k].load() != 1) {
++wrong;
}
}
Void::Testing::expect_eq(wrong, 0);
Void::Testing::expect_eq(hits[255].load(), 0);
}
// Top of the unsigned range, and a grain larger than the range.
{
std::atomic<int> calls{0};
std::atomic<std::uint64_t> sum{0};
const std::uint64_t top = std::numeric_limits<std::uint64_t>::max();
const auto result = parallel_for(
top - 3, top, [&](std::uint64_t i) { calls.fetch_add(1); sum.fetch_add(top - i); }, pool,
ParallelForOptions{.grain = 1000});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 3);
Void::Testing::expect_eq(sum.load(), std::uint64_t{3 + 2 + 1});
}
}
Void::Testing::Test parallel_for_bounded_stop_joins_started_no_new_chunks()
{
ThreadPool pool{2};
// One runner: chunk 0 requests stop; no later chunk may start.
{
std::stop_source stop;
std::atomic<int> started{0};
std::atomic<int> finished{0};
const auto result = parallel_for(
0, 100,
[&](int i) {
started.fetch_add(1);
if (i == 0) {
stop.request_stop();
std::this_thread::sleep_for(5ms);
}
finished.fetch_add(1);
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::stopped);
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{100});
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{1});
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{0});
Void::Testing::expect(!result.error().first_failed_chunk.has_value());
// The started chunk was joined (ran to completion) and nothing else ran.
Void::Testing::expect_eq(started.load(), 1);
Void::Testing::expect_eq(finished.load(), 1);
}
// Two runners: every chunk that started finishes; the rest never start.
{
std::stop_source stop;
std::atomic<int> started{0};
std::atomic<int> finished{0};
const auto result = parallel_for(
0, 1000,
[&](int i) {
started.fetch_add(1);
if (i == 3) {
stop.request_stop();
}
std::this_thread::sleep_for(1ms);
finished.fetch_add(1);
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::stopped);
Void::Testing::expect_eq(started.load(), finished.load());
Void::Testing::expect_eq(result.error().chunks_started, static_cast<std::size_t>(started.load()));
Void::Testing::expect(result.error().chunks_started < std::size_t{1000});
Void::Testing::expect(result.error().chunks_started >= std::size_t{4});
}
// Stop requested before the call: nothing runs.
{
std::stop_source stop;
stop.request_stop();
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 10, [&](int) { calls.fetch_add(1); }, pool,
ParallelForOptions{.stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::stopped);
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{0});
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10});
Void::Testing::expect_eq(calls.load(), 0);
}
// A stop that arrives once every chunk has started is not an error.
{
std::stop_source stop;
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 4,
[&](int i) {
calls.fetch_add(1);
if (i == 3) {
stop.request_stop();
}
},
pool, ParallelForOptions{.max_concurrency = 1, .stop = stop.get_token()});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 4);
}
}
Void::Testing::Test parallel_for_bounded_errors_join_all_lowest_index_reported()
{
ThreadPool pool{2};
// stop_on_error == false: every chunk runs; the lowest failed chunk wins
// even though higher chunks fail first or concurrently.
{
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 10,
[&](int i) {
calls.fetch_add(1);
if (i == 5 || i == 2 || i == 8) {
throw std::runtime_error{"chunk " + std::to_string(i)};
}
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = false});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(calls.load(), 10);
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10});
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{10});
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{3});
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{2});
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"chunk 2"});
}
// stop_on_error == true: chunk 1 fails first, chunk 0 (already started)
// fails afterwards. The caller joins both and reports the LOWER chunk; no
// new chunk starts after the first failure.
{
std::atomic<bool> chunk_one_failed{false};
std::atomic<bool> chunk_zero_timed_out{false};
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 10,
[&](int i) {
calls.fetch_add(1);
if (i == 0) {
const auto end = std::chrono::steady_clock::now() + 5s;
while (!chunk_one_failed.load() && std::chrono::steady_clock::now() < end) {
std::this_thread::yield();
}
if (!chunk_one_failed.load()) {
chunk_zero_timed_out.store(true);
}
throw std::runtime_error{"zero"};
}
if (i == 1) {
chunk_one_failed.store(true);
throw std::runtime_error{"one"};
}
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = true});
Void::Testing::require(!result.has_value());
Void::Testing::expect(!chunk_zero_timed_out.load());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{2});
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{0});
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"zero"});
// Only the two started chunks ran.
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{2});
Void::Testing::expect_eq(calls.load(), 2);
}
// `failed` outranks `stopped`.
{
std::stop_source stop;
const auto result = parallel_for(
0, 10,
[&](int i) {
if (i == 0) {
stop.request_stop();
throw std::runtime_error{"failed and stopped"};
}
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1});
}
// A non-std exception is preserved as an exception_ptr.
{
const auto result = parallel_for(
0, 3, [](int i) { if (i == 1) { throw 42; } }, pool,
ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop_on_error = false});
Void::Testing::require(!result.has_value());
bool is_int = false;
try {
std::rethrow_exception(result.error().first_exception);
} catch (int value) {
is_int = value == 42;
} catch (...) {
}
Void::Testing::expect(is_int);
}
}
Void::Testing::Test parallel_for_bounded_zero_grain_invalid()
{
ThreadPool pool{2};
std::atomic<int> calls{0};
const auto zero_grain = parallel_for(
0, 10, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{.grain = 0});
Void::Testing::require(!zero_grain.has_value());
Void::Testing::expect(zero_grain.error().kind == Kind::invalid_argument);
Void::Testing::expect_eq(zero_grain.error().chunks_total, std::size_t{0});
Void::Testing::expect_eq(zero_grain.error().chunks_started, std::size_t{0});
Void::Testing::expect_eq(calls.load(), 0);
// An empty or reversed range is a success and runs nothing.
const auto empty = parallel_for(5, 5, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{});
Void::Testing::expect(empty.has_value());
const auto reversed = parallel_for(9, 2, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{});
Void::Testing::expect(reversed.has_value());
Void::Testing::expect_eq(calls.load(), 0);
// The legacy overloads are unchanged.
std::atomic<int> legacy{0};
parallel_for(0, 5, [&](int) { legacy.fetch_add(1); }, pool);
Void::Testing::expect_eq(legacy.load(), 5);
}
Void::Testing::Test parallel_for_bounded_rejected_pool_runs_inline()
{
Gate gate;
std::atomic<bool> blocker_started{false};
{
// One worker, queue bound 1: occupy the worker and fill the queue so
// every try_submit is rejected.
ThreadPool pool{1, 1};
GateGuard guard{gate};
auto blocker = pool.submit([&] {
blocker_started.store(true);
gate.wait();
});
Void::Testing::require(wait_until([&] { return blocker_started.load(); }));
auto filler = pool.submit([] {});
Void::Testing::expect_eq(pool.pending_count(), std::size_t{1});
std::vector<std::thread::id> owner(20);
std::atomic<int> calls{0};
const auto caller = std::this_thread::get_id();
const auto result = parallel_for(
0, 20,
[&](int i) {
owner[static_cast<std::size_t>(i)] = std::this_thread::get_id();
calls.fetch_add(1);
},
pool, ParallelForOptions{.grain = 4, .max_concurrency = 3});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 20);
int off_caller = 0;
for (const auto& id : owner) {
if (id != caller) {
++off_caller;
}
}
// The pool rejected the runner, so the calling thread ran everything.
Void::Testing::expect_eq(off_caller, 0);
Void::Testing::expect(pool.stats().rejected >= 1);
gate.open();
blocker.get();
filler.get();
}
// Partial rejection: the caller joins the accepted runner but the bound
// on running chunks still holds (accepted runners + the caller).
{
ThreadPool pool{1, 1};
ConcurrencyMeter meter;
std::vector<std::atomic<int>> hits(30);
const auto result = parallel_for(
0, 30,
[&](int i) {
meter.enter();
hits[static_cast<std::size_t>(i)].fetch_add(1);
std::this_thread::sleep_for(1ms);
meter.leave();
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2});
Void::Testing::expect(result.has_value());
int wrong = 0;
for (const auto& hit : hits) {
if (hit.load() != 1) {
++wrong;
}
}
Void::Testing::expect_eq(wrong, 0);
Void::Testing::expect(meter.peak.load() <= 2);
}
}
Void::Testing::Test parallel_for_bounded_waits_all_submitted_runners()
{
Gate gate;
std::atomic<bool> blocker_started{false};
std::atomic<bool> returned{false};
std::atomic<int> calls{0};
std::optional<std::expected<void, ParallelForError>> outcome;
std::stop_source stop;
ThreadPool pool{1};
GateGuard guard{gate};
auto blocker = pool.submit([&] {
blocker_started.store(true);
gate.wait();
});
Void::Testing::require(wait_until([&] { return blocker_started.load(); }));
// Three runners queue behind the blocker and cannot start. The caller must
// still wait for every one of them, also after a stop was requested.
std::thread caller([&] {
outcome = parallel_for(
0, 100, [&](int) { calls.fetch_add(1); }, pool,
ParallelForOptions{.grain = 10, .max_concurrency = 3, .stop = stop.get_token()});
returned.store(true);
});
ThreadJoiner joiner{gate, caller};
Void::Testing::expect(wait_until([&] { return pool.pending_count() == 3; }));
stop.request_stop();
std::this_thread::sleep_for(60ms);
Void::Testing::expect(!returned.load());
gate.open();
caller.join();
blocker.get();
Void::Testing::expect(returned.load());
Void::Testing::require(outcome.has_value());
Void::Testing::require(!outcome->has_value());
Void::Testing::expect((*outcome).error().kind == Kind::stopped);
// The runners found the stop request: no chunk ever started.
Void::Testing::expect_eq((*outcome).error().chunks_started, std::size_t{0});
Void::Testing::expect_eq((*outcome).error().chunks_total, std::size_t{10});
Void::Testing::expect_eq(calls.load(), 0);
// Every runner future was waited for: the queue is empty.
Void::Testing::expect_eq(pool.pending_count(), std::size_t{0});
}
Void::Testing::Test legacy_parallel_for_exception_joins_all()
{
ThreadPool pool{2};
std::atomic<int> finished{0};
bool caught = false;
try {
parallel_for(0, 8, [&](int i) {
if (i == 0) {
throw std::runtime_error{"first"};
}
std::this_thread::sleep_for(25ms);
finished.fetch_add(1);
}, pool);
} catch (const std::runtime_error& error) {
caught = std::string{error.what()} == "first";
}
Void::Testing::expect(caught);
// The exception surfaced only after every other task finished; none is
// still running against this stack.
Void::Testing::expect_eq(finished.load(), 7);
// With several failures the first (lowest index) is rethrown.
std::atomic<int> second_finished{0};
std::string message;
try {
parallel_for(0, 6, [&](int i) {
std::this_thread::sleep_for(5ms);
second_finished.fetch_add(1);
if (i == 1 || i == 3) {
throw std::runtime_error{"error " + std::to_string(i)};
}
}, pool);
} catch (const std::runtime_error& error) {
message = error.what();
}
Void::Testing::expect_eq(message, std::string{"error 1"});
Void::Testing::expect_eq(second_finished.load(), 6);
}
+881
View File
@@ -0,0 +1,881 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>
// Every assertion runs on the test thread: jobs executed by workers only touch
// atomics or mutex-guarded containers (the assertion context is thread_local).
namespace
{
using namespace Void::Async;
using namespace std::chrono_literals;
// Detached, self-destroying coroutine frame created suspended: a handle to
// post. A job that is never resumed must be destroy()ed by its creator.
struct Job {
struct promise_type {
Job get_return_object() noexcept
{
return Job{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{};
};
Job make_job(std::function<void()> body)
{
body();
co_return;
}
class Gate
{
public:
void open()
{
{
std::lock_guard lk{mu_};
open_ = true;
}
cv_.notify_all();
}
void wait()
{
std::unique_lock lk{mu_};
cv_.wait(lk, [this] { return open_; });
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
};
template <class Pred>
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
{
const auto end = std::chrono::steady_clock::now() + timeout;
while (!pred()) {
if (std::chrono::steady_clock::now() >= end) {
return false;
}
std::this_thread::sleep_for(1ms);
}
return true;
}
// Owns the executor and a gate. The destructor opens the gate FIRST, so a
// failed assertion can never leave a blocker job hanging ~ThreadExecutor, then
// destroys the executor (which joins) and finally the gate.
struct Fixture {
Gate gate{};
std::unique_ptr<ThreadExecutor> exec{};
Fixture(std::size_t workers, std::size_t max_admitted, bool start = true)
{
auto created = ThreadExecutor::create(
ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted});
Void::Testing::require(created.has_value());
exec = std::move(*created);
if (start) {
Void::Testing::require(exec->start().has_value());
}
}
~Fixture() { gate.open(); }
Fixture(const Fixture&) = delete;
Fixture& operator=(const Fixture&) = delete;
ThreadExecutor& operator*() { return *exec; }
ThreadExecutor* operator->() { return exec.get(); }
};
// A job that occupies a worker until the fixture gate opens.
Job make_blocker(Fixture& fx, std::atomic<bool>& running)
{
return make_job([&fx, &running] {
running.store(true, std::memory_order_release);
fx.gate.wait();
});
}
std::optional<AsyncErrorCode> async_code(const Void::Result::Error& error)
{
if (error.code().domain != Void::Result::kAsyncErrorDomain) {
return std::nullopt;
}
return static_cast<AsyncErrorCode>(error.code().value);
}
Void::Coro::Task<void> bump_task(std::atomic<int>* counter)
{
counter->fetch_add(1, std::memory_order_relaxed);
co_return;
}
// Posts `job` through one of the four admission paths (retrying while the
// bound is full). Returns false (and destroys the frame) on an unexpected
// rejection. Assertion free: runs on poster threads.
bool post_one(ThreadExecutor& exec, int kind, Job& job)
{
switch (kind) {
case 0:
for (;;) {
const auto admitted = exec.try_post(job.handle);
if (admitted.has_value()) {
return true;
}
if (admitted.error() != AdmissionError::overloaded) {
job.handle.destroy();
return false;
}
std::this_thread::yield();
}
case 1:
exec.post(job.handle);
return true;
case 2:
exec.post_completion(job.handle);
return true;
default:
for (;;) {
const auto reserved = exec.try_reserve_slot();
if (reserved.has_value()) {
break;
}
if (reserved.error() != AdmissionError::overloaded) {
job.handle.destroy();
return false;
}
std::this_thread::yield();
}
exec.commit_reserved(job.handle);
return true;
}
}
} // namespace
Void::Testing::Test thread_executor_create_starts_no_threads()
{
std::atomic<int> hook_calls{0};
std::atomic<int> ran{0};
auto created = ThreadExecutor::create(ThreadExecutorOptions{
.workers = 2,
.max_admitted = 4,
.before_worker_start = [&hook_calls](std::size_t) -> Void::Result::Result<void> {
hook_calls.fetch_add(1);
return {};
}});
Void::Testing::require(created.has_value());
auto& exec = **created;
// No thread (and no hook call) exists yet.
Void::Testing::expect_eq(hook_calls.load(), 0);
Void::Testing::expect(exec.idle());
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
Void::Testing::expect(exec.supports_reservation());
Void::Testing::expect(exec.has_background_workers());
// Admission before start() queues normally and nothing runs.
auto job = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(job.handle).has_value());
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
std::this_thread::sleep_for(30ms);
Void::Testing::expect_eq(ran.load(), 0);
Void::Testing::expect_eq(exec.stats().queued, std::size_t{1});
Void::Testing::expect(!exec.idle());
Void::Testing::require(exec.start().has_value());
Void::Testing::expect_eq(hook_calls.load(), 2);
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
Void::Testing::require(exec.join().has_value());
// create() validates its options.
const auto zero_workers = ThreadExecutor::create(ThreadExecutorOptions{.workers = 0});
Void::Testing::require(!zero_workers.has_value());
Void::Testing::expect(async_code(zero_workers.error()) == AsyncErrorCode::invalid_argument);
const auto zero_bound = ThreadExecutor::create(ThreadExecutorOptions{.max_admitted = 0});
Void::Testing::require(!zero_bound.has_value());
Void::Testing::expect(async_code(zero_bound.error()) == AsyncErrorCode::invalid_argument);
}
Void::Testing::Test thread_executor_bound_includes_running_work()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> ran{0};
Fixture exec{1, 2};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
// The running blocker keeps its slot.
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
Void::Testing::expect_eq(exec->stats().running, std::size_t{1});
auto queued = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec->try_post(queued.handle).has_value());
Void::Testing::expect_eq(exec->admitted(), std::size_t{2});
// running (1) + queued (1) == max_admitted (2): the next one is rejected.
auto rejected = make_job([&ran] { ran.fetch_add(100); });
const auto overloaded = exec->try_post(rejected.handle);
Void::Testing::expect(!overloaded.has_value());
Void::Testing::expect(overloaded.error() == AdmissionError::overloaded);
rejected.handle.destroy();
Void::Testing::expect_eq(exec->stats().rejected, std::uint64_t{1});
Void::Testing::expect_eq(exec->stats().queued, std::size_t{1});
// Legacy post() never rejects: it may exceed the bound and is counted.
auto legacy = make_job([&ran] { ran.fetch_add(10); });
exec->post(legacy.handle);
Void::Testing::expect_eq(exec->admitted(), std::size_t{3});
Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1});
// A null handle is invalid for try_post.
const auto null_handle = exec->try_post({});
Void::Testing::expect(!null_handle.has_value());
Void::Testing::expect(null_handle.error() == AdmissionError::invalid_argument);
exec.gate.open();
Void::Testing::expect(wait_until([&] { return ran.load() == 11 && exec->idle(); }));
// A slot is free again once the work returned.
auto again = make_job([&ran] { ran.fetch_add(1000); });
Void::Testing::require(exec->try_post(again.handle).has_value());
Void::Testing::expect(wait_until([&] { return ran.load() == 1011; }));
Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; }));
}
Void::Testing::Test thread_executor_reservation_with_task_scope_preserves_task()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> ran{0};
Fixture exec{1, 1};
TaskScope scope{*exec, TaskScopeOptions{.max_tasks = 8}};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
// The bound is full: TaskScope's reserve-then-transfer is rejected and the
// caller still owns the task.
auto preserved = bump_task(&ran);
const auto rejected = scope.spawn(std::move(preserved));
Void::Testing::require(!rejected.has_value());
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
Void::Testing::expect(!preserved.done());
// The failed reservation did not leak a slot.
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
Void::Testing::expect_eq(ran.load(), 0);
exec.gate.open();
Void::Testing::require(wait_until([&] { return exec->admitted() == 0; }));
const auto accepted = scope.spawn(std::move(preserved));
Void::Testing::require(accepted.has_value());
Void::Testing::require(scope.join_blocking().has_value());
Void::Testing::expect_eq(ran.load(), 1);
Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; }));
}
Void::Testing::Test thread_executor_completion_lane_bypasses_full_normal_lane()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> completion_ran{0};
Fixture exec{1, 1};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
// The normal lane is full ...
auto normal = make_job([] {});
const auto overloaded = exec->try_post(normal.handle);
Void::Testing::expect(!overloaded.has_value());
normal.handle.destroy();
const auto reserve_rejected = exec->try_reserve_slot();
Void::Testing::expect(!reserve_rejected.has_value());
Void::Testing::expect(reserve_rejected.error() == AdmissionError::overloaded);
// ... but the completion lane still accepts and is not part of the bound.
auto completion = make_job([&completion_ran] { completion_ran.fetch_add(1); });
exec->post_completion(completion.handle);
Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{1});
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
exec.gate.open();
Void::Testing::expect(wait_until([&] { return completion_ran.load() == 1; }));
Void::Testing::expect(wait_until([&] { return exec->idle(); }));
}
Void::Testing::Test thread_executor_close_rejects_normal_drains_completion()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> order_counter{0};
std::atomic<int> completion_order{-1};
std::atomic<int> legacy_order{-1};
std::atomic<int> queued_order{-1};
Fixture exec{1, 8};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
auto queued = make_job([&] { queued_order.store(order_counter.fetch_add(1)); });
Void::Testing::require(exec->try_post(queued.handle).has_value());
exec->close();
// Normal admission is closed.
auto refused = make_job([] {});
const auto stopped_post = exec->try_post(refused.handle);
Void::Testing::expect(!stopped_post.has_value());
Void::Testing::expect(stopped_post.error() == AdmissionError::stopped);
refused.handle.destroy();
const auto stopped_reserve = exec->try_reserve_slot();
Void::Testing::expect(!stopped_reserve.has_value());
Void::Testing::expect(stopped_reserve.error() == AdmissionError::stopped);
// A legacy post after close() is redirected to the completion lane and
// counted; post_completion keeps working.
auto legacy = make_job([&] { legacy_order.store(order_counter.fetch_add(1)); });
exec->post(legacy.handle);
auto completion = make_job([&] { completion_order.store(order_counter.fetch_add(1)); });
exec->post_completion(completion.handle);
Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{2});
Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1});
exec.gate.open();
Void::Testing::require(exec->join().has_value());
// Both lanes drained; the completion lane (legacy post, then the explicit
// completion) runs before the queued normal handle.
Void::Testing::expect_eq(legacy_order.load(), 0);
Void::Testing::expect_eq(completion_order.load(), 1);
Void::Testing::expect_eq(queued_order.load(), 2);
Void::Testing::expect(exec->idle());
}
Void::Testing::Test thread_executor_join_self_join_on_worker()
{
std::atomic<int> code{-1};
std::atomic<bool> observed_executor_thread{false};
Fixture exec{1, 4};
auto job = make_job([&] {
const auto joined = exec->join();
code.store(joined.has_value() ? 0 : static_cast<int>(joined.error().code().value));
observed_executor_thread.store(exec->is_executor_thread());
});
Void::Testing::require(exec->try_post(job.handle).has_value());
Void::Testing::require(wait_until([&] { return code.load() != -1; }));
Void::Testing::expect_eq(code.load(), static_cast<int>(AsyncErrorCode::self_join));
Void::Testing::expect(observed_executor_thread.load());
// A normal join from a non-executor thread still works afterwards.
Void::Testing::expect(!exec->is_executor_thread());
Void::Testing::require(exec->join().has_value());
}
Void::Testing::Test thread_executor_partial_start_failure_joins_started()
{
std::atomic<int> hook_calls{0};
std::atomic<bool> fail{true};
std::atomic<int> ran{0};
auto created = ThreadExecutor::create(ThreadExecutorOptions{
.workers = 3,
.max_admitted = 8,
.before_worker_start = [&](std::size_t index) -> Void::Result::Result<void> {
hook_calls.fetch_add(1);
if (fail.load() && index == 2) {
return std::unexpected{make_async_error(
AsyncErrorCode::limit_exceeded, "injected thread start failure")};
}
return {};
}});
Void::Testing::require(created.has_value());
auto& exec = **created;
// Work admitted before start() must not run on workers of a failed start.
auto job = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(job.handle).has_value());
const auto failed = exec.start();
Void::Testing::require(!failed.has_value());
Void::Testing::expect(async_code(failed.error()) == AsyncErrorCode::limit_exceeded);
Void::Testing::expect_eq(hook_calls.load(), 3);
std::this_thread::sleep_for(30ms);
Void::Testing::expect_eq(ran.load(), 0);
Void::Testing::expect_eq(exec.stats().queued, std::size_t{1});
Void::Testing::expect_eq(exec.stats().running, std::size_t{0});
// The two workers that were already started were joined: a retry starts a
// full set again.
fail.store(false);
Void::Testing::require(exec.start().has_value());
Void::Testing::expect_eq(hook_calls.load(), 6);
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
Void::Testing::require(exec.join().has_value());
}
Void::Testing::Test thread_executor_system_error_path_shared_with_hook()
{
std::atomic<int> mode{0}; // 0 = ok, 1 = system_error, 2 = runtime_error
std::atomic<int> hook_calls{0};
std::atomic<int> ran{0};
auto created = ThreadExecutor::create(ThreadExecutorOptions{
.workers = 3,
.max_admitted = 8,
.before_worker_start = [&](std::size_t index) -> Void::Result::Result<void> {
hook_calls.fetch_add(1);
if (index == 1 && mode.load() == 1) {
throw std::system_error{std::make_error_code(std::errc::resource_unavailable_try_again),
"injected thread creation failure"};
}
if (index == 1 && mode.load() == 2) {
throw std::runtime_error{"injected hook failure"};
}
return {};
}});
Void::Testing::require(created.has_value());
auto& exec = **created;
auto job = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(job.handle).has_value());
// std::system_error: same cleanup path as a hook error, system code kept.
mode.store(1);
const auto sys_failed = exec.start();
Void::Testing::require(!sys_failed.has_value());
Void::Testing::expect(async_code(sys_failed.error()) == AsyncErrorCode::backend_error);
Void::Testing::expect(sys_failed.error().system_code() ==
std::make_error_code(std::errc::resource_unavailable_try_again));
Void::Testing::expect_eq(hook_calls.load(), 2);
// Any other exception takes the same path, without a system code.
mode.store(2);
const auto other_failed = exec.start();
Void::Testing::require(!other_failed.has_value());
Void::Testing::expect(async_code(other_failed.error()) == AsyncErrorCode::backend_error);
Void::Testing::expect(!other_failed.error().system_code());
Void::Testing::expect_eq(hook_calls.load(), 4);
Void::Testing::expect_eq(ran.load(), 0);
mode.store(0);
Void::Testing::require(exec.start().has_value());
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
Void::Testing::require(exec.join().has_value());
}
namespace
{
Void::Coro::Task<void> hop_task(ThreadExecutor* exec,
std::atomic<int>* stage,
std::atomic<bool>* on_executor_before,
std::atomic<bool>* on_executor_after,
std::atomic<int>* status_code)
{
on_executor_before->store(exec->is_executor_thread());
stage->store(1);
co_await schedule_on(*exec);
stage->store(2);
const auto status = co_await schedule_on(*exec, OperationOptions{});
status_code->store(status.has_value() ? 0 : static_cast<int>(status.error().code().value));
on_executor_after->store(exec->is_executor_thread());
stage->store(3);
}
} // namespace
Void::Testing::Test thread_executor_legacy_post_spawn_schedule_on_compat()
{
std::atomic<int> stage{0};
std::atomic<bool> before{false};
std::atomic<bool> after{false};
std::atomic<int> status_code{-1};
std::atomic<bool> blocker_running{false};
std::atomic<int> ran{0};
Fixture exec{1, 2};
// spawn() and schedule_on(executor) use the legacy post(): never rejected.
// spawn() is called from the single worker itself, not from a foreign
// thread: ThreadSanitizer reports a data race in Executor.hpp's spawn_impl
// (lines 292/296) when spawn() is called from a thread other than the
// executor's workers onto a multi-worker executor. That behaviour is
// independent of ThreadExecutor and is escalated to the root; it is not
// covered here.
auto spawner = make_job([&] {
spawn(*exec, hop_task(exec.exec.get(), &stage, &before, &after, &status_code));
});
Void::Testing::require(exec->try_post(spawner.handle).has_value());
Void::Testing::require(wait_until([&] { return stage.load() == 3; }));
Void::Testing::expect(before.load());
Void::Testing::expect(after.load());
Void::Testing::expect_eq(status_code.load(), 0);
Void::Testing::expect(exec->stats().legacy_posts >= 2);
// A full bound (running + queued == 2) rejects try_post (and the status
// schedule_on built on it) but never the legacy post.
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
auto filler = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec->try_post(filler.handle).has_value());
auto rejected = make_job([] {});
Void::Testing::expect(!exec->try_post(rejected.handle).has_value());
rejected.handle.destroy();
const std::uint64_t legacy_before = exec->stats().legacy_posts;
auto j1 = make_job([&ran] { ran.fetch_add(1); });
auto j2 = make_job([&ran] { ran.fetch_add(1); });
exec->post(j1.handle);
exec->post(j2.handle);
Void::Testing::expect_eq(exec->stats().legacy_posts, legacy_before + 2);
Void::Testing::expect_eq(exec->admitted(), std::size_t{4});
exec.gate.open();
Void::Testing::expect(wait_until([&] { return ran.load() == 3; }));
Void::Testing::require(exec->join().has_value());
}
Void::Testing::Test thread_executor_inline_after_join_counted()
{
std::atomic<int> ran{0};
std::mutex mu;
std::vector<std::thread::id> threads;
std::atomic<bool> guarded{false};
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
auto before_join = make_job([&] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(before_join.handle).has_value());
Void::Testing::require(exec.join().has_value());
Void::Testing::expect_eq(ran.load(), 1);
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{0});
// After join, posts resume inline on the caller (counted), never dropped.
const auto caller = std::this_thread::get_id();
auto record = [&] {
std::lock_guard lk{mu};
threads.push_back(std::this_thread::get_id());
guarded.store(exec.is_executor_thread());
};
auto j1 = make_job(record);
exec.post(j1.handle);
auto j2 = make_job(record);
exec.post_completion(j2.handle);
Void::Testing::expect_eq(threads.size(), std::size_t{2});
Void::Testing::expect(threads[0] == caller);
Void::Testing::expect(threads[1] == caller);
// The inline resume runs under ExecutorThreadGuard.
Void::Testing::expect(guarded.load());
Void::Testing::expect(!exec.is_executor_thread());
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{2});
Void::Testing::expect_eq(exec.stats().legacy_posts, std::uint64_t{1});
// Normal admission stays closed after join, and join/start are repeatable
// or rejected.
auto refused = make_job([] {});
const auto stopped = exec.try_post(refused.handle);
Void::Testing::expect(!stopped.has_value());
Void::Testing::expect(stopped.error() == AdmissionError::stopped);
refused.handle.destroy();
const auto reserved = exec.try_reserve_slot();
Void::Testing::expect(!reserved.has_value());
Void::Testing::expect(reserved.error() == AdmissionError::stopped);
Void::Testing::require(exec.join().has_value());
const auto restarted = exec.start();
Void::Testing::expect(!restarted.has_value());
Void::Testing::expect(exec.idle());
}
Void::Testing::Test thread_executor_join_without_start_drains_inline()
{
std::mutex mu;
std::vector<int> order;
std::atomic<bool> all_on_caller{true};
const auto caller = std::this_thread::get_id();
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 8});
Void::Testing::require(created.has_value());
auto& exec = **created;
auto make_marker = [&](int id) {
return make_job([&, id] {
std::lock_guard lk{mu};
order.push_back(id);
if (std::this_thread::get_id() != caller) {
all_on_caller.store(false);
}
});
};
auto n1 = make_marker(1);
auto n2 = make_marker(2);
auto c1 = make_marker(10);
auto n3 = make_marker(3);
Void::Testing::require(exec.try_post(n1.handle).has_value());
Void::Testing::require(exec.try_post(n2.handle).has_value());
exec.post_completion(c1.handle);
exec.post(n3.handle);
Void::Testing::expect_eq(exec.admitted(), std::size_t{3});
// No worker exists: join() drains both lanes inline, never waits.
Void::Testing::require(exec.join().has_value());
Void::Testing::expect(all_on_caller.load());
// Completion lane first, then the normal lane in FIFO order.
Void::Testing::expect_eq(order.size(), std::size_t{4});
if (order.size() == 4) {
Void::Testing::expect_eq(order[0], 10);
Void::Testing::expect_eq(order[1], 1);
Void::Testing::expect_eq(order[2], 2);
Void::Testing::expect_eq(order[3], 3);
}
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{4});
Void::Testing::expect(exec.idle());
Void::Testing::expect(!exec.start().has_value());
// The destructor of a never-started executor also drains inline.
std::atomic<int> ran{0};
{
auto second = ThreadExecutor::create();
Void::Testing::require(second.has_value());
auto pending = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require((*second)->try_post(pending.handle).has_value());
}
Void::Testing::expect_eq(ran.load(), 1);
}
Void::Testing::Test thread_executor_start_twice_and_after_close_invalid()
{
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
const auto twice = exec.start();
Void::Testing::require(!twice.has_value());
Void::Testing::expect(async_code(twice.error()) == AsyncErrorCode::invalid_argument);
auto closed_created = ThreadExecutor::create();
Void::Testing::require(closed_created.has_value());
auto& closed = **closed_created;
closed.close();
const auto after_close = closed.start();
Void::Testing::require(!after_close.has_value());
Void::Testing::expect(async_code(after_close.error()) == AsyncErrorCode::invalid_argument);
Void::Testing::require(exec.join().has_value());
const auto after_join = exec.start();
Void::Testing::require(!after_join.has_value());
Void::Testing::expect(async_code(after_join.error()) == AsyncErrorCode::invalid_argument);
}
Void::Testing::Test thread_executor_reservation_across_close_binding()
{
std::atomic<int> ran{0};
std::atomic<bool> joined{false};
std::atomic<bool> join_ok{false};
std::atomic<bool> job_on_joiner{false};
// (1) Workers running: a reservation taken before close() stays binding.
{
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
Void::Testing::require(exec.try_reserve_slot().has_value());
// A reserved slot counts in admitted() and in the bound.
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
Void::Testing::require(exec.try_reserve_slot().has_value());
const auto full = exec.try_reserve_slot();
Void::Testing::expect(!full.has_value());
Void::Testing::expect(full.error() == AdmissionError::overloaded);
exec.release_reserved();
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
exec.close();
const auto after_close = exec.try_reserve_slot();
Void::Testing::expect(!after_close.has_value());
Void::Testing::expect(after_close.error() == AdmissionError::stopped);
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
std::thread joiner([&] {
join_ok.store(exec.join().has_value());
joined.store(true);
});
// join() also waits until no reservation is outstanding.
std::this_thread::sleep_for(60ms);
Void::Testing::expect(!joined.load());
auto job = make_job([&ran] { ran.fetch_add(1); });
exec.commit_reserved(job.handle); // binding: enqueues normally after close()
joiner.join();
Void::Testing::expect(joined.load());
Void::Testing::expect(join_ok.load());
Void::Testing::expect_eq(ran.load(), 1);
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
}
// (2) A released reservation also lets join() finish (no workers: the
// joiner drains inline, but still waits for the reservation).
{
joined.store(false);
join_ok.store(false);
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.try_reserve_slot().has_value());
std::thread joiner([&] {
join_ok.store(exec.join().has_value());
joined.store(true);
});
std::this_thread::sleep_for(60ms);
Void::Testing::expect(!joined.load());
exec.release_reserved();
joiner.join();
Void::Testing::expect(joined.load());
Void::Testing::expect(join_ok.load());
}
// (3) No workers + a commit after join() began: the committed handle is
// drained by the joining thread.
{
joined.store(false);
join_ok.store(false);
const auto joiner_id = std::make_shared<std::atomic<std::thread::id>>();
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.try_reserve_slot().has_value());
std::thread joiner([&] {
joiner_id->store(std::this_thread::get_id());
join_ok.store(exec.join().has_value());
joined.store(true);
});
std::this_thread::sleep_for(60ms);
auto job = make_job([&] {
job_on_joiner.store(std::this_thread::get_id() == joiner_id->load());
ran.fetch_add(1);
});
exec.commit_reserved(job.handle);
joiner.join();
Void::Testing::expect(join_ok.load());
Void::Testing::expect(job_on_joiner.load());
Void::Testing::expect_eq(ran.load(), 2);
}
}
Void::Testing::Test thread_executor_stress_tsan()
{
constexpr int kPosters = 4;
constexpr int kPerPoster = 1200;
std::atomic<std::uint64_t> accepted{0};
std::atomic<std::uint64_t> executed{0};
std::atomic<std::uint64_t> posted_failed_unexpectedly{0};
std::atomic<std::uint64_t> snapshot_inconsistent{0};
std::vector<std::thread> posters;
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 3, .max_admitted = 32});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
for (int p = 0; p < kPosters; ++p) {
posters.emplace_back([&, p] {
for (int k = 0; k < kPerPoster; ++k) {
const int kind = (p + k) % 4;
auto job = make_job([&executed] { executed.fetch_add(1, std::memory_order_relaxed); });
if (post_one(exec, kind, job)) {
accepted.fetch_add(1, std::memory_order_relaxed);
} else {
posted_failed_unexpectedly.fetch_add(1);
}
if ((k & 63) == 0) {
const auto stats = exec.stats();
if (stats.running > 3) {
snapshot_inconsistent.fetch_add(1);
}
(void)exec.idle();
}
}
});
}
for (auto& poster : posters) {
poster.join();
}
// Repeated and concurrent join(): every caller returns success and the
// worker threads are joined exactly once.
std::atomic<int> concurrent_join_failures{0};
std::vector<std::thread> joiners;
for (int j = 0; j < 3; ++j) {
joiners.emplace_back([&] {
if (!exec.join().has_value()) {
concurrent_join_failures.fetch_add(1);
}
});
}
const bool main_join_ok = exec.join().has_value();
for (auto& joiner : joiners) {
joiner.join();
}
Void::Testing::require(main_join_ok);
Void::Testing::expect_eq(concurrent_join_failures.load(), 0);
Void::Testing::expect_eq(posted_failed_unexpectedly.load(), std::uint64_t{0});
Void::Testing::expect_eq(snapshot_inconsistent.load(), std::uint64_t{0});
Void::Testing::expect_eq(accepted.load(), static_cast<std::uint64_t>(kPosters) * kPerPoster);
Void::Testing::expect_eq(executed.load(), accepted.load());
Void::Testing::expect(exec.idle());
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
}
// Regression (W11): spawn() from a foreign thread onto a multi-worker executor
// must not race with the worker that resumes and destroys the detached frame.
namespace
{
Void::Coro::Task<void> spawn_bump(std::atomic<int>* counter)
{
counter->fetch_add(1, std::memory_order_relaxed);
co_return;
}
} // namespace
Void::Testing::Test thread_executor_spawn_from_foreign_thread_multi_worker_tsan()
{
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 4, .max_admitted = 64});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
constexpr int kSpawns = 2000;
std::atomic<int> counter{0};
for (int i = 0; i < kSpawns; ++i) {
spawn(exec, spawn_bump(&counter));
}
Void::Testing::require(exec.join().has_value());
Void::Testing::expect_eq(counter.load(std::memory_order_relaxed), kSpawns);
}
File diff suppressed because it is too large. Load diff
+293
View File
@@ -0,0 +1,293 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/Pump.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <array>
#include <chrono>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <stop_token>
namespace
{
using namespace std::chrono_literals;
using Void::Async::ManualExecutor;
using Void::Async::OperationOptions;
using Void::Async::TaskScope;
using Void::Async::TimerEvent;
using Void::Async::TimerQueue;
using Void::Async::TimerQueueOptions;
using Void::IO::BackendOptions;
using Void::IO::BackendPreference;
using Void::IO::ByteStream;
using Void::IO::Driver;
using Void::IO::IoErrorCode;
using Void::IO::PumpOptions;
using Void::IO::Transfer;
using Void::IO::pump_until;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
} // namespace
Void::Testing::Test io_pump_until_scope_join_mock()
{
ManualExecutor exec;
Void::Time::ManualClock clock;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
auto* ctrl = drv.mock_controller();
require(ctrl != nullptr);
auto s_res = drv.create_mock_stream();
require(s_res.has_value());
ByteStream stream = std::move(*s_res);
std::array<std::byte, 8> buf{};
std::optional<Void::Result::Result<Transfer>> read_res;
TaskScope scope{exec};
auto rtask = [](ByteStream* st,
std::span<std::byte> sp,
std::optional<Void::Result::Result<Transfer>>* out)
-> Void::Coro::Task<void> { *out = co_await st->read_some(sp); };
require(scope.spawn(rtask(&stream, buf, &read_res)).has_value());
(void)exec.drain();
const std::array<std::byte, 3> payload{
std::byte{'o'}, std::byte{'k'}, std::byte{'!'}};
expect(ctrl->complete_read(stream, payload));
auto work = pump_until(drv, exec, [&] { return scope.active_count() == 0; });
require(work.has_value());
expect(*work >= std::size_t{1});
require(read_res.has_value() && read_res->has_value());
expect_eq((*read_res)->bytes, std::size_t{3});
}
Void::Testing::Test io_pump_until_deadline_injected_clock()
{
ManualExecutor exec;
Void::Time::ManualClock clock{
Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}};
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
// 1. Pre-expired deadline returns timeout with zero poll turns.
auto r0 = pump_until(
drv,
exec,
[] { return false; },
PumpOptions{.operation = OperationOptions{.deadline = clock.now()}});
require(!r0.has_value());
expect_eq(r0.error().code().value,
static_cast<std::int32_t>(IoErrorCode::timeout));
expect_eq(drv.telemetry().turns, std::uint64_t{0});
// 2. Bounded turns advancing injected ManualClock expire cleanly on turn 3.
const auto dl = clock.now() + 30ms;
int checks = 0;
auto r1 = pump_until(
drv,
exec,
[&]() {
if (++checks >= 2) {
(void)clock.advance(10ms);
}
return false;
},
PumpOptions{
.max_wait = 5ms,
.max_turns = 20,
.operation = OperationOptions{.deadline = dl},
});
require(!r1.has_value());
expect_eq(r1.error().code().value,
static_cast<std::int32_t>(IoErrorCode::timeout));
expect(drv.telemetry().turns > std::uint64_t{0});
expect(drv.telemetry().turns <= std::uint64_t{5});
}
Void::Testing::Test io_pump_until_max_turns_exhausted()
{
ManualExecutor exec;
Void::Time::ManualClock clock;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
auto res = pump_until(
drv,
exec,
[] { return false; },
PumpOptions{.max_wait = 0ns, .max_turns = 5});
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(IoErrorCode::exhausted));
expect_eq(drv.telemetry().turns, std::uint64_t{5});
}
Void::Testing::Test io_pump_until_drives_timer_queue()
{
ManualExecutor exec;
Void::Time::ManualClock clock;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
auto tq_res = TimerQueue::create(exec, clock, TimerQueueOptions{});
require(tq_res.has_value());
auto& timers = **tq_res;
bool fired = false;
TimerEvent seen = TimerEvent::closed;
auto h = timers.schedule_at(clock.now() + 10ms, [&](TimerEvent ev) noexcept {
seen = ev;
fired = true;
});
require(h.has_value());
// Advance ManualClock from an executor coroutine on turn 1 so poll_expired fires on turn 2.
TaskScope scope{exec};
auto adv_task = [](Void::Time::ManualClock* c) -> Void::Coro::Task<void> {
(void)c->advance(10ms);
co_return;
};
require(scope.spawn(adv_task(&clock)).has_value());
auto res = pump_until(
drv,
exec,
[&]() { return fired; },
PumpOptions{.max_wait = 50ms, .max_turns = 16, .timers = &timers});
require(res.has_value());
expect(fired);
expect(seen == TimerEvent::expired);
require(scope.join_pumping(exec).has_value());
}
Void::Testing::Test io_pump_until_stop_cancelled()
{
ManualExecutor exec;
Void::Time::ManualClock clock;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
std::stop_source stop_src;
TaskScope scope{exec};
auto req_task = [](std::stop_source* src) -> Void::Coro::Task<void> {
src->request_stop();
co_return;
};
require(scope.spawn(req_task(&stop_src)).has_value());
auto res = pump_until(
drv,
exec,
[] { return false; },
PumpOptions{
.max_turns = 16,
.operation = OperationOptions{.stop = stop_src.get_token()},
});
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(IoErrorCode::cancelled));
require(scope.join_pumping(exec).has_value());
}
Void::Testing::Test io_pump_until_exits_after_shutdown_complete()
{
// 1. Pre-shut-down Driver exits pump_until immediately with 0 poll turns.
{
ManualExecutor exec;
Void::Time::ManualClock clock;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
auto rep = drv.shutdown(OperationOptions{});
require(rep.has_value());
expect(rep->complete);
expect(drv.shutdown_complete());
auto res = pump_until(
drv,
exec,
[] { return false; },
PumpOptions{.max_turns = 10});
require(res.has_value());
expect_eq(drv.telemetry().turns, std::uint64_t{0});
}
// 2. Coroutine calling Driver::shutdown during pump_until causes prompt exit.
{
ManualExecutor exec;
Void::Time::ManualClock clock;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
TaskScope scope{exec};
auto sd_task = [](Driver* d) -> Void::Coro::Task<void> {
(void)d->shutdown(OperationOptions{});
co_return;
};
require(scope.spawn(sd_task(&drv)).has_value());
auto res = pump_until(
drv,
exec,
[] { return false; },
PumpOptions{.max_turns = 10});
require(res.has_value());
expect(drv.shutdown_complete());
expect_eq(drv.telemetry().turns, std::uint64_t{1});
require(scope.join_pumping(exec).has_value());
}
}
Void::Testing::Test io_pump_until_mock_max_wait_paces_idle_turns()
{
ManualExecutor exec;
const auto& clock = Void::Time::SystemMonotonicClock::instance();
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock}, clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
auto res = pump_until(
drv,
exec,
[] { return false; },
PumpOptions{
.max_wait = 5ms,
.max_turns = 200,
.operation = OperationOptions{.deadline = clock.now() + 20ms},
});
require(!res.has_value());
expect_eq(res.error().code().value,
static_cast<std::int32_t>(IoErrorCode::timeout));
expect(drv.telemetry().turns < std::uint64_t{100});
}
+736
View File
@@ -0,0 +1,736 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/File.hpp>
#include <Void/IO/Stream.hpp>
#include <Void/IO/Types.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
#include <fcntl.h>
#include <unistd.h>
namespace
{
using namespace std::chrono_literals;
using Void::Async::ManualExecutor;
using Void::Async::OperationOptions;
using Void::Async::TaskScope;
using Void::IO::BackendOptions;
using Void::IO::BackendPreference;
using Void::IO::BufferLease;
using Void::IO::ByteStream;
using Void::IO::Driver;
using Void::IO::DriverShutdownReport;
using Void::IO::File;
using Void::IO::FileOpenOptions;
using Void::IO::FileSyscallResult;
using Void::IO::FileSyscalls;
using Void::IO::IoErrorCode;
using Void::IO::IoLimits;
using Void::IO::Transfer;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
class ScopedTempDir
{
public:
ScopedTempDir()
{
auto tmpl = (std::filesystem::temp_directory_path() / "void_w11_io4_XXXXXX")
.string();
std::vector<char> buf(tmpl.begin(), tmpl.end());
buf.push_back('\0');
char* created = ::mkdtemp(buf.data());
if (created != nullptr) {
path_ = created;
}
}
~ScopedTempDir()
{
if (!path_.empty()) {
std::error_code ec;
std::filesystem::remove_all(path_, ec);
}
}
ScopedTempDir(const ScopedTempDir&) = delete;
ScopedTempDir& operator=(const ScopedTempDir&) = delete;
[[nodiscard]] bool valid() const noexcept { return !path_.empty(); }
[[nodiscard]] std::filesystem::path file(std::string_view name) const
{
return path_ / name;
}
private:
std::filesystem::path path_{};
};
class Gate
{
public:
void wait()
{
std::unique_lock lk{mu_};
++waiting_;
cv_.notify_all();
cv_.wait(lk, [this] { return open_; });
}
[[nodiscard]] bool wait_for_waiters(
int n, std::chrono::milliseconds timeout = 5000ms)
{
std::unique_lock lk{mu_};
return cv_.wait_for(lk, timeout, [&] { return waiting_ >= n; });
}
void open()
{
std::lock_guard lk{mu_};
open_ = true;
cv_.notify_all();
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
int waiting_{0};
};
class GatedFileSyscalls final : public FileSyscalls
{
public:
Gate gate{};
std::atomic<bool> block_pread{true};
std::atomic<int> preads{0};
std::atomic<int> closes{0};
FileSyscallResult pread(int fd, std::span<std::byte> buf,
std::uint64_t offset) noexcept override
{
preads.fetch_add(1, std::memory_order_relaxed);
if (block_pread.load(std::memory_order_acquire)) {
gate.wait();
}
return FileSyscalls::pread(fd, buf, offset);
}
FileSyscallResult close(int fd) noexcept override
{
closes.fetch_add(1, std::memory_order_relaxed);
return FileSyscalls::close(fd);
}
};
} // namespace
Void::Testing::Test io_shutdown_expired_budget_incomplete_retains_stalled_file_worker()
{
ScopedTempDir dir;
require(dir.valid());
const auto path = dir.file("stalled.dat");
{
std::ofstream ofs(path, std::ios::binary);
ofs << "hello_stalled_worker";
}
GatedFileSyscalls sys;
ManualExecutor exec;
Void::Time::ManualClock clock{
Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}};
auto drv_res = Driver::create(
exec,
BackendOptions{
.limits = IoLimits{.file_workers = 1, .max_file_queue = 8},
.preference = BackendPreference::epoll,
.file_syscalls = &sys,
},
clock);
require(drv_res.has_value());
Driver& drv = **drv_res;
require(drv.start_file_workers().has_value());
auto f_res = drv.open_file(path, FileOpenOptions{});
require(f_res.has_value());
File file = std::move(*f_res);
std::array<std::byte, 16> buf{};
std::optional<Void::Result::Result<Transfer>> read_res;
int deliveries = 0;
TaskScope scope{exec};
auto read_task = [](File* f,
std::span<std::byte> b,
std::optional<Void::Result::Result<Transfer>>* out,
int* count) -> Void::Coro::Task<void> {
*out = co_await f->read_at(0, b);
++(*count);
};
require(scope.spawn(read_task(&file, buf, &read_res, &deliveries)).has_value());
(void)exec.drain();
require(sys.gate.wait_for_waiters(1));
expect_eq(drv.telemetry().active_file_requests, std::size_t{1});
// Expired budget on shutdown leaves worker stalled, fd open, and complete=false.
auto r1 = drv.shutdown(OperationOptions{.deadline = clock.now()});
require(r1.has_value());
expect(!r1->complete);
expect_eq(r1->active_file_requests, std::size_t{1});
expect(r1->open_descriptors >= std::size_t{1});
expect(!drv.shutdown_complete());
expect_eq(sys.closes.load(), 0);
expect_eq(deliveries, 0);
// Unblock worker and finish shutdown.
sys.gate.open();
auto r2 = drv.shutdown(
OperationOptions{.deadline = Void::Time::deadline_after(clock, 5s)});
require(r2.has_value());
expect(r2->complete);
expect(drv.shutdown_complete());
expect_eq(r2->active_file_requests, std::size_t{0});
expect_eq(r2->open_descriptors, std::size_t{0});
(void)scope.join_pumping(exec);
expect_eq(deliveries, 1);
require(read_res.has_value() && read_res->has_value());
expect_eq((*read_res)->bytes, std::size_t{16});
expect_eq(sys.closes.load(), 1);
}
Void::Testing::Test io_shutdown_pending_socket_read_retains_buffer_until_delivery()
{
// 1. In-flight mock stream read retains borrowed buffer and op across shutdown
// until explicitly delivered once by controller.
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock});
require(drv_res.has_value());
Driver& drv = **drv_res;
auto* ctrl = drv.mock_controller();
require(ctrl != nullptr);
auto s_res = drv.create_mock_stream();
require(s_res.has_value());
ByteStream stream = std::move(*s_res);
std::array<std::byte, 32> buf{};
std::optional<Void::Result::Result<Transfer>> res;
int deliveries = 0;
TaskScope scope{exec};
auto read_task = [](ByteStream* s,
std::span<std::byte> sp,
std::optional<Void::Result::Result<Transfer>>* out,
int* count) -> Void::Coro::Task<void> {
*out = co_await s->read_some(sp);
++(*count);
};
require(scope.spawn(read_task(&stream, buf, &res, &deliveries)).has_value());
(void)exec.drain();
const auto tok = ctrl->try_acquire_read(stream);
require(tok.has_value());
expect_eq(drv.telemetry().borrowed_buffer_bytes, std::size_t{32});
auto r1 = drv.shutdown(OperationOptions{});
require(r1.has_value());
expect(r1->complete);
expect_eq(r1->pending_operations, std::size_t{1});
expect_eq(r1->retained_buffer_bytes, std::size_t{32});
expect_eq(drv.telemetry().borrowed_buffer_bytes, std::size_t{32});
expect_eq(deliveries, 0);
const std::array<std::byte, 4> payload{
std::byte{'d'}, std::byte{'a'}, std::byte{'t'}, std::byte{'a'}};
expect(ctrl->finish_read_data(*tok, payload, false));
(void)scope.join_pumping(exec);
expect_eq(deliveries, 1);
require(res.has_value() && res->has_value());
expect_eq((*res)->bytes, std::size_t{4});
expect_eq(drv.telemetry().borrowed_buffer_bytes, std::size_t{0});
}
// 2. Epoll socketpair read_some_owned retains owned BufferLease across shutdown
// until executor delivers the closed completion once and drops the lease.
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::epoll});
require(drv_res.has_value());
Driver& drv = **drv_res;
auto pair_res = drv.create_socket_pair();
require(pair_res.has_value());
ByteStream a = std::move(pair_res->first);
ByteStream b = std::move(pair_res->second);
auto lease_res = drv.allocate_buffer(64);
require(lease_res.has_value());
std::optional<Void::Result::Result<Transfer>> res;
int deliveries = 0;
TaskScope scope{exec};
auto sock_task = [](ByteStream* s,
BufferLease lease,
std::optional<Void::Result::Result<Transfer>>* out,
int* count) -> Void::Coro::Task<void> {
*out = co_await s->read_some_owned(lease);
++(*count);
lease.reset();
};
require(scope
.spawn(sock_task(&a, std::move(*lease_res), &res, &deliveries))
.has_value());
(void)exec.drain();
expect_eq(drv.telemetry().active_operations, std::size_t{1});
expect_eq(drv.telemetry().borrowed_buffer_bytes, std::size_t{64});
expect_eq(drv.telemetry().owned_buffer_bytes, std::size_t{64});
auto r2 = drv.shutdown(OperationOptions{});
require(r2.has_value());
expect(r2->complete);
expect(drv.shutdown_complete());
expect_eq(r2->open_descriptors, std::size_t{0});
expect_eq(drv.telemetry().borrowed_buffer_bytes, std::size_t{0});
expect_eq(drv.telemetry().owned_buffer_bytes, std::size_t{64});
expect_eq(deliveries, 0);
(void)scope.join_pumping(exec);
expect_eq(deliveries, 1);
require(res.has_value());
expect(!res->has_value());
expect_eq(res->error().code().value,
static_cast<std::int32_t>(IoErrorCode::closed));
expect_eq(drv.telemetry().owned_buffer_bytes, std::size_t{0});
(void)b;
}
}
Void::Testing::Test io_shutdown_repeated_idempotent_after_complete()
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::epoll});
require(drv_res.has_value());
Driver& drv = **drv_res;
for (int i = 0; i < 3; ++i) {
auto r = drv.shutdown(OperationOptions{});
require(r.has_value());
expect(r->complete);
expect(drv.shutdown_complete());
expect_eq(r->pending_operations, std::size_t{0});
expect_eq(r->open_descriptors, std::size_t{0});
}
}
Void::Testing::Test io_shutdown_concurrent_with_run_loop_tsan()
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::epoll});
require(drv_res.has_value());
Driver& drv = **drv_res;
auto pair_res = drv.create_socket_pair();
require(pair_res.has_value());
ByteStream a = std::move(pair_res->first);
ByteStream b = std::move(pair_res->second);
std::stop_source stop_src;
std::optional<Void::Result::Result<std::size_t>> run_res;
std::thread runner([&]() {
run_res = drv.run(stop_src.get_token(), 2ms);
});
std::array<std::byte, 8> rbuf{};
std::optional<Void::Result::Result<Transfer>> read_res;
TaskScope scope{exec};
auto rtask = [](ByteStream* s,
std::span<std::byte> sp,
std::optional<Void::Result::Result<Transfer>>* out)
-> Void::Coro::Task<void> {
*out = co_await s->read_some(sp);
};
require(scope.spawn(rtask(&a, rbuf, &read_res)).has_value());
(void)exec.drain();
// Concurrently shut down driver while runner thread executes run() loop.
std::this_thread::sleep_for(5ms);
auto rep = drv.shutdown(OperationOptions{});
require(rep.has_value());
expect(rep->complete);
runner.join();
require(run_res.has_value() && run_res->has_value());
expect(drv.shutdown_complete());
(void)scope.join_pumping(exec);
require(read_res.has_value());
(void)b;
}
Void::Testing::Test io_run_stops_on_token_and_on_shutdown()
{
// 1. Stops promptly on std::stop_source request.
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::epoll});
require(drv_res.has_value());
Driver& drv = **drv_res;
std::stop_source stop_src;
Void::Result::Result<std::size_t> res{std::size_t{0}};
std::thread t([&]() { res = drv.run(stop_src.get_token(), 50ms); });
std::this_thread::sleep_for(5ms);
const auto t0 = std::chrono::steady_clock::now();
stop_src.request_stop();
drv.wake();
t.join();
const auto elapsed = std::chrono::steady_clock::now() - t0;
require(res.has_value());
expect(elapsed < 40ms);
expect(!drv.shutdown_complete());
require(drv.shutdown(OperationOptions{}).has_value());
}
// 2. Exits when shutdown_complete() becomes true even with unstoppable token.
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock});
require(drv_res.has_value());
Driver& drv = **drv_res;
Void::Result::Result<std::size_t> res{std::size_t{0}};
std::thread t([&]() { res = drv.run(std::stop_token{}, 2ms); });
std::this_thread::sleep_for(5ms);
auto rep = drv.shutdown(OperationOptions{});
require(rep.has_value());
expect(rep->complete);
t.join();
require(res.has_value());
expect(drv.shutdown_complete());
}
}
Void::Testing::Test io_begin_shutdown_rejects_new_admission()
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock});
require(drv_res.has_value());
Driver& drv = **drv_res;
drv.begin_shutdown();
auto sock = drv.create_mock_stream();
expect(!sock.has_value());
expect_eq(sock.error().code().value,
static_cast<std::int32_t>(IoErrorCode::closed));
auto f = drv.open_file("nonexistent_after_shutdown.bin");
expect(!f.has_value());
expect_eq(f.error().code().value,
static_cast<std::int32_t>(IoErrorCode::closed));
auto sw = drv.start_file_workers();
expect(!sw.has_value());
expect_eq(sw.error().code().value,
static_cast<std::int32_t>(IoErrorCode::closed));
auto rep = drv.shutdown(OperationOptions{});
require(rep.has_value());
expect(rep->complete);
expect(drv.quiescent());
}
Void::Testing::Test io_run_busy_and_mock_wait_does_not_spin()
{
// 1. Mock driver with 5ms max_wait does not spin over ~30ms.
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock});
require(drv_res.has_value());
Driver& drv = **drv_res;
std::stop_source stop;
Void::Result::Result<std::size_t> res{std::size_t{0}};
std::thread t([&]() { res = drv.run(stop.get_token(), 5ms); });
std::this_thread::sleep_for(30ms);
stop.request_stop();
t.join();
require(res.has_value());
expect(drv.telemetry().turns < 40);
}
// 2. Epoll busy retry waits stop-aware without returning busy or spinning.
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::epoll});
require(drv_res.has_value());
Driver& drv = **drv_res;
std::atomic<bool> holder_started{false};
std::thread holder([&]() {
holder_started.store(true, std::memory_order_release);
(void)drv.poll_once(25ms);
});
while (!holder_started.load(std::memory_order_acquire)) {
std::this_thread::yield();
}
std::this_thread::sleep_for(2ms);
std::stop_source stop;
Void::Result::Result<std::size_t> res{std::size_t{0}};
std::thread runner([&]() { res = drv.run(stop.get_token(), 2ms); });
std::this_thread::sleep_for(15ms);
stop.request_stop();
holder.join();
runner.join();
require(res.has_value());
expect(drv.telemetry().turns < 50);
}
}
Void::Testing::Test io_shutdown_epoll_idle_readable_fd_no_busy_spin()
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::epoll});
require(drv_res.has_value());
Driver& drv = **drv_res;
auto pair_res = drv.create_socket_pair();
require(pair_res.has_value());
ByteStream a = std::move(pair_res->first);
ByteStream b = std::move(pair_res->second);
// Push unread data into stream `a` while NO read operation is pending on `a`.
TaskScope scope{exec};
const std::array<std::byte, 4> msg{
std::byte{'p'}, std::byte{'i'}, std::byte{'n'}, std::byte{'g'}};
std::optional<Void::Result::Result<Transfer>> wres;
auto wtask = [](ByteStream* st,
std::span<const std::byte> sp,
std::optional<Void::Result::Result<Transfer>>* out)
-> Void::Coro::Task<void> { *out = co_await st->write_some(sp); };
require(scope.spawn(wtask(&b, msg, &wres)).has_value());
(void)exec.drain();
while (!wres.has_value()) {
(void)drv.poll_once(1ms);
(void)exec.drain();
}
require(wres->has_value());
expect_eq((*wres)->bytes, std::size_t{4});
// Running driver with unread data on `a` and no active reader must NOT busy-spin.
std::stop_source stop;
Void::Result::Result<std::size_t> run_res{std::size_t{0}};
std::thread runner([&]() { run_res = drv.run(stop.get_token(), 10ms); });
std::this_thread::sleep_for(40ms);
stop.request_stop();
runner.join();
require(run_res.has_value());
expect(drv.telemetry().turns <= std::uint64_t{15});
auto rep = drv.shutdown(OperationOptions{});
require(rep.has_value());
expect(rep->complete);
require(scope.join_pumping(exec).has_value());
(void)a;
}
Void::Testing::Test io_shutdown_mock_try_acquire_race_tsan()
{
// 1. try_acquire_read refuses once stream close or driver shutdown begins.
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock});
require(drv_res.has_value());
Driver& drv = **drv_res;
auto* ctrl = drv.mock_controller();
require(ctrl != nullptr);
auto s_res = drv.create_mock_stream();
require(s_res.has_value());
ByteStream s = std::move(*s_res);
std::array<std::byte, 8> buf{};
std::optional<Void::Result::Result<Transfer>> rres;
TaskScope scope{exec};
auto rtask = [](ByteStream* st,
std::span<std::byte> sp,
std::optional<Void::Result::Result<Transfer>>* out)
-> Void::Coro::Task<void> { *out = co_await st->read_some(sp); };
require(scope.spawn(rtask(&s, buf, &rres)).has_value());
(void)exec.drain();
std::optional<Void::Result::Result<void>> cres;
auto ctask = [](ByteStream* st,
std::optional<Void::Result::Result<void>>* out)
-> Void::Coro::Task<void> { *out = co_await st->close_and_join(); };
require(scope.spawn(ctask(&s, &cres)).has_value());
(void)exec.drain();
expect(!ctrl->try_acquire_read(s).has_value());
(void)drv.poll_once(0ns);
require(scope.join_pumping(exec).has_value());
auto rep = drv.shutdown(OperationOptions{});
require(rep.has_value());
expect(rep->complete);
}
// 2. Concurrent race between try_acquire_read and stop_requested cancellation (TSan).
{
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock});
require(drv_res.has_value());
Driver& drv = **drv_res;
auto* ctrl = drv.mock_controller();
require(ctrl != nullptr);
auto s_res = drv.create_mock_stream();
require(s_res.has_value());
ByteStream s = std::move(*s_res);
const std::array<std::byte, 2> payload{std::byte{'o'}, std::byte{'k'}};
for (int iter = 0; iter < 30; ++iter) {
std::array<std::byte, 8> buf{};
std::optional<Void::Result::Result<Transfer>> rres;
std::stop_source stop_src;
TaskScope scope{exec};
auto rtask = [](ByteStream* st,
std::span<std::byte> sp,
std::stop_token tok,
std::optional<Void::Result::Result<Transfer>>* out)
-> Void::Coro::Task<void> {
*out = co_await st->read_some(sp, OperationOptions{.stop = tok});
};
require(scope.spawn(rtask(&s, buf, stop_src.get_token(), &rres)).has_value());
(void)exec.drain();
std::atomic<bool> finish_ok{true};
std::thread finisher([&]() {
if (auto tok = ctrl->try_acquire_read(s)) {
finish_ok.store(
ctrl->finish_read_data(*tok, payload, false),
std::memory_order_release);
}
});
std::thread canceller([&]() {
stop_src.request_stop();
(void)drv.poll_once(0ns);
});
finisher.join();
canceller.join();
expect(finish_ok.load(std::memory_order_acquire));
(void)drv.poll_once(0ns);
require(scope.join_pumping(exec).has_value());
require(rres.has_value());
if (rres->has_value()) {
expect_eq((*rres)->bytes, std::size_t{2});
} else {
expect_eq(rres->error().code().value,
static_cast<std::int32_t>(IoErrorCode::cancelled));
}
}
auto rep = drv.shutdown(OperationOptions{});
require(rep.has_value());
expect(rep->complete);
}
// 3. Concurrent race between try_acquire_read and Driver::shutdown (TSan).
for (int iter = 0; iter < 15; ++iter) {
ManualExecutor exec;
auto drv_res = Driver::create(
exec, BackendOptions{.preference = BackendPreference::mock});
require(drv_res.has_value());
Driver& drv = **drv_res;
auto* ctrl = drv.mock_controller();
require(ctrl != nullptr);
auto s_res = drv.create_mock_stream();
require(s_res.has_value());
ByteStream s = std::move(*s_res);
std::array<std::byte, 8> buf{};
std::optional<Void::Result::Result<Transfer>> rres;
TaskScope scope{exec};
auto rtask = [](ByteStream* st,
std::span<std::byte> sp,
std::optional<Void::Result::Result<Transfer>>* out)
-> Void::Coro::Task<void> { *out = co_await st->read_some(sp); };
require(scope.spawn(rtask(&s, buf, &rres)).has_value());
(void)exec.drain();
const std::array<std::byte, 2> payload{std::byte{'o'}, std::byte{'k'}};
std::atomic<bool> finish_ok{true};
std::thread finisher([&]() {
if (auto tok = ctrl->try_acquire_read(s)) {
finish_ok.store(
ctrl->finish_read_data(*tok, payload, false),
std::memory_order_release);
}
});
std::optional<Void::Result::Result<DriverShutdownReport>> sd_rep;
std::thread shutdowner([&]() {
sd_rep = drv.shutdown(OperationOptions{});
});
finisher.join();
shutdowner.join();
expect(finish_ok.load(std::memory_order_acquire));
require(sd_rep.has_value() && sd_rep->has_value());
expect((*sd_rep)->complete);
require(scope.join_pumping(exec).has_value());
require(rres.has_value());
if (rres->has_value()) {
expect_eq((*rres)->bytes, std::size_t{2});
} else {
expect_eq(rres->error().code().value,
static_cast<std::int32_t>(IoErrorCode::closed));
}
}
}
File diff suppressed because it is too large. Load diff
+298
View File
@@ -0,0 +1,298 @@
#include <Void/Async/Task.hpp>
#include <Void/Runtime/Host.hpp>
#include <Void/Runtime/Lifecycle.hpp>
#include <Void/Runtime/Options.hpp>
#include <Void/System/SignalWatcher.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <optional>
#include <thread>
#include <vector>
namespace
{
using Void::Runtime::Host;
using Void::Runtime::HostState;
using Void::Runtime::Options;
using Void::Runtime::SignalGate;
using Void::Runtime::StartOptions;
using Void::Runtime::StartStep;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
[[nodiscard]] std::size_t count_open_fds()
{
std::size_t count = 0;
std::error_code ec;
for (const auto& _ : std::filesystem::directory_iterator("/proc/self/fd", ec)) {
(void)_;
++count;
}
return count;
}
[[nodiscard]] bool is_sig_blocked(int sig) noexcept
{
sigset_t cur{};
if (::pthread_sigmask(SIG_SETMASK, nullptr, &cur) != 0) {
return false;
}
return ::sigismember(&cur, sig) == 1;
}
void drain_and_unblock_sigusr2() noexcept
{
sigset_t set{};
::sigemptyset(&set);
::sigaddset(&set, SIGUSR2);
// Drain any queued SIGUSR2 safely while blocked before unblocking.
timespec zero{0, 0};
siginfo_t info{};
while (::sigtimedwait(&set, &info, &zero) == SIGUSR2) {
}
::pthread_sigmask(SIG_UNBLOCK, &set, nullptr);
}
struct Sigusr2CleanupGuard {
~Sigusr2CleanupGuard() { drain_and_unblock_sigusr2(); }
};
class ProcessSignalGate final : public SignalGate
{
public:
std::atomic<int> install_calls{0};
std::atomic<int> uninstall_calls{0};
std::vector<int> drained_signals{};
bool drain_before_uninstall{true};
Void::Result::Result<void> install() override
{
install_calls.fetch_add(1, std::memory_order_relaxed);
auto w = Void::Process::SignalWatcher::create({SIGUSR2});
if (!w.has_value()) {
return std::unexpected{std::move(w.error())};
}
watcher_ = std::move(*w);
return {};
}
[[nodiscard]] int drain_pending()
{
int count = 0;
if (!watcher_.has_value()) {
return count;
}
for (;;) {
auto r = watcher_->poll();
if (!r.has_value() || !r->has_value()) {
break;
}
drained_signals.push_back(**r);
++count;
}
return count;
}
void uninstall(bool on_owner_thread) noexcept override
{
(void)on_owner_thread;
if (drain_before_uninstall && watcher_.has_value()) {
(void)drain_pending();
}
watcher_.reset();
uninstall_calls.fetch_add(1, std::memory_order_relaxed);
}
private:
std::optional<Void::Process::SignalWatcher> watcher_{};
};
} // namespace
Void::Testing::Test runtime_system_gate_mask_inherited_by_workers()
{
Sigusr2CleanupGuard sig_guard;
drain_and_unblock_sigusr2();
expect(!is_sig_blocked(SIGUSR2));
ProcessSignalGate gate;
Options opts;
opts.cpu_workers = 2;
opts.file_workers = 2;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
std::atomic<int> blocked_hooks{0};
std::atomic<int> total_hooks{0};
StartOptions start_opts;
start_opts.signal_gate = &gate;
start_opts.before_thread_start =
[&](StartStep, std::size_t) -> Void::Result::Result<void> {
total_hooks.fetch_add(1, std::memory_order_relaxed);
if (is_sig_blocked(SIGUSR2)) {
blocked_hooks.fetch_add(1, std::memory_order_relaxed);
}
return {};
};
require(host.start(start_opts).has_value());
expect(is_sig_blocked(SIGUSR2));
// Owner mask installed before any thread started, so every worker hook saw it.
expect_eq(total_hooks.load(), 5);
expect_eq(blocked_hooks.load(), 5);
std::atomic<bool> worker_saw_blocked{false};
auto check_task = [](std::atomic<bool>* out) -> Void::Coro::Task<void> {
out->store(is_sig_blocked(SIGUSR2), std::memory_order_release);
co_return;
};
auto jh = host.spawn(check_task(&worker_saw_blocked));
require(jh.has_value());
require(jh->join_blocking().has_value());
expect(worker_saw_blocked.load(std::memory_order_acquire));
require(host.shutdown_blocking().has_value());
expect(!is_sig_blocked(SIGUSR2));
}
Void::Testing::Test runtime_system_gate_mask_restored_on_owner_after_failed_start_and_teardown()
{
Sigusr2CleanupGuard sig_guard;
drain_and_unblock_sigusr2();
expect(!is_sig_blocked(SIGUSR2));
// 1. Failed start restores SIGUSR2 mask on owner thread during reverse cleanup.
{
ProcessSignalGate gate;
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
StartOptions so;
so.signal_gate = &gate;
so.before_step = [](StartStep step) -> Void::Result::Result<void> {
if (step == StartStep::components) {
return std::unexpected{Void::Runtime::make_runtime_error(
Void::Runtime::RuntimeErrorCode::internal,
"inject_comp_fail")};
}
return {};
};
auto sr = host.start(so);
require(!sr.has_value());
expect(host.state() == HostState::failed_start);
expect(!is_sig_blocked(SIGUSR2));
expect_eq(gate.uninstall_calls.load(), 1);
}
// 2. Normal start -> teardown restores SIGUSR2 mask on owner thread.
{
ProcessSignalGate gate;
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
require(host.start(StartOptions{.signal_gate = &gate}).has_value());
expect(is_sig_blocked(SIGUSR2));
require(host.shutdown_blocking().has_value());
expect(!is_sig_blocked(SIGUSR2));
expect_eq(gate.uninstall_calls.load(), 1);
}
}
Void::Testing::Test runtime_signal_during_start_stays_pending_and_is_drained()
{
Sigusr2CleanupGuard sig_guard;
drain_and_unblock_sigusr2();
ProcessSignalGate gate;
Options opts;
opts.cpu_workers = 2;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
StartOptions so;
so.signal_gate = &gate;
so.before_step = [](StartStep step) -> Void::Result::Result<void> {
if (step == StartStep::readiness) {
// Send SIGUSR2 mid-start while workers exist; all block SIGUSR2.
(void)::kill(::getpid(), SIGUSR2);
}
return {};
};
require(host.start(so).has_value());
expect(is_sig_blocked(SIGUSR2));
// Signal remained pending in signalfd without killing the process and is drained once.
const int n = gate.drain_pending();
expect_eq(n, 1);
require(gate.drained_signals.size() == 1);
expect_eq(gate.drained_signals[0], SIGUSR2);
expect_eq(gate.drain_pending(), 0);
require(host.shutdown_blocking().has_value());
expect(!is_sig_blocked(SIGUSR2));
}
Void::Testing::Test runtime_offowner_destroy_closes_gate_fd_mask_not_restored()
{
Sigusr2CleanupGuard sig_guard;
drain_and_unblock_sigusr2();
expect(!is_sig_blocked(SIGUSR2));
const std::size_t fds_before = count_open_fds();
ProcessSignalGate gate;
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
require(host.start(StartOptions{.signal_gate = &gate}).has_value());
expect(is_sig_blocked(SIGUSR2));
expect(count_open_fds() > fds_before);
// Move host to a non-owner thread and destroy it there.
std::thread off_owner([moved = std::move(host)]() mutable {});
off_owner.join();
// Gate signalfd fd is closed, while owner thread mask remains blocked (not restored off-owner).
expect_eq(gate.uninstall_calls.load(), 1);
expect_eq(count_open_fds(), fds_before);
expect(is_sig_blocked(SIGUSR2));
// P3-3: explicitly restore owner mask cleanly before leaving test.
drain_and_unblock_sigusr2();
expect(!is_sig_blocked(SIGUSR2));
}
+773
View File
@@ -0,0 +1,773 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Runtime/Host.hpp>
#include <Void/Runtime/Lifecycle.hpp>
#include <Void/Runtime/Options.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <latch>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace std::chrono_literals;
using Void::Runtime::Component;
using Void::Runtime::EmbeddedResources;
using Void::Runtime::Host;
using Void::Runtime::HostBuilder;
using Void::Runtime::HostContext;
using Void::Runtime::HostState;
using Void::Runtime::Options;
using Void::Runtime::ResourceKind;
using Void::Runtime::RuntimeErrorCode;
using Void::Runtime::ShutdownPhase;
using Void::Runtime::SignalGate;
using Void::Runtime::StartOptions;
using Void::Runtime::StartStep;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
[[nodiscard]] std::size_t count_dir_entries(const char* path)
{
std::size_t count = 0;
std::error_code ec;
for (const auto& _ : std::filesystem::directory_iterator(path, ec)) {
(void)_;
++count;
}
return count;
}
// Linux pthread_join() returns at mm_release(), slightly before
// exit_notify()/release_task() removes the thread from /proc/self/task.
[[nodiscard]] std::size_t wait_for_task_count(
std::size_t expected,
std::chrono::milliseconds timeout = 500ms)
{
const auto deadline = std::chrono::steady_clock::now() + timeout;
std::size_t current = count_dir_entries("/proc/self/task");
while (current != expected && std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(1ms);
current = count_dir_entries("/proc/self/task");
}
return current;
}
[[nodiscard]] std::size_t settle_baseline_tasks()
{
std::size_t prev = count_dir_entries("/proc/self/task");
if (prev <= 1) {
return prev;
}
const auto deadline = std::chrono::steady_clock::now() + 500ms;
int stable_samples = 0;
while (std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(2ms);
const std::size_t cur = count_dir_entries("/proc/self/task");
if (cur <= 1) {
return cur;
}
if (cur == prev) {
if (++stable_samples >= 3) {
return cur;
}
} else {
prev = cur;
stable_samples = 0;
}
}
return prev;
}
class FakeSignalGate final : public SignalGate
{
public:
std::atomic<int> install_calls{0};
std::atomic<int> uninstall_calls{0};
std::optional<std::size_t> task_count_at_install{};
bool last_uninstall_on_owner{false};
bool fail_install{false};
Void::Result::Result<void> install() override
{
install_calls.fetch_add(1, std::memory_order_relaxed);
task_count_at_install = count_dir_entries("/proc/self/task");
if (fail_install) {
return std::unexpected{Void::Runtime::make_runtime_error(
RuntimeErrorCode::internal, "fake signal gate install fail")};
}
return {};
}
void uninstall(bool on_owner_thread) noexcept override
{
last_uninstall_on_owner = on_owner_thread;
uninstall_calls.fetch_add(1, std::memory_order_relaxed);
}
};
class TraceComponent final : public Component
{
public:
TraceComponent(std::string name,
std::vector<std::string>* start_log,
std::vector<std::string>* stop_log,
bool fail_start = false)
: name_(std::move(name))
, start_log_(start_log)
, stop_log_(stop_log)
, fail_start_(fail_start)
{
}
Void::Result::Result<void> start(HostContext&) override
{
if (start_log_ != nullptr) {
start_log_->push_back(name_);
}
if (fail_start_) {
return std::unexpected{Void::Runtime::make_runtime_error(
RuntimeErrorCode::conflict, name_ + "_start_failed")};
}
return {};
}
Void::Coro::Task<Void::Result::Result<void>>
stop(Void::Async::OperationOptions) override
{
if (stop_log_ != nullptr) {
stop_log_->push_back(name_);
}
co_return Void::Result::Result<void>{};
}
private:
std::string name_;
std::vector<std::string>* start_log_;
std::vector<std::string>* stop_log_;
bool fail_start_{false};
};
class StalledStopComponent final : public Component
{
public:
void release()
{
std::lock_guard lk{mu_};
released_ = true;
cv_.notify_all();
}
[[nodiscard]] bool stop_entered() const
{
std::lock_guard lk{mu_};
return entered_;
}
Void::Result::Result<void> start(HostContext&) override { return {}; }
Void::Coro::Task<Void::Result::Result<void>>
stop(Void::Async::OperationOptions) override
{
std::unique_lock lk{mu_};
entered_ = true;
cv_.notify_all();
cv_.wait(lk, [&] { return released_; });
co_return Void::Result::Result<void>{};
}
private:
mutable std::mutex mu_{};
std::condition_variable cv_{};
bool entered_{false};
bool released_{false};
};
[[nodiscard]] Void::Coro::Task<void> set_flag_task(std::atomic<bool>* flag)
{
flag->store(true, std::memory_order_release);
co_return;
}
} // namespace
Void::Testing::Test runtime_start_spawns_workers_only_on_start_ready()
{
const std::size_t baseline_tasks = settle_baseline_tasks();
Options opts;
opts.cpu_workers = 2;
opts.file_workers = 2;
opts.io.preference = Void::IO::BackendPreference::epoll;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
expect(host.state() == HostState::constructed);
expect(!host.is_running());
expect(!host.is_ready());
expect_eq(host.started_worker_count(), std::size_t{0});
expect_eq(count_dir_entries("/proc/self/task"), baseline_tasks);
require(host.start().has_value());
expect(host.state() == HostState::running);
expect(host.is_running());
expect(host.is_ready());
expect_eq(host.started_worker_count(), std::size_t{5});
expect(host.owner_thread().has_value() &&
*host.owner_thread() == std::this_thread::get_id());
expect(host.executor() != nullptr);
expect(host.io() != nullptr);
expect_eq(wait_for_task_count(baseline_tasks + 5), baseline_tasks + 5);
std::atomic<bool> ran{false};
auto jh = host.spawn(set_flag_task(&ran));
require(jh.has_value());
require(jh->join_blocking().has_value());
expect(ran.load(std::memory_order_acquire));
auto rep = host.shutdown_blocking();
require(rep.has_value());
expect(rep->complete);
expect(rep->state == HostState::stopped);
expect(!host.is_ready());
expect_eq(host.started_worker_count(), std::size_t{0});
expect_eq(wait_for_task_count(baseline_tasks), baseline_tasks);
}
Void::Testing::Test runtime_start_twice_invalid_state()
{
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
require(host.start().has_value());
auto second = host.start();
require(!second.has_value());
expect_eq(second.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::invalid_state));
expect(host.is_running());
require(host.shutdown_blocking().has_value());
auto third = host.start();
require(!third.has_value());
expect_eq(third.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::invalid_state));
}
Void::Testing::Test runtime_failed_start_each_step_reverse_cleanup_no_threads_no_fds()
{
const std::vector<StartStep> steps = {
StartStep::signal_gate,
StartStep::memory_budget,
StartStep::cpu_executor,
StartStep::io_driver,
StartStep::file_workers,
StartStep::reactor,
StartStep::components,
StartStep::readiness,
};
for (const StartStep target_step : steps) {
const std::size_t tasks_before = settle_baseline_tasks();
const std::size_t fds_before = count_dir_entries("/proc/self/fd");
FakeSignalGate gate;
std::vector<std::string> start_log;
std::vector<std::string> stop_log;
Options opts;
opts.cpu_workers = 2;
opts.file_workers = 2;
opts.io.preference = Void::IO::BackendPreference::epoll;
HostBuilder builder;
builder.with_options(opts);
require(builder
.add_component(
"trace",
ResourceKind::service,
std::make_shared<TraceComponent>(
"trace", &start_log, &stop_log))
.has_value());
auto host_res = builder.build();
require(host_res.has_value());
Host host = std::move(*host_res);
StartOptions start_opts;
start_opts.signal_gate = &gate;
start_opts.before_step = [target_step](StartStep s)
-> Void::Result::Result<void> {
if (s == target_step) {
return std::unexpected{Void::Runtime::make_runtime_error(
RuntimeErrorCode::not_found, "injected_step_failure")};
}
return {};
};
auto sr = host.start(start_opts);
require(!sr.has_value());
expect_eq(sr.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::not_found));
expect(host.state() == HostState::failed_start);
expect(!host.is_ready());
expect_eq(host.started_worker_count(), std::size_t{0});
if (target_step == StartStep::signal_gate) {
expect_eq(gate.install_calls.load(), 0);
expect_eq(gate.uninstall_calls.load(), 0);
} else {
expect_eq(gate.install_calls.load(), 1);
expect_eq(gate.uninstall_calls.load(), 1);
expect(gate.last_uninstall_on_owner);
}
if (target_step == StartStep::readiness) {
expect_eq(start_log.size(), std::size_t{1});
expect_eq(stop_log.size(), std::size_t{1});
} else {
expect_eq(start_log.size(), std::size_t{0});
expect_eq(stop_log.size(), std::size_t{0});
}
// Verify zero leaked threads or fds while failed_start Host still exists.
expect_eq(wait_for_task_count(tasks_before), tasks_before);
expect_eq(count_dir_entries("/proc/self/fd"), fds_before);
}
// A subsequent healthy Host starts cleanly after all step failures.
Options ok_opts;
ok_opts.cpu_workers = 1;
ok_opts.file_workers = 1;
ok_opts.io.preference = Void::IO::BackendPreference::epoll;
auto ok_host = Host::create(ok_opts);
require(ok_host.has_value());
require(ok_host->start().has_value());
expect(ok_host->is_ready());
require(ok_host->shutdown_blocking().has_value());
}
Void::Testing::Test runtime_failed_start_thread_fault_each_threaded_step_reverse_cleanup()
{
struct FaultCase {
StartStep step;
std::size_t index;
};
const std::vector<FaultCase> cases = {
{StartStep::cpu_executor, 0},
{StartStep::cpu_executor, 1},
{StartStep::file_workers, 0},
{StartStep::file_workers, 1},
{StartStep::reactor, 0},
};
for (const auto& c : cases) {
const std::size_t tasks_before = settle_baseline_tasks();
const std::size_t fds_before = count_dir_entries("/proc/self/fd");
FakeSignalGate gate;
Options opts;
opts.cpu_workers = 2;
opts.file_workers = 2;
opts.io.preference = Void::IO::BackendPreference::epoll;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
StartOptions start_opts;
start_opts.signal_gate = &gate;
start_opts.before_thread_start =
[c](StartStep step, std::size_t idx) -> Void::Result::Result<void> {
if (step == c.step && idx == c.index) {
return std::unexpected{Void::Runtime::make_runtime_error(
RuntimeErrorCode::internal, "injected_thread_start_failure")};
}
return {};
};
auto sr = host.start(start_opts);
require(!sr.has_value());
if (c.step == StartStep::file_workers) {
expect_eq(sr.error().code().domain, Void::Result::kIoErrorDomain);
expect_eq(sr.error().code().value,
static_cast<std::int32_t>(Void::IO::IoErrorCode::os_error));
} else {
expect_eq(sr.error().code().domain, Void::Result::kRuntimeErrorDomain);
expect_eq(sr.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::internal));
}
expect(host.state() == HostState::failed_start);
expect_eq(host.started_worker_count(), std::size_t{0});
expect_eq(gate.uninstall_calls.load(), 1);
expect_eq(wait_for_task_count(tasks_before), tasks_before);
expect_eq(count_dir_entries("/proc/self/fd"), fds_before);
}
}
Void::Testing::Test runtime_failed_start_component_cleanup_timeout_retains_then_completes()
{
auto comp_a = std::make_shared<StalledStopComponent>();
auto comp_b = std::make_shared<TraceComponent>(
"b", nullptr, nullptr, /*fail_start=*/true);
FakeSignalGate gate;
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
HostBuilder builder;
builder.with_options(opts);
require(builder.add_component("a", ResourceKind::service, comp_a).has_value());
require(
builder.add_component("b", ResourceKind::service, comp_b, {"a"}).has_value());
auto host_res = builder.build();
require(host_res.has_value());
Host host = std::move(*host_res);
auto sr = host.start(StartOptions{
.signal_gate = &gate,
.cleanup_timeout = 15ms,
});
require(!sr.has_value());
expect_eq(sr.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::conflict));
expect(host.state() == HostState::failed_start);
expect(comp_a->stop_entered());
// Resources retained because cleanup timed out on comp_a::stop.
expect(host.started_worker_count() > std::size_t{0});
expect(host.executor() != nullptr);
expect(host.io() != nullptr);
expect_eq(gate.uninstall_calls.load(), 0);
// Release comp_a and resume cleanup via shutdown_blocking.
comp_a->release();
auto rep = host.shutdown_blocking();
require(rep.has_value());
expect(rep->complete);
expect(rep->state == HostState::stopped);
expect_eq(host.started_worker_count(), std::size_t{0});
expect_eq(gate.uninstall_calls.load(), 1);
}
Void::Testing::Test runtime_component_start_failure_unwinds_reverse()
{
std::vector<std::string> start_log;
std::vector<std::string> stop_log;
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
HostBuilder builder;
builder.with_options(opts);
require(builder
.add_component(
"c1",
ResourceKind::service,
std::make_shared<TraceComponent>(
"c1", &start_log, &stop_log))
.has_value());
require(builder
.add_component(
"c2",
ResourceKind::service,
std::make_shared<TraceComponent>(
"c2", &start_log, &stop_log),
{"c1"})
.has_value());
require(builder
.add_component(
"c3",
ResourceKind::service,
std::make_shared<TraceComponent>(
"c3", &start_log, &stop_log, /*fail_start=*/true),
{"c2"})
.has_value());
auto host_res = builder.build();
require(host_res.has_value());
Host host = std::move(*host_res);
auto sr = host.start();
require(!sr.has_value());
expect(host.state() == HostState::failed_start);
require(start_log.size() == 3);
expect_eq(start_log[0], std::string{"c1"});
expect_eq(start_log[1], std::string{"c2"});
expect_eq(start_log[2], std::string{"c3"});
require(stop_log.size() == 2);
expect_eq(stop_log[0], std::string{"c2"});
expect_eq(stop_log[1], std::string{"c1"});
}
Void::Testing::Test runtime_signal_gate_before_threads_uninstall_on_owner()
{
const std::size_t tasks_before = settle_baseline_tasks();
FakeSignalGate gate;
Options opts;
opts.cpu_workers = 2;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
require(host.start(StartOptions{.signal_gate = &gate}).has_value());
require(gate.task_count_at_install.has_value());
expect_eq(*gate.task_count_at_install, tasks_before);
expect_eq(gate.uninstall_calls.load(), 0);
auto rep = host.shutdown_blocking();
require(rep.has_value());
expect(rep->complete);
expect(!rep->owner_release_pending);
expect_eq(gate.uninstall_calls.load(), 1);
expect(gate.last_uninstall_on_owner);
expect_eq(wait_for_task_count(tasks_before), tasks_before);
}
Void::Testing::Test runtime_signal_gate_uninstalled_at_most_once()
{
FakeSignalGate gate;
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
{
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
require(host.start(StartOptions{.signal_gate = &gate}).has_value());
require(host.shutdown_blocking().has_value());
require(host.shutdown_blocking().has_value());
}
expect_eq(gate.install_calls.load(), 1);
expect_eq(gate.uninstall_calls.load(), 1);
}
Void::Testing::Test runtime_embedded_start_no_threads()
{
const std::size_t tasks_before = settle_baseline_tasks();
Void::Async::ManualExecutor manual;
Void::Time::ManualClock clock;
auto drv_res = Void::IO::Driver::create(
manual,
Void::IO::BackendOptions{.preference = Void::IO::BackendPreference::mock},
clock);
require(drv_res.has_value());
auto host_res = Host::create_embedded(
Options{},
EmbeddedResources{
.executor = &manual,
.io = drv_res->get(),
.clock = &clock,
});
require(host_res.has_value());
Host host = std::move(*host_res);
require(host.start().has_value());
expect(host.is_running());
expect(host.is_ready());
expect_eq(host.started_worker_count(), std::size_t{0});
expect_eq(host.cpu_admitted(), std::size_t{0});
expect(host.executor() == &manual);
expect(host.io() == drv_res->get());
expect_eq(count_dir_entries("/proc/self/task"), tasks_before);
auto rep = host.shutdown_pumping(manual);
require(rep.has_value());
expect(rep->complete);
expect_eq(wait_for_task_count(tasks_before), tasks_before);
}
Void::Testing::Test runtime_move_after_start_keeps_resources_valid()
{
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto h1_res = Host::create(opts);
require(h1_res.has_value());
Host h1 = std::move(*h1_res);
require(h1.start().has_value());
auto* orig_exec = h1.executor();
auto* orig_io = h1.io();
Host h2 = std::move(h1);
auto h3_res = Host::create(opts);
require(h3_res.has_value());
Host h3 = std::move(*h3_res);
h3 = std::move(h2);
expect(h3.valid());
expect(h3.is_running());
expect(h3.is_ready());
expect(h3.executor() == orig_exec);
expect(h3.io() == orig_io);
std::atomic<bool> done{false};
auto jh = h3.spawn(set_flag_task(&done));
require(jh.has_value());
require(jh->join_blocking().has_value());
expect(done.load(std::memory_order_acquire));
auto rep = h3.shutdown_blocking();
require(rep.has_value());
expect(rep->complete);
}
Void::Testing::Test runtime_moved_from_host_safe_defaults()
{
auto h1_res = Host::create();
require(h1_res.has_value());
Host h1 = std::move(*h1_res);
Host h2 = std::move(h1);
expect(h2.valid());
expect(!h1.valid());
expect(h1.state() == HostState::stopped);
expect(!h1.is_running());
expect(!h1.is_ready());
expect_eq(h1.started_worker_count(), std::size_t{0});
expect_eq(h1.cpu_admitted(), std::size_t{0});
expect(h1.executor() == nullptr);
expect(h1.io() == nullptr);
expect(!h1.owner_thread().has_value());
expect(!h1.last_shutdown_report().has_value());
auto st = h1.start();
expect(!st.has_value());
expect_eq(st.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::invalid_state));
auto ps = h1.poll_shutdown();
expect(!ps.has_value());
expect_eq(ps.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::invalid_state));
auto sb = h1.shutdown_blocking();
expect(!sb.has_value());
expect_eq(sb.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::invalid_state));
Void::Async::ManualExecutor manual;
auto sp = h1.shutdown_pumping(manual);
expect(!sp.has_value());
expect_eq(sp.error().code().value,
static_cast<std::int32_t>(RuntimeErrorCode::invalid_state));
std::atomic<bool> flag{false};
auto spw = h1.spawn(set_flag_task(&flag));
expect(!spw.has_value());
expect(spw.error() == Void::Async::AdmissionError::stopped);
h1.begin_shutdown();
}
Void::Testing::Test runtime_begin_shutdown_during_start_prevents_ready()
{
const std::size_t baseline = settle_baseline_tasks();
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
bool invoked = false;
auto sr = host.start(StartOptions{
.before_step = [&](StartStep step) -> Void::Result::Result<void> {
if (step == StartStep::components && !invoked) {
invoked = true;
std::thread t([&]() { host.begin_shutdown(); });
t.join();
}
return {};
},
});
require(sr.has_value());
expect(invoked);
expect(!host.is_ready());
expect(host.state() == HostState::stopping_admission);
std::atomic<bool> flag{false};
auto spw = host.spawn(set_flag_task(&flag));
expect(!spw.has_value());
expect(spw.error() == Void::Async::AdmissionError::stopped);
auto rep = host.shutdown_blocking();
require(rep.has_value());
expect(rep->complete);
expect(rep->state == HostState::stopped);
expect_eq(wait_for_task_count(baseline), baseline);
}
Void::Testing::Test runtime_concurrent_shutdown_waits_for_start_tsan()
{
const std::size_t baseline = settle_baseline_tasks();
Options opts;
opts.cpu_workers = 1;
opts.file_workers = 1;
opts.io.preference = Void::IO::BackendPreference::mock;
auto host_res = Host::create(opts);
require(host_res.has_value());
Host host = std::move(*host_res);
std::latch entered_components{1};
std::optional<Void::Result::Result<Void::Runtime::ShutdownReport>> sd_res;
std::thread stopper([&]() {
entered_components.wait();
sd_res = host.shutdown_blocking();
});
auto sr = host.start(StartOptions{
.before_step = [&](StartStep step) -> Void::Result::Result<void> {
if (step == StartStep::components) {
entered_components.count_down();
std::this_thread::sleep_for(10ms);
}
return {};
},
});
stopper.join();
require(sr.has_value());
require(sd_res.has_value() && sd_res->has_value());
expect((*sd_res)->complete);
expect(host.state() == HostState::stopped);
expect(!host.is_ready());
expect_eq(wait_for_task_count(baseline), baseline);
}
@@ -0,0 +1,243 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/IO/File.hpp>
#include <Void/IO/Pump.hpp>
#include <Void/IO/Types.hpp>
#include <Void/System/AsyncProcess.hpp>
#include <Void/System/Process.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <unistd.h>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <optional>
#include <span>
#include <stop_token>
#include <vector>
#ifndef VOID_PROCESS_HELPER_PATH
#define VOID_PROCESS_HELPER_PATH ""
#endif
namespace
{
using namespace std::chrono_literals;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
class ScopedTempDir
{
public:
ScopedTempDir()
{
auto tmpl =
(std::filesystem::temp_directory_path() / "void_w11_sysasync_XXXXXX")
.string();
std::vector<char> buf(tmpl.begin(), tmpl.end());
buf.push_back('\0');
char* created = ::mkdtemp(buf.data());
if (created != nullptr) {
path_ = created;
}
}
~ScopedTempDir()
{
if (!path_.empty()) {
std::error_code ec;
std::filesystem::remove_all(path_, ec);
}
}
ScopedTempDir(const ScopedTempDir&) = delete;
ScopedTempDir& operator=(const ScopedTempDir&) = delete;
[[nodiscard]] bool valid() const noexcept { return !path_.empty(); }
[[nodiscard]] std::filesystem::path file(std::string_view name) const
{
return path_ / name;
}
private:
std::filesystem::path path_{};
};
class Gate
{
public:
void wait()
{
std::unique_lock lk{mu_};
++waiting_;
cv_.notify_all();
cv_.wait(lk, [this] { return open_; });
}
[[nodiscard]] bool wait_for_waiters(
int n, std::chrono::milliseconds timeout = 5000ms)
{
std::unique_lock lk{mu_};
return cv_.wait_for(lk, timeout, [&] { return waiting_ >= n; });
}
void open()
{
std::lock_guard lk{mu_};
open_ = true;
cv_.notify_all();
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
int waiting_{0};
};
class GatedFileSyscalls final : public Void::IO::FileSyscalls
{
public:
Gate gate{};
Void::IO::FileSyscallResult pread(int fd, std::span<std::byte> buf,
std::uint64_t offset) noexcept override
{
gate.wait();
return Void::IO::FileSyscalls::pread(fd, buf, offset);
}
};
} // namespace
Void::Testing::Test systemasync_driver_shutdown_pending_pipe_read_retains_and_delivers_once()
{
ScopedTempDir dir;
require(dir.valid());
const auto path = dir.file("pipe_gate.bin");
{
std::ofstream ofs(path, std::ios::binary);
ofs << "gate_data_123456";
}
GatedFileSyscalls sys;
Void::Time::ManualClock clock{
Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}};
Void::Async::ManualExecutor exec;
auto drv_res = Void::IO::Driver::create(
exec,
Void::IO::BackendOptions{
.limits = Void::IO::IoLimits{.file_workers = 1, .max_file_queue = 8},
.preference = Void::IO::BackendPreference::epoll,
.file_syscalls = &sys,
},
clock);
require(drv_res.has_value());
Void::IO::Driver& drv = **drv_res;
require(drv.start_file_workers().has_value());
auto f_res = drv.open_file(path, Void::IO::FileOpenOptions{});
require(f_res.has_value());
Void::IO::File file = std::move(*f_res);
Void::SystemAsync::ProcessManager mgr{
drv,
exec,
Void::SystemAsync::ProcessManagerOptions{
.default_kill_grace = 30ms,
}};
Void::Process::SpawnOptions opts;
opts.executable = VOID_PROCESS_HELPER_PATH;
opts.arguments = {"ignore-sigterm", "10000"};
opts.kill_grace = 20ms;
auto child_res = mgr.spawn(opts);
require(child_res.has_value());
auto child = std::move(*child_res);
std::array<std::byte, 8> fbuf{};
std::optional<Void::Result::Result<Void::IO::Transfer>> file_res;
int file_deliveries = 0;
std::optional<
Void::Result::Result<Void::Process::CommunicateResult, Void::Result::Error>>
comm_res;
int comm_deliveries = 0;
Void::Async::TaskScope scope{exec};
auto file_coro = [](Void::IO::File* f,
std::span<std::byte> b,
std::optional<Void::Result::Result<Void::IO::Transfer>>* out,
int* count) -> Void::Coro::Task<void> {
*out = co_await f->read_at(0, b);
++(*count);
};
auto comm_coro = [](Void::SystemAsync::ProcessManager* m,
Void::SystemAsync::ManagedChild* ch,
std::optional<Void::Result::Result<
Void::Process::CommunicateResult,
Void::Result::Error>>* out,
int* count) -> Void::Coro::Task<void> {
*out = co_await m->communicate(*ch);
++(*count);
};
require(scope.spawn(file_coro(&file, fbuf, &file_res, &file_deliveries)).has_value());
require(scope.spawn(comm_coro(&mgr, &child, &comm_res, &comm_deliveries)).has_value());
// Wait for the stalled file worker AND ProcessManager's two pipe leases (2 * 16 KiB).
auto wait_reg = Void::IO::pump_until(
drv,
exec,
[&]() {
return drv.telemetry().active_file_requests >= 1 &&
drv.telemetry().owned_buffer_bytes >= 32768;
},
Void::IO::PumpOptions{.max_wait = 2ms, .max_turns = 200});
require(wait_reg.has_value());
require(sys.gate.wait_for_waiters(1));
expect_eq(comm_deliveries, 0);
expect_eq(file_deliveries, 0);
// Bounded Driver::shutdown expires while file worker stalls -> incomplete, pipe leases retained.
auto rep1 = drv.shutdown(
Void::Async::OperationOptions{.deadline = clock.now()});
require(rep1.has_value());
expect(!rep1->complete);
expect_eq(rep1->active_file_requests, std::size_t{1});
expect(rep1->open_descriptors >= std::size_t{1});
expect_eq(drv.telemetry().owned_buffer_bytes, std::size_t{32768});
expect_eq(comm_deliveries, 0);
expect_eq(file_deliveries, 0);
// Unblock file worker and kill child -> Driver shutdown completes and delivers once.
sys.gate.open();
(void)child.child().send_signal(SIGKILL);
auto rep2 = drv.shutdown(
Void::Async::OperationOptions{
.deadline = Void::Time::deadline_after(clock, 5s)});
require(rep2.has_value());
expect(rep2->complete);
expect(drv.shutdown_complete());
expect_eq(rep2->open_descriptors, std::size_t{0});
(void)scope.join_pumping(exec);
expect_eq(file_deliveries, 1);
expect_eq(comm_deliveries, 1);
require(file_res.has_value() && file_res->has_value());
expect_eq((*file_res)->bytes, std::size_t{8});
expect(comm_res.has_value());
expect_eq(drv.telemetry().owned_buffer_bytes, std::size_t{0});
}