From 710a9c183375865a24ba8fbdf69ded7de2ffa4d6 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:33:45 +0300 Subject: [PATCH 1/5] docs(workflow): add Wave 4A (P1 Algorithms, Unicode, Async) task specs --- docs/agent-workflow/tasks/M-ASYNC-02-03.md | 38 ++++++++++++++++++++ docs/agent-workflow/tasks/S-ALGORITHMS-02.md | 38 ++++++++++++++++++++ docs/agent-workflow/tasks/S-UNICODE-01-02.md | 38 ++++++++++++++++++++ 3 files changed, 114 insertions(+) create mode 100644 docs/agent-workflow/tasks/M-ASYNC-02-03.md create mode 100644 docs/agent-workflow/tasks/S-ALGORITHMS-02.md create mode 100644 docs/agent-workflow/tasks/S-UNICODE-01-02.md diff --git a/docs/agent-workflow/tasks/M-ASYNC-02-03.md b/docs/agent-workflow/tasks/M-ASYNC-02-03.md new file mode 100644 index 0000000..47f481f --- /dev/null +++ b/docs/agent-workflow/tasks/M-ASYNC-02-03.md @@ -0,0 +1,38 @@ +# Async OperationState, ResumeTicket, TaskScope, and Bounded Executor Lanes +Task ID: M-ASYNC-02, M-ASYNC-03 +Phase: P1 +Status: APPROVED +Contracts: C-01, C-04, C-06, C-07 + +## 1. Context and baseline +`src/Async/module.cmake` currently depends only on `LogState`, while `include/Void/Async/Executor.hpp` provides only void-returning `post()`, `ManualExecutor`, `schedule_on`, and fire-and-forget `spawn()`. Async lacks structured admission control, race-free backend completion vs cancellation settlement, completion-lane backpressure bypass, and structured `TaskScope` join/cancellation/exception ownership. + +## 2. Deliverables +- Updated `src/Async/module.cmake` declaring `INTERNAL_DEPS Functional Time LogState`. +- New `include/Void/Async/Operation.hpp`: `OperationOptions`, `AdmissionError`, `AsyncErrorCode` (`kAsyncErrorDomain`), `make_async_error`, `DomainOutcomeKind`, `ResumeTicket`, and `OperationState` managing combined `std::stop_source`, atomic `backend_refs`, single-winner CAS terminal state, and post-backend-release continuation resumption outside locks. +- Upgraded `include/Void/Async/Executor.hpp`: keeps 1.x `post`/`ManualExecutor`/`schedule_on`/`spawn` working while adding `try_post`, `post_completion` (reserved completion lane), `is_executor_thread()`, bounded `ManualExecutor` queue capacity, and cancellable clock-aware `schedule_on(executor, options, clock)`. +- New `include/Void/Async/TaskScope.hpp`: `TaskScopeOptions`, `JoinHandle`, reserve-then-transfer `TaskScope::spawn` (preserving `Task` on admission failure), `request_stop`, `co_await join()`, `join_blocking()` with `self_join` detection, `join_pumping`, and `DetachedOwner`. +- Tests in `tests/standalone/Async/OperationScope.cpp`. + +## 3. Exact files and interfaces +- `src/Async/module.cmake` +- `include/Void/Async/Operation.hpp` +- `include/Void/Async/Executor.hpp` +- `include/Void/Async/TaskScope.hpp` +- `tests/standalone/Async/OperationScope.cpp` + +## 4. Edge cases +- Failed `TaskScope::spawn` (full or stopped) does not consume or destroy caller's `Coro::Task`. +- Concurrent backend commit vs `std::stop_token` firing resolves to exactly one terminal outcome, releases backend references before resuming continuation outside locks, and supports synchronous completion without double-resume. +- Reserved `post_completion` succeeds even when normal submission queue capacity is saturated. +- `join_blocking()` called from the associated executor thread detects `self_join` rather than deadlocking. +- Concurrent cancellation/completion/join stress passes cleanly under Debug TSan and ASan/UBSan. + +## 5. Acceptance criteria +- `OperationScope*`, `Executor*`, `Coro*`, and `ThreadPool*` tests pass under RelWithDebInfo `-Werror`, ASan+UBSan, and Debug TSan (`-DVOID_ENABLE_TSAN=ON`). + +## 6. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-async -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-async && /tmp/void-w4a-async/tests/VoidTests --filter "OperationScope*|Executor*|Coro*" && ctest --test-dir /tmp/void-w4a-async --output-on-failure --timeout 60' +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-async-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-async-tsan && /tmp/void-w4a-async-tsan/tests/VoidTests --filter "OperationScope*|Executor*|ThreadPool*"' +``` \ No newline at end of file diff --git a/docs/agent-workflow/tasks/S-ALGORITHMS-02.md b/docs/agent-workflow/tasks/S-ALGORITHMS-02.md new file mode 100644 index 0000000..82cf4eb --- /dev/null +++ b/docs/agent-workflow/tasks/S-ALGORITHMS-02.md @@ -0,0 +1,38 @@ +# Algorithms Indexed Graph Views, Work Budgets, and Iterative Traversals/Topology +Task ID: S-ALGORITHMS-02 +Phase: P1 +Status: APPROVED +Contracts: C-01, C-05, C-07 + +## 1. Context and baseline +VoidLibrary currently has no `Algorithms` module (`src/Algorithms/module.cmake`, `include/Void/Algorithms/`). Graph algorithms are needed as a standalone header-only module with strict dependency discipline (`INTERNAL_DEPS Core Math`), zero unbounded recursion, pre-checked scratch memory budgets, overflow-safe sizing via `Void::Numeric`, and safe cancellation / concurrent graph mutation detection. + +## 2. Deliverables +- `src/Algorithms/module.cmake` declaring `INTERNAL_DEPS Core Math`. +- New `include/Void/Algorithms/Graph.hpp` defining `Void::Algorithms::{WorkLimits, AlgorithmError, Topology, TraversalResult, ShortestPathResult, IndexedGraphView, HasVersionStamp, AdjacencyView}` and iterative `bfs`, `dfs`, `shortest_path_unweighted`, and `topological_order`. +- Comprehensive unit and edge-case tests in `tests/standalone/Algorithms/Graph.cpp`. +- Package consumer `tests/package/AlgorithmsOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake` (`Algorithms Math Core`). + +## 3. Exact files and interfaces +- `src/Algorithms/module.cmake` +- `include/Void/Algorithms/Graph.hpp` +- `tests/standalone/Algorithms/Graph.cpp` +- `tests/package/AlgorithmsOnly/CMakeLists.txt` +- `tests/package/AlgorithmsOnly/main.cpp` +- `tests/package/InstalledComponents.cmake` + +## 4. Edge cases +- Out-of-range source/target vertex IDs or `vertex_count()` exceeding `WorkLimits` rejected before scratch allocations. +- Overflowing edge/vertex scratch budget calculations rejected using `Void::Numeric::checked_mul`/`checked_add`. +- Out-of-range neighbor IDs in adjacency lists diagnosed cleanly without out-of-bounds vector access. +- Deep graphs (`> 100k` vertices / chains) execute strictly iteratively with no stack overflow. +- `topological_order` uses Kahn's algorithm and, on cycle detection, runs iterative 3-color DFS to extract a deterministic cycle witness `[u0, ..., uk, u0]`. +- Periodic `std::stop_token` and `HasVersionStamp::version()` checks abort mid-traversal with `cancelled` / `concurrent_modification`. + +## 5. Acceptance criteria +- `Graph*` tests and `VoidInstalledComponentConsumers` (`AlgorithmsOnly`) pass under `-DVOID_WARNINGS_AS_ERRORS=ON` and ASan/UBSan. + +## 6. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-alg -G Ninja -DVOID_ENABLED_MODULES="Algorithms;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-alg && /tmp/void-w4a-alg/tests/VoidTests --filter "Graph*" && ctest --test-dir /tmp/void-w4a-alg --output-on-failure --timeout 60' +``` \ No newline at end of file diff --git a/docs/agent-workflow/tasks/S-UNICODE-01-02.md b/docs/agent-workflow/tasks/S-UNICODE-01-02.md new file mode 100644 index 0000000..179e227 --- /dev/null +++ b/docs/agent-workflow/tasks/S-UNICODE-01-02.md @@ -0,0 +1,38 @@ +# Unicode 17.0.0 Manifest and Strict/Repair/Streaming UTF Codecs +Task ID: S-UNICODE-01, S-UNICODE-02 +Phase: P1 +Status: APPROVED +Contracts: C-01, C-05, C-07 + +## 1. Context and baseline +VoidLibrary currently has no `Unicode` module (`src/Unicode/`). `Text` handles locale-free ASCII-only operations (`M-TEXT-02`), while UTF-8/UTF-16/UTF-32 validation, transcoding, one-unit repair, and streaming decoding must live in a dedicated `Unicode` module pinning Unicode `17.0.0` metadata and keeping `Text` independent of Unicode data. + +## 2. Deliverables +- `src/Unicode/module.cmake` declaring `INTERNAL_DEPS Core Text`. +- `src/Unicode/MANIFEST.md` pinning Unicode `17.0.0`, official UCD source URL, and Unicode license notice. +- New `include/Void/Unicode/Utf.hpp` defining `Void::Unicode::{data_version, is_scalar_value, UtfPolicy, UtfErrorKind, UtfError, Scalar, UtfLimits, TranscodeCounts}`, strict & `replace_one_unit` validation/transcoding functions for UTF-8/UTF-16/UTF-32 (owning and into-`std::span`), and stateful `Utf8StreamDecoder` / `Utf16StreamDecoder`. +- Tests in `tests/standalone/Unicode/Utf.cpp`. +- Package consumer `tests/package/UnicodeOnly/{CMakeLists.txt,main.cpp}` registered in `tests/package/InstalledComponents.cmake` (`Unicode Text Core`). + +## 3. Exact files and interfaces +- `src/Unicode/module.cmake` +- `src/Unicode/MANIFEST.md` +- `include/Void/Unicode/Utf.hpp` +- `tests/standalone/Unicode/Utf.cpp` +- `tests/package/UnicodeOnly/CMakeLists.txt` +- `tests/package/UnicodeOnly/main.cpp` +- `tests/package/InstalledComponents.cmake` + +## 4. Edge cases +- Rejects overlong UTF-8 sequences, UTF-16 surrogates (`U+D800..U+DFFF`) in UTF-8/UTF-32, unpaired surrogates in UTF-16, code points `> U+10FFFF`, and truncated sequences under `UtfPolicy::reject`. +- WHATWG-compliant maximal subpart (`replace_one_unit`) emits `U+FFFD` per ill-formed unit/maximal subpart and advances cleanly without skipping subsequent valid units. +- Pre-reserve limit checks against `UtfLimits` reject oversized inputs/outputs before large allocations; periodic `std::stop_token` checks abort long transcodes cleanly. +- Streaming `Utf8StreamDecoder` / `Utf16StreamDecoder` split sequences across arbitrary 1-byte/1-unit boundaries and flush trailing incomplete sequences cleanly at EOF. + +## 5. Acceptance criteria +- `Utf*` tests and `VoidInstalledComponentConsumers` (`UnicodeOnly`) pass under `-DVOID_WARNINGS_AS_ERRORS=ON` and ASan/UBSan. + +## 6. Verification commands +```sh +dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w4a-unicode -G Ninja -DVOID_ENABLED_MODULES="Unicode;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w4a-unicode && /tmp/void-w4a-unicode/tests/VoidTests --filter "Utf*" && ctest --test-dir /tmp/void-w4a-unicode --output-on-failure --timeout 60' +``` \ No newline at end of file From bfd6246d32c90c2b65809553f9b6e16392b031cd Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:36:10 +0300 Subject: [PATCH 2/5] feat(Algorithms): add indexed graph views, work budgets, and iterative traversals/topology (S-ALGORITHMS-02) --- include/Void/Algorithms/Graph.hpp | 786 ++++++++++++++++++++ src/Algorithms/module.cmake | 3 + tests/package/AlgorithmsOnly/CMakeLists.txt | 10 + tests/package/AlgorithmsOnly/main.cpp | 20 + tests/package/InstalledComponents.cmake | 5 + tests/standalone/Algorithms/Graph.cpp | 304 ++++++++ 6 files changed, 1128 insertions(+) create mode 100644 include/Void/Algorithms/Graph.hpp create mode 100644 src/Algorithms/module.cmake create mode 100644 tests/package/AlgorithmsOnly/CMakeLists.txt create mode 100644 tests/package/AlgorithmsOnly/main.cpp create mode 100644 tests/standalone/Algorithms/Graph.cpp diff --git a/include/Void/Algorithms/Graph.hpp b/include/Void/Algorithms/Graph.hpp new file mode 100644 index 0000000..9229ca9 --- /dev/null +++ b/include/Void/Algorithms/Graph.hpp @@ -0,0 +1,786 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Algorithms +{ + +struct WorkLimits { + std::size_t max_vertices{1'000'000}; + std::size_t max_steps{16'000'000}; + std::size_t max_scratch_bytes{64ULL * 1024ULL * 1024ULL}; + std::size_t cancel_check_interval{1024}; +}; + +struct AlgorithmError { + enum class Code { + invalid_input, + invalid_vertex, + limit_exceeded, + overflow, + cancelled, + concurrent_modification, + cycle_detected + }; + + Code code{Code::invalid_input}; + std::string message{}; + std::vector cycle{}; +}; + +struct TraversalResult { + static constexpr std::size_t npos = std::numeric_limits::max(); + + std::vector order{}; + std::vector parent{}; + std::vector depth{}; +}; + +struct ShortestPathResult { + static constexpr std::size_t npos = std::numeric_limits::max(); + + bool found{false}; + std::size_t distance{npos}; + std::vector path{}; +}; + +struct Topology { + std::vector order{}; + std::vector position{}; +}; + +template +concept IndexedGraphView = requires(const G& g, std::size_t u) { + { g.vertex_count() } -> std::convertible_to; + { g.neighbors(u) } -> std::ranges::input_range; + requires std::convertible_to, + std::size_t>; +}; + +template +concept HasVersionStamp = requires(const G& g) { + { g.version() }; + { g.version() == g.version() } -> std::convertible_to; +}; + +class AdjacencyView +{ +public: + AdjacencyView() noexcept = default; + + explicit AdjacencyView(std::span> lists) noexcept + : lists_(lists) + { + } + + explicit AdjacencyView(const std::vector>& lists) noexcept + : lists_(lists) + { + } + + [[nodiscard]] static std::expected + try_from_csr(std::span offsets, + std::span edges) + { + if (offsets.empty()) { + if (!edges.empty()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR edges present with empty offsets"}}; + } + return AdjacencyView{}; + } + if (offsets.front() != 0) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR offsets must start at 0"}}; + } + for (std::size_t i = 0; i + 1 < offsets.size(); ++i) { + if (offsets[i] > offsets[i + 1]) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR offsets must be monotonically non-decreasing"}}; + } + } + if (offsets.back() > edges.size()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_input, + "CSR final offset exceeds edges span size"}}; + } + return AdjacencyView{offsets, edges}; + } + + [[nodiscard]] std::size_t vertex_count() const noexcept + { + if (is_csr_) { + return csr_offsets_.empty() ? 0 : (csr_offsets_.size() - 1); + } + return lists_.size(); + } + + [[nodiscard]] std::span neighbors(std::size_t u) const noexcept + { + if (is_csr_) { + if (u + 1 >= csr_offsets_.size()) { + return {}; + } + const std::size_t begin = csr_offsets_[u]; + const std::size_t end = csr_offsets_[u + 1]; + if (begin > end || end > csr_edges_.size()) { + return {}; + } + return csr_edges_.subspan(begin, end - begin); + } + if (u >= lists_.size()) { + return {}; + } + return lists_[u]; + } + +private: + AdjacencyView(std::span offsets, + std::span edges) noexcept + : csr_offsets_(offsets) + , csr_edges_(edges) + , is_csr_(true) + { + } + + std::span> lists_{}; + std::span csr_offsets_{}; + std::span csr_edges_{}; + bool is_csr_{false}; +}; + +namespace detail +{ + +template +[[nodiscard]] inline bool valid_vertex_index(T raw, std::size_t vertex_count) noexcept +{ + if constexpr (std::is_signed_v) { + if (raw < 0) { + return false; + } + } + return std::cmp_less(raw, vertex_count); +} + +[[nodiscard]] inline std::expected + checked_scratch_bytes(std::size_t count, + std::size_t bytes_per_element, + const WorkLimits& limits) +{ + const auto prod = Void::Numeric::checked_mul(count, bytes_per_element); + if (!prod.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "Scratch byte budget multiplication overflowed"}}; + } + if (*prod > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Estimated scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + return *prod; +} + +template +struct VersionSnapshot { +}; + +template + requires HasVersionStamp +struct VersionSnapshot { + using type = std::remove_cvref_t().version())>; + type initial{}; +}; + +template +[[nodiscard]] inline VersionSnapshot capture_version(const G& g) +{ + if constexpr (HasVersionStamp) { + return VersionSnapshot{g.version()}; + } else { + (void)g; + return VersionSnapshot{}; + } +} + +template +[[nodiscard]] inline std::expected + check_state(const G& g, + const VersionSnapshot& snap, + const std::stop_token& stop_token) +{ + if (stop_token.stop_requested()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::cancelled, + "Algorithm cancelled via stop_token"}}; + } + if constexpr (HasVersionStamp) { + if (!(g.version() == snap.initial)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::concurrent_modification, + "Graph version changed during traversal"}}; + } + } else { + (void)g; + (void)snap; + } + return {}; +} + +[[nodiscard]] inline std::expected + advance_step(std::size_t& steps, const WorkLimits& limits) +{ + if (steps >= limits.max_steps) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Step count exceeded WorkLimits::max_steps"}}; + } + const auto next = Void::Numeric::checked_add(steps, std::size_t{1}); + if (!next.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "Step counter overflowed"}}; + } + steps = *next; + return {}; +} + +template +[[nodiscard]] inline std::expected + step_and_maybe_check(const G& g, + const VersionSnapshot& snap, + const std::stop_token& stop_token, + std::size_t& steps, + const WorkLimits& limits) +{ + if (auto s = advance_step(steps, limits); !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (limits.cancel_check_interval > 0 && + (steps % limits.cancel_check_interval) == 0) { + if (auto c = check_state(g, snap, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + } + return {}; +} + +} // namespace detail + +template +[[nodiscard]] std::expected + bfs(const G& graph, + std::size_t start, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + if (start >= n) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Start vertex index is out of range"}}; + } + + constexpr std::size_t kPerVertexBytes = + 4 * sizeof(std::size_t) + sizeof(std::uint8_t); + if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + + std::vector visited(n, 0); + std::vector queue; + queue.reserve(n); + + TraversalResult result; + result.parent.assign(n, TraversalResult::npos); + result.depth.assign(n, TraversalResult::npos); + result.order.reserve(n); + + visited[start] = 1; + result.depth[start] = 0; + queue.push_back(start); + + std::size_t steps = 0; + std::size_t head = 0; + while (head < queue.size()) { + const std::size_t u = queue[head++]; + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + result.order.push_back(u); + + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (!visited[v]) { + visited[v] = 1; + result.parent[v] = u; + result.depth[v] = result.depth[u] + 1; + queue.push_back(v); + } + } + } + + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return result; +} + +template +[[nodiscard]] std::expected + dfs(const G& graph, + std::size_t start, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + if (start >= n) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Start vertex index is out of range"}}; + } + + struct Frame { + std::size_t vertex; + std::size_t parent; + std::size_t depth; + }; + + constexpr std::size_t kBasePerVertexBytes = + 3 * sizeof(std::size_t) + sizeof(std::uint8_t); + const auto base_scratch = + detail::checked_scratch_bytes(n, kBasePerVertexBytes, limits); + if (!base_scratch.has_value()) { + return std::unexpected{std::move(base_scratch.error())}; + } + + std::vector visited(n, 0); + std::vector stack; + std::vector scratch_neighbors; + + TraversalResult result; + result.parent.assign(n, TraversalResult::npos); + result.depth.assign(n, TraversalResult::npos); + result.order.reserve(n); + + if (*base_scratch + sizeof(Frame) > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + stack.push_back(Frame{start, TraversalResult::npos, 0}); + + std::size_t steps = 0; + while (!stack.empty()) { + const Frame cur = stack.back(); + stack.pop_back(); + + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (visited[cur.vertex]) { + continue; + } + visited[cur.vertex] = 1; + result.parent[cur.vertex] = cur.parent; + result.depth[cur.vertex] = cur.depth; + result.order.push_back(cur.vertex); + + scratch_neighbors.clear(); + for (const auto raw_v : graph.neighbors(cur.vertex)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (!visited[v]) { + scratch_neighbors.push_back(v); + const auto dyn_bytes = Void::Numeric::checked_mul( + stack.size() + scratch_neighbors.size(), sizeof(Frame)); + if (!dyn_bytes.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "DFS stack byte calculation overflowed"}}; + } + if (*base_scratch + *dyn_bytes > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + } + } + for (auto it = scratch_neighbors.rbegin(); it != scratch_neighbors.rend(); ++it) { + stack.push_back(Frame{*it, cur.vertex, cur.depth + 1}); + } + } + + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return result; +} + +template +[[nodiscard]] std::expected + shortest_path_unweighted(const G& graph, + std::size_t start, + std::size_t target, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + if (start >= n || target >= n) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Start or target vertex index is out of range"}}; + } + + if (start == target) { + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return ShortestPathResult{ + .found = true, + .distance = 0, + .path = {start}, + }; + } + + constexpr std::size_t kPerVertexBytes = + 2 * sizeof(std::size_t) + sizeof(std::uint8_t); + if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + + std::vector visited(n, 0); + std::vector parent(n, ShortestPathResult::npos); + std::vector queue; + queue.reserve(n); + + visited[start] = 1; + queue.push_back(start); + + bool reached = false; + std::size_t steps = 0; + std::size_t head = 0; + while (head < queue.size() && !reached) { + const std::size_t u = queue[head++]; + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (!visited[v]) { + visited[v] = 1; + parent[v] = u; + queue.push_back(v); + if (v == target) { + reached = true; + break; + } + } + } + } + + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + if (!reached) { + return ShortestPathResult{ + .found = false, + .distance = ShortestPathResult::npos, + .path = {}, + }; + } + + std::vector path; + for (std::size_t cur = target; cur != ShortestPathResult::npos; cur = parent[cur]) { + path.push_back(cur); + } + std::reverse(path.begin(), path.end()); + const std::size_t distance = path.empty() ? 0 : (path.size() - 1); + return ShortestPathResult{ + .found = true, + .distance = distance, + .path = std::move(path), + }; +} + +template +[[nodiscard]] std::expected + topological_order(const G& graph, + const WorkLimits& limits = {}, + std::stop_token stop_token = {}) +{ + const auto version = detail::capture_version(graph); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + + const std::size_t n = static_cast(graph.vertex_count()); + if (n > limits.max_vertices) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Vertex count exceeds WorkLimits::max_vertices"}}; + } + + if (n == 0) { + return Topology{}; + } + + constexpr std::size_t kPerVertexBytes = 4 * sizeof(std::size_t); + const auto base_scratch = + detail::checked_scratch_bytes(n, kPerVertexBytes, limits); + if (!base_scratch.has_value()) { + return std::unexpected{std::move(base_scratch.error())}; + } + + std::vector in_degree(n, 0); + std::size_t steps = 0; + for (std::size_t u = 0; u < n; ++u) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + const auto inc = Void::Numeric::checked_add(in_degree[v], std::size_t{1}); + if (!inc.has_value()) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::overflow, + "In-degree counter overflowed"}}; + } + in_degree[v] = *inc; + } + } + + std::vector queue; + queue.reserve(n); + for (std::size_t u = 0; u < n; ++u) { + if (in_degree[u] == 0) { + queue.push_back(u); + } + } + + Topology topo; + topo.order.reserve(n); + topo.position.assign(n, 0); + + std::size_t head = 0; + while (head < queue.size()) { + const std::size_t u = queue[head++]; + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + topo.position[u] = topo.order.size(); + topo.order.push_back(u); + + for (const auto raw_v : graph.neighbors(u)) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + if (!detail::valid_vertex_index(raw_v, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + const std::size_t v = static_cast(raw_v); + if (--in_degree[v] == 0) { + queue.push_back(v); + } + } + } + + if (topo.order.size() == n) { + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return topo; + } + + // Extract a deterministic cycle witness [u0, ..., uk, u0] via iterative 3-color DFS. + enum class Color : std::uint8_t { unvisited = 0, active = 1, done = 2 }; + struct CycleFrame { + std::size_t vertex; + std::size_t edge_begin; + std::size_t edge_end; + std::size_t edge_cursor; + }; + + const auto extra_colors = detail::checked_scratch_bytes(n, sizeof(Color), limits); + if (!extra_colors.has_value() || + *base_scratch + *extra_colors > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + + std::vector color(n, Color::unvisited); + std::vector stack; + std::vector edge_pool; + + auto push_frame = [&](std::size_t v) -> std::expected { + color[v] = Color::active; + const std::size_t begin = edge_pool.size(); + for (const auto raw_nxt : graph.neighbors(v)) { + if (!detail::valid_vertex_index(raw_nxt, n)) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::invalid_vertex, + "Neighbor vertex index out of range"}}; + } + edge_pool.push_back(static_cast(raw_nxt)); + } + const std::size_t end = edge_pool.size(); + const std::size_t dyn_bytes = + (stack.size() + 1) * sizeof(CycleFrame) + edge_pool.size() * sizeof(std::size_t); + if (*base_scratch + *extra_colors + dyn_bytes > limits.max_scratch_bytes) { + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::limit_exceeded, + "Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}}; + } + stack.push_back(CycleFrame{v, begin, end, begin}); + return {}; + }; + + for (std::size_t seed = 0; seed < n; ++seed) { + if (in_degree[seed] == 0 || color[seed] != Color::unvisited) { + continue; + } + if (auto p = push_frame(seed); !p.has_value()) { + return std::unexpected{std::move(p.error())}; + } + + while (!stack.empty()) { + if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits); + !s.has_value()) { + return std::unexpected{std::move(s.error())}; + } + auto& top = stack.back(); + if (top.edge_cursor < top.edge_end) { + const std::size_t v = edge_pool[top.edge_cursor++]; + if (color[v] == Color::active) { + std::vector witness; + auto it = std::find_if(stack.begin(), stack.end(), [v](const CycleFrame& f) { + return f.vertex == v; + }); + for (; it != stack.end(); ++it) { + witness.push_back(it->vertex); + } + witness.push_back(v); + if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) { + return std::unexpected{std::move(c.error())}; + } + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::cycle_detected, + "Directed graph contains a cycle", + std::move(witness)}}; + } + if (color[v] == Color::unvisited) { + if (auto p = push_frame(v); !p.has_value()) { + return std::unexpected{std::move(p.error())}; + } + } + } else { + const std::size_t pop_begin = top.edge_begin; + color[top.vertex] = Color::done; + stack.pop_back(); + edge_pool.resize(pop_begin); + } + } + } + + return std::unexpected{AlgorithmError{ + AlgorithmError::Code::cycle_detected, + "Directed graph contains a cycle"}}; +} + +} // namespace Void::Algorithms \ No newline at end of file diff --git a/src/Algorithms/module.cmake b/src/Algorithms/module.cmake new file mode 100644 index 0000000..3cdfdc1 --- /dev/null +++ b/src/Algorithms/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Algorithms + INTERNAL_DEPS Core Math +) \ No newline at end of file diff --git a/tests/package/AlgorithmsOnly/CMakeLists.txt b/tests/package/AlgorithmsOnly/CMakeLists.txt new file mode 100644 index 0000000..e4cb483 --- /dev/null +++ b/tests/package/AlgorithmsOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidAlgorithmsOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Algorithms) + +add_executable(void_algorithms_only_consumer main.cpp) +target_link_libraries(void_algorithms_only_consumer PRIVATE Void::Algorithms) + +enable_testing() +add_test(NAME VoidAlgorithmsOnlyConsumer COMMAND void_algorithms_only_consumer) \ No newline at end of file diff --git a/tests/package/AlgorithmsOnly/main.cpp b/tests/package/AlgorithmsOnly/main.cpp new file mode 100644 index 0000000..7a62f47 --- /dev/null +++ b/tests/package/AlgorithmsOnly/main.cpp @@ -0,0 +1,20 @@ +#include + +#include + +int main() +{ + const std::vector> dag{ + {1, 2}, + {3}, + {3}, + {}, + }; + const Void::Algorithms::AdjacencyView view{dag}; + const auto sp = Void::Algorithms::shortest_path_unweighted(view, 0, 3); + const auto topo = Void::Algorithms::topological_order(view); + if (!sp || !sp->found || sp->distance != 2 || !topo || topo->order.size() != 4) { + return 1; + } + return 0; +} \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index a8bf104..043dab8 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -96,6 +96,11 @@ if(_has_binary) run_consumer(Binary "${install_prefix}" "Binary" ${_no_external_deps}) endif() +has_modules(_has_algorithms Algorithms Math Core) +if(_has_algorithms) + run_consumer(AlgorithmsOnly "${install_prefix}" "AlgorithmsOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/Algorithms/Graph.cpp b/tests/standalone/Algorithms/Graph.cpp new file mode 100644 index 0000000..a6b4579 --- /dev/null +++ b/tests/standalone/Algorithms/Graph.cpp @@ -0,0 +1,304 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +struct HugeMockGraph { + std::size_t count{0}; + [[nodiscard]] std::size_t vertex_count() const noexcept { return count; } + [[nodiscard]] std::span neighbors(std::size_t) const noexcept { return {}; } +}; + +struct VersionedChainGraph { + std::vector> adj; + mutable std::atomic ver{1}; + std::size_t mutate_after_reads{std::numeric_limits::max()}; + mutable std::size_t reads{0}; + + [[nodiscard]] std::size_t vertex_count() const noexcept { return adj.size(); } + [[nodiscard]] std::uint64_t version() const noexcept + { + return ver.load(std::memory_order_acquire); + } + + [[nodiscard]] std::span neighbors(std::size_t u) const noexcept + { + const std::size_t r = ++reads; + if (r >= mutate_after_reads) { + ver.fetch_add(1, std::memory_order_release); + } + return adj[u]; + } +}; + +struct CancellingGraph { + std::vector> adj; + std::stop_source* stop_src{nullptr}; + std::size_t cancel_after_reads{std::numeric_limits::max()}; + mutable std::size_t reads{0}; + + [[nodiscard]] std::size_t vertex_count() const noexcept { return adj.size(); } + + [[nodiscard]] std::span neighbors(std::size_t u) const noexcept + { + const std::size_t r = ++reads; + if (stop_src != nullptr && r >= cancel_after_reads) { + stop_src->request_stop(); + } + return adj[u]; + } +}; + +} // namespace + +Void::Testing::Test graph_bfs_dfs_shortest_path_and_csr_views() +{ + using Void::Algorithms::AdjacencyView; + using Void::Algorithms::AlgorithmError; + using Void::Algorithms::bfs; + using Void::Algorithms::dfs; + using Void::Algorithms::shortest_path_unweighted; + + // 0 -> {1, 2}, 1 -> {3, 4}, 2 -> {4}, 3 -> {5}, 4 -> {}, 5 -> {}, 6 (isolated) + const std::vector> adj{ + {1, 2}, + {3, 4}, + {4}, + {5}, + {}, + {}, + {}, + }; + const AdjacencyView list_view{adj}; + + const auto bfs_res = bfs(list_view, 0); + Void::Testing::require(bfs_res.has_value()); + Void::Testing::expect_eq(bfs_res->order.size(), std::size_t{6}); + Void::Testing::expect_eq(bfs_res->order[0], std::size_t{0}); + Void::Testing::expect_eq(bfs_res->depth[5], std::size_t{3}); + Void::Testing::expect_eq(bfs_res->depth[6], Void::Algorithms::TraversalResult::npos); + Void::Testing::expect_eq(bfs_res->parent[4], std::size_t{1}); + + const auto dfs_res = dfs(list_view, 0); + Void::Testing::require(dfs_res.has_value()); + Void::Testing::expect_eq(dfs_res->order.size(), std::size_t{6}); + Void::Testing::expect_eq(dfs_res->order[0], std::size_t{0}); + Void::Testing::expect_eq(dfs_res->order[1], std::size_t{1}); + Void::Testing::expect_eq(dfs_res->order[2], std::size_t{3}); + Void::Testing::expect_eq(dfs_res->order[3], std::size_t{5}); + Void::Testing::expect_eq(dfs_res->order[4], std::size_t{4}); + Void::Testing::expect_eq(dfs_res->order[5], std::size_t{2}); + + const auto sp_found = shortest_path_unweighted(list_view, 0, 5); + Void::Testing::require(sp_found.has_value()); + Void::Testing::expect(sp_found->found); + Void::Testing::expect_eq(sp_found->distance, std::size_t{3}); + Void::Testing::expect_eq(sp_found->path.size(), std::size_t{4}); + Void::Testing::expect_eq(sp_found->path[0], std::size_t{0}); + Void::Testing::expect_eq(sp_found->path[1], std::size_t{1}); + Void::Testing::expect_eq(sp_found->path[2], std::size_t{3}); + Void::Testing::expect_eq(sp_found->path[3], std::size_t{5}); + + const auto sp_self = shortest_path_unweighted(list_view, 2, 2); + Void::Testing::require(sp_self.has_value()); + Void::Testing::expect(sp_self->found); + Void::Testing::expect_eq(sp_self->distance, std::size_t{0}); + Void::Testing::expect_eq(sp_self->path.size(), std::size_t{1}); + + const auto sp_missing = shortest_path_unweighted(list_view, 0, 6); + Void::Testing::require(sp_missing.has_value()); + Void::Testing::expect(!sp_missing->found); + Void::Testing::expect(sp_missing->path.empty()); + + // Equivalent CSR view validation + const std::vector offsets{0, 2, 4, 5, 6, 6, 6, 6}; + const std::vector edges{1, 2, 3, 4, 4, 5}; + const auto csr_res = AdjacencyView::try_from_csr(offsets, edges); + Void::Testing::require(csr_res.has_value()); + const auto csr_sp = shortest_path_unweighted(*csr_res, 0, 4); + Void::Testing::require(csr_sp.has_value()); + Void::Testing::expect_eq(csr_sp->distance, std::size_t{2}); + + // Malformed CSR rejected + const std::vector bad_offsets{0, 3, 2}; + Void::Testing::expect( + AdjacencyView::try_from_csr(bad_offsets, edges).error().code == + AlgorithmError::Code::invalid_input); +} + +Void::Testing::Test graph_topological_order_and_cycle_witness() +{ + using Void::Algorithms::AdjacencyView; + using Void::Algorithms::AlgorithmError; + using Void::Algorithms::topological_order; + + // Empty graph is a valid DAG + const std::vector> empty_adj{}; + const auto empty_topo = topological_order(AdjacencyView{empty_adj}); + Void::Testing::require(empty_topo.has_value()); + Void::Testing::expect(empty_topo->order.empty()); + + // DAG: 0 -> {1, 2}, 1 -> {3}, 2 -> {3}, 3 -> {4} + const std::vector> dag{ + {1, 2}, + {3}, + {3}, + {4}, + {}, + }; + const auto topo = topological_order(AdjacencyView{dag}); + Void::Testing::require(topo.has_value()); + Void::Testing::expect_eq(topo->order.size(), std::size_t{5}); + for (std::size_t u = 0; u < dag.size(); ++u) { + for (const std::size_t v : dag[u]) { + Void::Testing::expect(topo->position[u] < topo->position[v]); + } + } + + // Cyclic graph: 0 -> 1 -> 2 -> 3 -> 1 plus tail 4 + const std::vector> cyclic{ + {1}, + {2}, + {3}, + {1, 4}, + {}, + }; + const AdjacencyView cyclic_view{cyclic}; + const auto cyc_res = topological_order(cyclic_view); + Void::Testing::expect(!cyc_res.has_value()); + Void::Testing::expect(cyc_res.error().code == AlgorithmError::Code::cycle_detected); + const auto& witness = cyc_res.error().cycle; + Void::Testing::require(witness.size() >= 2); + Void::Testing::expect_eq(witness.front(), witness.back()); + // Every consecutive pair in witness must be a real edge in the graph + for (std::size_t i = 0; i + 1 < witness.size(); ++i) { + const auto nbrs = cyclic_view.neighbors(witness[i]); + bool found_edge = false; + for (const std::size_t x : nbrs) { + if (x == witness[i + 1]) { + found_edge = true; + break; + } + } + Void::Testing::expect(found_edge); + } + + // Self-loop cycle witness [u, u] + const std::vector> self_loop{{0}}; + const auto self_res = topological_order(AdjacencyView{self_loop}); + Void::Testing::expect(!self_res.has_value()); + Void::Testing::expect(self_res.error().code == AlgorithmError::Code::cycle_detected); + Void::Testing::expect_eq(self_res.error().cycle.size(), std::size_t{2}); + Void::Testing::expect_eq(self_res.error().cycle[0], std::size_t{0}); + Void::Testing::expect_eq(self_res.error().cycle[1], std::size_t{0}); +} + +Void::Testing::Test graph_bounds_limits_overflow_and_deep_chain() +{ + using Void::Algorithms::AdjacencyView; + using Void::Algorithms::AlgorithmError; + using Void::Algorithms::WorkLimits; + using Void::Algorithms::bfs; + using Void::Algorithms::dfs; + using Void::Algorithms::shortest_path_unweighted; + using Void::Algorithms::topological_order; + + // Overflow before scratch allocation on absurd vertex_count() + const HugeMockGraph huge{std::numeric_limits::max()}; + const WorkLimits huge_v_limits{ + .max_vertices = std::numeric_limits::max(), + .max_scratch_bytes = std::numeric_limits::max(), + }; + const auto ovf = bfs(huge, 0, huge_v_limits); + Void::Testing::expect(!ovf.has_value()); + Void::Testing::expect(ovf.error().code == AlgorithmError::Code::overflow); + + // Scratch memory limit exceeded cleanly + const std::vector> small{{1}, {}}; + const auto small_scratch = bfs( + AdjacencyView{small}, + 0, + WorkLimits{.max_scratch_bytes = 8}); + Void::Testing::expect(!small_scratch.has_value()); + Void::Testing::expect(small_scratch.error().code == AlgorithmError::Code::limit_exceeded); + + // Out-of-range neighbor index rejected safely without UB + const std::vector> bad_edge{{99}, {}}; + const auto bad_nbr = bfs(AdjacencyView{bad_edge}, 0); + Void::Testing::expect(!bad_nbr.has_value()); + Void::Testing::expect(bad_nbr.error().code == AlgorithmError::Code::invalid_vertex); + + // Step budget limit exceeded cleanly + const std::vector> path4{{1}, {2}, {3}, {}}; + const auto step_limited = bfs( + AdjacencyView{path4}, + 0, + WorkLimits{.max_steps = 2}); + Void::Testing::expect(!step_limited.has_value()); + Void::Testing::expect(step_limited.error().code == AlgorithmError::Code::limit_exceeded); + + // Deep chain (> 100,000 vertices) runs iteratively with no stack overflow + constexpr std::size_t kDeepCount = 110'000; + std::vector> deep(kDeepCount); + for (std::size_t i = 0; i + 1 < kDeepCount; ++i) { + deep[i].push_back(i + 1); + } + const AdjacencyView deep_view{deep}; + const auto deep_dfs = dfs(deep_view, 0); + Void::Testing::require(deep_dfs.has_value()); + Void::Testing::expect_eq(deep_dfs->order.size(), kDeepCount); + Void::Testing::expect_eq(deep_dfs->depth[kDeepCount - 1], kDeepCount - 1); + + const auto deep_topo = topological_order(deep_view); + Void::Testing::require(deep_topo.has_value()); + Void::Testing::expect_eq(deep_topo->order.size(), kDeepCount); + Void::Testing::expect_eq(deep_topo->order.back(), kDeepCount - 1); + + const auto deep_sp = shortest_path_unweighted(deep_view, 0, kDeepCount - 1); + Void::Testing::require(deep_sp.has_value()); + Void::Testing::expect_eq(deep_sp->distance, kDeepCount - 1); +} + +Void::Testing::Test graph_cancellation_and_version_mutation_checks() +{ + using Void::Algorithms::AlgorithmError; + using Void::Algorithms::WorkLimits; + using Void::Algorithms::bfs; + using Void::Algorithms::topological_order; + + // Concurrent version mutation detected mid-traversal + VersionedChainGraph mutated{ + .adj = {{1}, {2}, {3}, {4}, {5}, {}}, + .mutate_after_reads = 2, + }; + const auto mod_res = bfs( + mutated, + 0, + WorkLimits{.cancel_check_interval = 1}); + Void::Testing::expect(!mod_res.has_value()); + Void::Testing::expect(mod_res.error().code == AlgorithmError::Code::concurrent_modification); + + // Cooperative cancellation via std::stop_token + std::stop_source src; + CancellingGraph cg{ + .adj = {{1}, {2}, {3}, {4}, {}}, + .stop_src = &src, + .cancel_after_reads = 2, + }; + const auto cancel_res = topological_order( + cg, + WorkLimits{.cancel_check_interval = 1}, + src.get_token()); + Void::Testing::expect(!cancel_res.has_value()); + Void::Testing::expect(cancel_res.error().code == AlgorithmError::Code::cancelled); +} \ No newline at end of file From 4369fde867076bc01a9f89200559e481a019af33 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:38:53 +0300 Subject: [PATCH 3/5] feat(Unicode): add Unicode 17.0.0 manifest and strict/repair/streaming UTF codecs (S-UNICODE-01, S-UNICODE-02) --- docs/agent-workflow/tasks/S-UNICODE-01-02.md | 2 +- include/Void/Unicode/Utf.hpp | 1319 ++++++++++++++++++ src/Unicode/MANIFEST.md | 11 + src/Unicode/module.cmake | 3 + tests/package/InstalledComponents.cmake | 5 + tests/package/UnicodeOnly/CMakeLists.txt | 10 + tests/package/UnicodeOnly/main.cpp | 16 + tests/standalone/Unicode/Utf.cpp | 269 ++++ 8 files changed, 1634 insertions(+), 1 deletion(-) create mode 100644 include/Void/Unicode/Utf.hpp create mode 100644 src/Unicode/MANIFEST.md create mode 100644 src/Unicode/module.cmake create mode 100644 tests/package/UnicodeOnly/CMakeLists.txt create mode 100644 tests/package/UnicodeOnly/main.cpp create mode 100644 tests/standalone/Unicode/Utf.cpp diff --git a/docs/agent-workflow/tasks/S-UNICODE-01-02.md b/docs/agent-workflow/tasks/S-UNICODE-01-02.md index 179e227..7a1d75d 100644 --- a/docs/agent-workflow/tasks/S-UNICODE-01-02.md +++ b/docs/agent-workflow/tasks/S-UNICODE-01-02.md @@ -25,7 +25,7 @@ VoidLibrary currently has no `Unicode` module (`src/Unicode/`). `Text` handles l ## 4. Edge cases - Rejects overlong UTF-8 sequences, UTF-16 surrogates (`U+D800..U+DFFF`) in UTF-8/UTF-32, unpaired surrogates in UTF-16, code points `> U+10FFFF`, and truncated sequences under `UtfPolicy::reject`. -- WHATWG-compliant maximal subpart (`replace_one_unit`) emits `U+FFFD` per ill-formed unit/maximal subpart and advances cleanly without skipping subsequent valid units. +- One-unit repair (`replace_one_unit`) emits `U+FFFD` per ill-formed unit and advances cleanly by one code unit without skipping subsequent valid units; streaming chunk boundaries match one-shot behavior identically. - Pre-reserve limit checks against `UtfLimits` reject oversized inputs/outputs before large allocations; periodic `std::stop_token` checks abort long transcodes cleanly. - Streaming `Utf8StreamDecoder` / `Utf16StreamDecoder` split sequences across arbitrary 1-byte/1-unit boundaries and flush trailing incomplete sequences cleanly at EOF. diff --git a/include/Void/Unicode/Utf.hpp b/include/Void/Unicode/Utf.hpp new file mode 100644 index 0000000..8b11c6e --- /dev/null +++ b/include/Void/Unicode/Utf.hpp @@ -0,0 +1,1319 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Unicode +{ + +[[nodiscard]] constexpr std::string_view data_version() noexcept +{ + return "17.0.0"; +} + +[[nodiscard]] constexpr bool is_scalar_value(char32_t cp) noexcept +{ + return cp <= 0x10FFFFu && (cp < 0xD800u || cp > 0xDFFFu); +} + +enum class UtfPolicy { + reject, + replace_one_unit +}; + +enum class UtfErrorKind { + invalid_utf8, + invalid_utf16, + invalid_scalar, + truncated, + limit_exceeded, + output_too_small, + overflow, + cancelled +}; + +struct UtfError { + UtfErrorKind kind{UtfErrorKind::invalid_utf8}; + std::size_t unit_offset{0}; + std::string message{}; +}; + +struct UtfLimits { + std::size_t max_input_units{16ULL * 1024ULL * 1024ULL}; + std::size_t max_output_units{64ULL * 1024ULL * 1024ULL}; + std::size_t cancel_check_interval{4096}; +}; + +struct TranscodeCounts { + std::size_t units_read{0}; + std::size_t units_written{0}; + std::size_t scalars_decoded{0}; + std::size_t replacements{0}; +}; + +class Scalar +{ +public: + constexpr Scalar() noexcept = default; + + [[nodiscard]] static constexpr std::expected + from_code_point(char32_t cp) noexcept + { + if (!is_scalar_value(cp)) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_scalar, + 0, + "Code point is outside Unicode scalar value range"}}; + } + return Scalar{cp}; + } + + [[nodiscard]] static constexpr Scalar replacement_character() noexcept + { + return Scalar{0xFFFDu}; + } + + [[nodiscard]] constexpr char32_t code_point() const noexcept { return value_; } + [[nodiscard]] constexpr explicit operator char32_t() const noexcept { return value_; } + + friend constexpr bool operator==(Scalar, Scalar) noexcept = default; + +private: + explicit constexpr Scalar(char32_t cp) noexcept + : value_(cp) + { + } + + char32_t value_{0}; +}; + +namespace detail +{ + +[[nodiscard]] constexpr bool check_cancel(const std::stop_token& stop_token, + std::size_t steps, + const UtfLimits& limits, + std::size_t offset) +{ + if (limits.cancel_check_interval > 0 && + (steps % limits.cancel_check_interval) == 0 && + stop_token.stop_requested()) { + return false; + } + (void)offset; + return true; +} + +[[nodiscard]] constexpr std::size_t utf8_length(char32_t cp) noexcept +{ + if (cp <= 0x7Fu) { + return 1; + } + if (cp <= 0x7FFu) { + return 2; + } + if (cp <= 0xFFFFu) { + return 3; + } + return 4; +} + +[[nodiscard]] constexpr std::size_t utf16_length(char32_t cp) noexcept +{ + return (cp <= 0xFFFFu) ? 1 : 2; +} + +constexpr void write_utf8_unchecked(char32_t cp, std::span out) noexcept +{ + if (cp <= 0x7Fu) { + out[0] = static_cast(cp); + } else if (cp <= 0x7FFu) { + out[0] = static_cast(0xC0u | (cp >> 6)); + out[1] = static_cast(0x80u | (cp & 0x3Fu)); + } else if (cp <= 0xFFFFu) { + out[0] = static_cast(0xE0u | (cp >> 12)); + out[1] = static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out[2] = static_cast(0x80u | (cp & 0x3Fu)); + } else { + out[0] = static_cast(0xF0u | (cp >> 18)); + out[1] = static_cast(0x80u | ((cp >> 12) & 0x3Fu)); + out[2] = static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out[3] = static_cast(0x80u | (cp & 0x3Fu)); + } +} + +constexpr void write_utf16_unchecked(char32_t cp, std::span out) noexcept +{ + if (cp <= 0xFFFFu) { + out[0] = static_cast(cp); + } else { + const char32_t adj = cp - 0x10000u; + out[0] = static_cast(0xD800u + (adj >> 10)); + out[1] = static_cast(0xDC00u + (adj & 0x3FFu)); + } +} + +[[nodiscard]] constexpr bool is_utf8_cont(std::uint8_t b) noexcept +{ + return b >= 0x80u && b <= 0xBFu; +} + +enum class StepStatus { + ok, + incomplete, + invalid +}; + +struct Utf8Step { + StepStatus status{StepStatus::invalid}; + Scalar scalar{}; + std::size_t consumed{1}; +}; + +[[nodiscard]] constexpr Utf8Step inspect_utf8(std::span bytes) noexcept +{ + if (bytes.empty()) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b0 = bytes[0]; + if (b0 <= 0x7Fu) { + return Utf8Step{ + StepStatus::ok, + *Scalar::from_code_point(static_cast(b0)), + 1}; + } + if (b0 >= 0xC2u && b0 <= 0xDFu) { + if (bytes.size() < 2) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b1 = bytes[1]; + if (!is_utf8_cont(b1)) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + const char32_t cp = + (static_cast(b0 & 0x1Fu) << 6) | + static_cast(b1 & 0x3Fu); + return Utf8Step{StepStatus::ok, *Scalar::from_code_point(cp), 2}; + } + if (b0 >= 0xE0u && b0 <= 0xEFu) { + if (bytes.size() < 2) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b1 = bytes[1]; + const std::uint8_t lo = (b0 == 0xE0u) ? 0xA0u : 0x80u; + const std::uint8_t hi = (b0 == 0xEDu) ? 0x9Fu : 0xBFu; + if (b1 < lo || b1 > hi) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + if (bytes.size() < 3) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b2 = bytes[2]; + if (!is_utf8_cont(b2)) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + const char32_t cp = + (static_cast(b0 & 0x0Fu) << 12) | + (static_cast(b1 & 0x3Fu) << 6) | + static_cast(b2 & 0x3Fu); + return Utf8Step{StepStatus::ok, *Scalar::from_code_point(cp), 3}; + } + if (b0 >= 0xF0u && b0 <= 0xF4u) { + if (bytes.size() < 2) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b1 = bytes[1]; + const std::uint8_t lo = (b0 == 0xF0u) ? 0x90u : 0x80u; + const std::uint8_t hi = (b0 == 0xF4u) ? 0x8Fu : 0xBFu; + if (b1 < lo || b1 > hi) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + if (bytes.size() < 3) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + if (!is_utf8_cont(bytes[2])) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + if (bytes.size() < 4) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + if (!is_utf8_cont(bytes[3])) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + const char32_t cp = + (static_cast(b0 & 0x07u) << 18) | + (static_cast(b1 & 0x3Fu) << 12) | + (static_cast(bytes[2] & 0x3Fu) << 6) | + static_cast(bytes[3] & 0x3Fu); + return Utf8Step{StepStatus::ok, *Scalar::from_code_point(cp), 4}; + } + return Utf8Step{StepStatus::invalid, {}, 1}; +} + +template +[[nodiscard]] inline std::expected + decode_utf8_each(std::string_view input, + UtfPolicy policy, + const UtfLimits& limits, + const std::stop_token& stop_token, + EmitFn&& emit) +{ + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + 0, + "Unicode operation cancelled"}}; + } + if (input.size() > limits.max_input_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + 0, + "Input size exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + std::size_t i = 0; + std::size_t steps = 0; + while (i < input.size()) { + if (!check_cancel(stop_token, steps++, limits, i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + i, + "Unicode operation cancelled"}}; + } + const std::size_t avail = std::min(4, input.size() - i); + std::array buf{}; + for (std::size_t k = 0; k < avail; ++k) { + buf[k] = static_cast(input[i + k]); + } + const Utf8Step st = inspect_utf8(std::span{buf.data(), avail}); + if (st.status == StepStatus::ok) { + const auto r = emit(st.scalar, false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + i += st.consumed; + } else { + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + (st.status == StepStatus::incomplete) + ? UtfErrorKind::truncated + : UtfErrorKind::invalid_utf8, + i, + (st.status == StepStatus::incomplete) + ? "Truncated UTF-8 sequence" + : "Invalid UTF-8 byte sequence"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + } + } + counts.units_read = i; + return counts; +} + +template +[[nodiscard]] inline std::expected + decode_utf16_each(std::u16string_view input, + UtfPolicy policy, + const UtfLimits& limits, + const std::stop_token& stop_token, + EmitFn&& emit) +{ + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + 0, + "Unicode operation cancelled"}}; + } + if (input.size() > limits.max_input_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + 0, + "Input size exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + std::size_t i = 0; + std::size_t steps = 0; + while (i < input.size()) { + if (!check_cancel(stop_token, steps++, limits, i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + i, + "Unicode operation cancelled"}}; + } + const std::uint16_t u0 = static_cast(input[i]); + if (u0 < 0xD800u || u0 > 0xDFFFu) { + const auto sc = *Scalar::from_code_point(static_cast(u0)); + const auto r = emit(sc, false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + i += 1; + continue; + } + if (u0 <= 0xDBFFu) { + if (i + 1 >= input.size()) { + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::truncated, + i, + "Truncated high surrogate in UTF-16 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + continue; + } + const std::uint16_t u1 = static_cast(input[i + 1]); + if (u1 >= 0xDC00u && u1 <= 0xDFFFu) { + const char32_t cp = + 0x10000u + + ((static_cast(u0 - 0xD800u) << 10) | + static_cast(u1 - 0xDC00u)); + const auto r = emit(*Scalar::from_code_point(cp), false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + i += 2; + continue; + } + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + i, + "Unpaired high surrogate in UTF-16 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + continue; + } + // Unpaired low surrogate 0xDC00..0xDFFF + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + i, + "Unpaired low surrogate in UTF-16 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + } + counts.units_read = i; + return counts; +} + +template +[[nodiscard]] inline std::expected + decode_utf32_each(std::u32string_view input, + UtfPolicy policy, + const UtfLimits& limits, + const std::stop_token& stop_token, + EmitFn&& emit) +{ + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + 0, + "Unicode operation cancelled"}}; + } + if (input.size() > limits.max_input_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + 0, + "Input size exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + for (std::size_t i = 0; i < input.size(); ++i) { + if (!check_cancel(stop_token, i, limits, i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + i, + "Unicode operation cancelled"}}; + } + const char32_t cp = input[i]; + if (is_scalar_value(cp)) { + const auto r = emit(*Scalar::from_code_point(cp), false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + } else { + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_scalar, + i, + "Invalid code point in UTF-32 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + } + } + counts.units_read = input.size(); + return counts; +} + +template +[[nodiscard]] inline auto make_string_sink(std::basic_string& dest, + std::size_t max_output_units) +{ + return [&dest, max_output_units](Scalar sc, + bool, + std::size_t in_offset) -> std::expected { + const char32_t cp = sc.code_point(); + if constexpr (sizeof(CharT) == 1) { + const std::size_t need = utf8_length(cp); + if (need > max_output_units - dest.size()) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + std::array tmp{}; + write_utf8_unchecked(cp, std::span{tmp.data(), need}); + dest.append(tmp.data(), need); + return need; + } else if constexpr (sizeof(CharT) == 2) { + const std::size_t need = utf16_length(cp); + if (need > max_output_units - dest.size()) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + std::array tmp{}; + write_utf16_unchecked(cp, std::span{tmp.data(), need}); + dest.append(tmp.data(), need); + return need; + } else { + if (1 > max_output_units - dest.size()) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + dest.push_back(cp); + return std::size_t{1}; + } + }; +} + +template +[[nodiscard]] inline auto make_span_sink(std::span out, + std::size_t& cursor, + std::size_t max_output_units) +{ + return [out, &cursor, max_output_units](Scalar sc, + bool, + std::size_t in_offset) -> std::expected { + const char32_t cp = sc.code_point(); + std::size_t need = 1; + if constexpr (sizeof(CharT) == 1) { + need = utf8_length(cp); + } else if constexpr (sizeof(CharT) == 2) { + need = utf16_length(cp); + } + if (need > max_output_units - cursor) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + if (need > out.size() - cursor) { + return std::unexpected{UtfError{ + UtfErrorKind::output_too_small, + in_offset, + "Destination span too small for transcoded output"}}; + } + if constexpr (sizeof(CharT) == 1) { + write_utf8_unchecked(cp, out.subspan(cursor, need)); + } else if constexpr (sizeof(CharT) == 2) { + write_utf16_unchecked(cp, out.subspan(cursor, need)); + } else { + out[cursor] = cp; + } + cursor += need; + return need; + }; +} + +} // namespace detail + +[[nodiscard]] constexpr std::expected + encode_utf8(Scalar s, std::span out) noexcept +{ + const std::size_t need = detail::utf8_length(s.code_point()); + if (out.size() < need) { + return std::unexpected{UtfError{ + UtfErrorKind::output_too_small, + 0, + "Output buffer too small for UTF-8 scalar"}}; + } + detail::write_utf8_unchecked(s.code_point(), out.first(need)); + return need; +} + +[[nodiscard]] constexpr std::expected + encode_utf16(Scalar s, std::span out) noexcept +{ + const std::size_t need = detail::utf16_length(s.code_point()); + if (out.size() < need) { + return std::unexpected{UtfError{ + UtfErrorKind::output_too_small, + 0, + "Output buffer too small for UTF-16 scalar"}}; + } + detail::write_utf16_unchecked(s.code_point(), out.first(need)); + return need; +} + +[[nodiscard]] inline std::expected + validate_utf8(std::string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t emitted = 0; + return detail::decode_utf8_each( + input, + UtfPolicy::reject, + limits, + stop_token, + [&](Scalar s, bool, std::size_t off) -> std::expected { + const std::size_t n = detail::utf8_length(s.code_point()); + if (n > limits.max_output_units - emitted) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Validated byte count exceeds UtfLimits::max_output_units"}}; + } + emitted += n; + return n; + }); +} + +[[nodiscard]] inline std::expected + validate_utf16(std::u16string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t emitted = 0; + return detail::decode_utf16_each( + input, + UtfPolicy::reject, + limits, + stop_token, + [&](Scalar s, bool, std::size_t off) -> std::expected { + const std::size_t n = detail::utf16_length(s.code_point()); + if (n > limits.max_output_units - emitted) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Validated unit count exceeds UtfLimits::max_output_units"}}; + } + emitted += n; + return n; + }); +} + +[[nodiscard]] inline std::expected + validate_utf32(std::u32string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t emitted = 0; + return detail::decode_utf32_each( + input, + UtfPolicy::reject, + limits, + stop_token, + [&](Scalar, bool, std::size_t off) -> std::expected { + if (1 > limits.max_output_units - emitted) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Validated unit count exceeds UtfLimits::max_output_units"}}; + } + emitted += 1; + return std::size_t{1}; + }); +} + +// ── Owning transcoders ─────────────────────────────────────────────────────── + +[[nodiscard]] inline std::expected + utf8_repair(std::string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf8_each( + input, + UtfPolicy::replace_one_unit, + limits, + stop_token, + detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf8_to_utf16(std::string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u16string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf8_to_utf32(std::string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u32string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf16_to_utf8(std::u16string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::string out; + const std::size_t est = + (input.size() <= limits.max_output_units / 3) + ? (input.size() * 3) + : limits.max_output_units; + out.reserve(est); + auto res = detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf16_to_utf32(std::u16string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u32string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf32_to_utf8(std::u32string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::string out; + const std::size_t est = + (input.size() <= limits.max_output_units / 4) + ? (input.size() * 4) + : limits.max_output_units; + out.reserve(est); + auto res = detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf32_to_utf16(std::u32string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u16string out; + const std::size_t est = + (input.size() <= limits.max_output_units / 2) + ? (input.size() * 2) + : limits.max_output_units; + out.reserve(est); + auto res = detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +// ── Non-allocating into-span transcoders ───────────────────────────────────── + +[[nodiscard]] inline std::expected + utf8_to_utf16_into(std::string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf8_to_utf32_into(std::string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf16_to_utf8_into(std::u16string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf16_to_utf32_into(std::u16string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf32_to_utf8_into(std::u32string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf32_to_utf16_into(std::u32string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +// ── Streaming Decoders ─────────────────────────────────────────────────────── + +class Utf8StreamDecoder +{ +public: + explicit Utf8StreamDecoder(UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}) noexcept + : policy_(policy) + , limits_(limits) + { + } + + template + [[nodiscard]] std::expected + push(std::string_view chunk, + EmitFn&& on_scalar, + std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-8 decode cancelled"}}; + } + if (chunk.size() > limits_.max_input_units - total_read_) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + total_read_, + "Streaming UTF-8 input exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts chunk_counts{}; + std::size_t i = 0; + std::size_t steps = 0; + + auto emit_scalar = [&](Scalar s, bool replaced, std::size_t off) + -> std::expected { + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-8 output exceeds UtfLimits::max_output_units"}}; + } + on_scalar(s); + total_written_ += 1; + chunk_counts.scalars_decoded += 1; + chunk_counts.units_written += 1; + if (replaced) { + chunk_counts.replacements += 1; + } + return {}; + }; + + auto pop_front_pending = [&](std::size_t count) noexcept { + for (std::size_t k = count; k < pending_len_; ++k) { + pending_[k - count] = pending_[k]; + } + pending_len_ -= count; + }; + + // Drain any buffered partial prefix from previous chunks first. + while (pending_len_ > 0 && i < chunk.size()) { + if (!detail::check_cancel(stop_token, steps++, limits_, total_read_ + i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_ + i, + "Streaming UTF-8 decode cancelled"}}; + } + while (pending_len_ < 4 && i < chunk.size()) { + pending_[pending_len_++] = static_cast(chunk[i++]); + } + const auto st = detail::inspect_utf8( + std::span{pending_.data(), pending_len_}); + if (st.status == detail::StepStatus::ok) { + const std::size_t start_off = total_read_ + i - pending_len_; + if (auto r = emit_scalar(st.scalar, false, start_off); !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(st.consumed); + // Any leftover bytes in pending_ were from chunk, not yet decoded; keep looping. + } else if (st.status == detail::StepStatus::incomplete) { + // Still need more bytes and chunk is exhausted. + break; + } else { + const std::size_t err_off = total_read_ + i - pending_len_; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf8, + err_off, + "Invalid UTF-8 sequence in stream"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, err_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(1); + } + } + + // If leftover validated-free bytes moved from chunk into pending_ still need decoding + // (e.g. a complete scalar was resolved inside pending_ and 1..3 bytes remain): + while (pending_len_ > 0 && i == chunk.size()) { + const auto st = detail::inspect_utf8( + std::span{pending_.data(), pending_len_}); + if (st.status == detail::StepStatus::ok) { + const std::size_t start_off = total_read_ + i - pending_len_; + if (auto r = emit_scalar(st.scalar, false, start_off); !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(st.consumed); + } else if (st.status == detail::StepStatus::invalid) { + const std::size_t err_off = total_read_ + i - pending_len_; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf8, + err_off, + "Invalid UTF-8 sequence in stream"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, err_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(1); + } else { + break; + } + } + + // Process the remainder of `chunk` directly once pending_ is empty. + while (i < chunk.size()) { + if (!detail::check_cancel(stop_token, steps++, limits_, total_read_ + i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_ + i, + "Streaming UTF-8 decode cancelled"}}; + } + const std::size_t avail = std::min(4, chunk.size() - i); + std::array buf{}; + for (std::size_t k = 0; k < avail; ++k) { + buf[k] = static_cast(chunk[i + k]); + } + const auto st = detail::inspect_utf8(std::span{buf.data(), avail}); + if (st.status == detail::StepStatus::ok) { + if (auto r = emit_scalar(st.scalar, false, total_read_ + i); !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += st.consumed; + } else if (st.status == detail::StepStatus::incomplete) { + for (std::size_t k = 0; k < avail; ++k) { + pending_[pending_len_++] = buf[k]; + } + i += avail; + } else { + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf8, + total_read_ + i, + "Invalid UTF-8 sequence in stream"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } + } + + total_read_ += chunk.size(); + chunk_counts.units_read = chunk.size(); + return chunk_counts; + } + + template + [[nodiscard]] std::expected + finish(EmitFn&& on_scalar, std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-8 finish cancelled"}}; + } + TranscodeCounts counts{}; + while (pending_len_ > 0) { + const std::size_t off = total_read_ - pending_len_; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::truncated, + off, + "Truncated trailing UTF-8 bytes at end of stream"}}; + } + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-8 output exceeds UtfLimits::max_output_units"}}; + } + on_scalar(Scalar::replacement_character()); + total_written_ += 1; + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += 1; + for (std::size_t k = 1; k < pending_len_; ++k) { + pending_[k - 1] = pending_[k]; + } + pending_len_ -= 1; + } + return counts; + } + + [[nodiscard]] bool has_pending() const noexcept { return pending_len_ > 0; } + [[nodiscard]] std::size_t bytes_read() const noexcept { return total_read_; } + + void reset() noexcept + { + pending_.fill(0); + pending_len_ = 0; + total_read_ = 0; + total_written_ = 0; + } + +private: + UtfPolicy policy_{UtfPolicy::reject}; + UtfLimits limits_{}; + std::array pending_{}; + std::size_t pending_len_{0}; + std::size_t total_read_{0}; + std::size_t total_written_{0}; +}; + +class Utf16StreamDecoder +{ +public: + explicit Utf16StreamDecoder(UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}) noexcept + : policy_(policy) + , limits_(limits) + { + } + + template + [[nodiscard]] std::expected + push(std::u16string_view chunk, + EmitFn&& on_scalar, + std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-16 decode cancelled"}}; + } + if (chunk.size() > limits_.max_input_units - total_read_) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + total_read_, + "Streaming UTF-16 input exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + std::size_t i = 0; + std::size_t steps = 0; + + auto emit_scalar = [&](Scalar s, bool replaced, std::size_t off) + -> std::expected { + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-16 output exceeds UtfLimits::max_output_units"}}; + } + on_scalar(s); + total_written_ += 1; + counts.scalars_decoded += 1; + counts.units_written += 1; + if (replaced) { + counts.replacements += 1; + } + return {}; + }; + + if (has_high_ && !chunk.empty()) { + const std::uint16_t u1 = static_cast(chunk[0]); + const std::size_t high_off = total_read_ - 1; + if (u1 >= 0xDC00u && u1 <= 0xDFFFu) { + const char32_t cp = + 0x10000u + + ((static_cast(pending_high_ - 0xD800u) << 10) | + static_cast(u1 - 0xDC00u)); + has_high_ = false; + if (auto r = emit_scalar(*Scalar::from_code_point(cp), false, high_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i = 1; + } else { + has_high_ = false; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + high_off, + "Unpaired high surrogate across UTF-16 stream boundary"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, high_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + } + } + + while (i < chunk.size()) { + if (!detail::check_cancel(stop_token, steps++, limits_, total_read_ + i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_ + i, + "Streaming UTF-16 decode cancelled"}}; + } + const std::uint16_t u0 = static_cast(chunk[i]); + if (u0 < 0xD800u || u0 > 0xDFFFu) { + if (auto r = emit_scalar(*Scalar::from_code_point(u0), false, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } else if (u0 <= 0xDBFFu) { + if (i + 1 >= chunk.size()) { + pending_high_ = u0; + has_high_ = true; + i += 1; + } else { + const std::uint16_t u1 = static_cast(chunk[i + 1]); + if (u1 >= 0xDC00u && u1 <= 0xDFFFu) { + const char32_t cp = + 0x10000u + + ((static_cast(u0 - 0xD800u) << 10) | + static_cast(u1 - 0xDC00u)); + if (auto r = emit_scalar(*Scalar::from_code_point(cp), false, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 2; + } else { + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + total_read_ + i, + "Unpaired high surrogate in UTF-16 stream"}}; + } + if (auto r = emit_scalar( + Scalar::replacement_character(), true, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } + } + } else { + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + total_read_ + i, + "Unpaired low surrogate in UTF-16 stream"}}; + } + if (auto r = emit_scalar( + Scalar::replacement_character(), true, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } + } + + total_read_ += chunk.size(); + counts.units_read = chunk.size(); + return counts; + } + + template + [[nodiscard]] std::expected + finish(EmitFn&& on_scalar, std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-16 finish cancelled"}}; + } + TranscodeCounts counts{}; + if (has_high_) { + const std::size_t off = total_read_ - 1; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::truncated, + off, + "Trailing unpaired high surrogate at end of UTF-16 stream"}}; + } + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-16 output exceeds UtfLimits::max_output_units"}}; + } + has_high_ = false; + on_scalar(Scalar::replacement_character()); + total_written_ += 1; + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += 1; + } + return counts; + } + + [[nodiscard]] bool has_pending() const noexcept { return has_high_; } + [[nodiscard]] std::size_t units_read() const noexcept { return total_read_; } + + void reset() noexcept + { + has_high_ = false; + pending_high_ = 0; + total_read_ = 0; + total_written_ = 0; + } + +private: + UtfPolicy policy_{UtfPolicy::reject}; + UtfLimits limits_{}; + std::uint16_t pending_high_{0}; + bool has_high_{false}; + std::size_t total_read_{0}; + std::size_t total_written_{0}; +}; + +} // namespace Void::Unicode \ No newline at end of file diff --git a/src/Unicode/MANIFEST.md b/src/Unicode/MANIFEST.md new file mode 100644 index 0000000..fbb7e9f --- /dev/null +++ b/src/Unicode/MANIFEST.md @@ -0,0 +1,11 @@ +# Void::Unicode Data & Specification Manifest + +- **Unicode Standard Version**: `17.0.0` +- **Official UCD Base URL**: `https://www.unicode.org/Public/17.0.0/ucd/` +- **Encoding & Scalar Specification**: Unicode Standard Section 3.9 (Forms & UTF-8/UTF-16/UTF-32 definitions D89-D92) +- **License**: Unicode License V3 (`Unicode-3.0`, https://www.unicode.org/license.txt) + +## Scope Notes +- `Void::Unicode` P1 implements Unicode `17.0.0` scalar value classification, UTF-8 / UTF-16 / UTF-32 strict validation, bounded transcoding (owning and non-allocating `std::span` destinations), one-unit repair (`U+FFFD`), and incremental streaming decoders. +- `Void::Text` remains intentionally Unicode-free (ASCII-only helpers in `M-TEXT-02`). +- Generated UCD character property tables (normalization, grapheme cluster segmentation, casefolding) belong to subsequent phases and will append table hashes here when introduced. \ No newline at end of file diff --git a/src/Unicode/module.cmake b/src/Unicode/module.cmake new file mode 100644 index 0000000..d39e426 --- /dev/null +++ b/src/Unicode/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Unicode + INTERNAL_DEPS Core Text +) \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 043dab8..2e86573 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -101,6 +101,11 @@ if(_has_algorithms) run_consumer(AlgorithmsOnly "${install_prefix}" "AlgorithmsOnly" ${_no_external_deps}) endif() +has_modules(_has_unicode Unicode Text Core) +if(_has_unicode) + run_consumer(UnicodeOnly "${install_prefix}" "UnicodeOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/UnicodeOnly/CMakeLists.txt b/tests/package/UnicodeOnly/CMakeLists.txt new file mode 100644 index 0000000..d5c4dd9 --- /dev/null +++ b/tests/package/UnicodeOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidUnicodeOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Unicode) + +add_executable(void_unicode_only_consumer main.cpp) +target_link_libraries(void_unicode_only_consumer PRIVATE Void::Unicode) + +enable_testing() +add_test(NAME VoidUnicodeOnlyConsumer COMMAND void_unicode_only_consumer) \ No newline at end of file diff --git a/tests/package/UnicodeOnly/main.cpp b/tests/package/UnicodeOnly/main.cpp new file mode 100644 index 0000000..44dbe62 --- /dev/null +++ b/tests/package/UnicodeOnly/main.cpp @@ -0,0 +1,16 @@ +#include + +#include + +int main() +{ + if (Void::Unicode::data_version() != std::string_view{"17.0.0"}) { + return 1; + } + const auto u16 = Void::Unicode::utf8_to_utf16("hi \xF0\x9F\x9A\x80"); + if (!u16.has_value()) { + return 1; + } + const auto u8 = Void::Unicode::utf16_to_utf8(*u16); + return (u8 && *u8 == "hi \xF0\x9F\x9A\x80") ? 0 : 1; +} \ No newline at end of file diff --git a/tests/standalone/Unicode/Utf.cpp b/tests/standalone/Unicode/Utf.cpp new file mode 100644 index 0000000..2758673 --- /dev/null +++ b/tests/standalone/Unicode/Utf.cpp @@ -0,0 +1,269 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +Void::Testing::Test utf_manifest_scalars_and_roundtrips() +{ + using Void::Unicode::Scalar; + using Void::Unicode::data_version; + using Void::Unicode::encode_utf16; + using Void::Unicode::encode_utf8; + using Void::Unicode::is_scalar_value; + using Void::Unicode::utf16_to_utf32; + using Void::Unicode::utf16_to_utf8; + using Void::Unicode::utf32_to_utf16; + using Void::Unicode::utf32_to_utf8; + using Void::Unicode::utf8_to_utf16; + using Void::Unicode::utf8_to_utf32; + using Void::Unicode::validate_utf16; + using Void::Unicode::validate_utf32; + using Void::Unicode::validate_utf8; + + Void::Testing::expect_eq(data_version(), std::string_view{"17.0.0"}); + + Void::Testing::expect(is_scalar_value(U'\0')); + Void::Testing::expect(is_scalar_value(U'A')); + Void::Testing::expect(is_scalar_value(U'\u00DF')); + Void::Testing::expect(is_scalar_value(U'\u20AC')); + Void::Testing::expect(is_scalar_value(U'\U0001F680')); + Void::Testing::expect(is_scalar_value(0x10FFFFu)); + Void::Testing::expect(!is_scalar_value(0xD800u)); + Void::Testing::expect(!is_scalar_value(0xDFFFu)); + Void::Testing::expect(!is_scalar_value(0x110000u)); + + Void::Testing::expect(Scalar::from_code_point(U'A').has_value()); + Void::Testing::expect(!Scalar::from_code_point(0xD800u).has_value()); + + // Roundtrip across 1-, 2-, 3-, and 4-byte scalars plus embedded NUL. + const std::string utf8_src{"A\0\xC3\x9F\xE2\x82\xAC\xF0\x9F\x9A\x80", 11}; + const auto v8 = validate_utf8(utf8_src); + Void::Testing::require(v8.has_value()); + Void::Testing::expect_eq(v8->scalars_decoded, std::size_t{5}); + Void::Testing::expect_eq(v8->replacements, std::size_t{0}); + + const auto u16 = utf8_to_utf16(utf8_src); + Void::Testing::require(u16.has_value()); + Void::Testing::expect_eq(u16->size(), std::size_t{6}); // 4 BMP + 2 surrogate pair + Void::Testing::expect(validate_utf16(*u16).has_value()); + + const auto u32 = utf16_to_utf32(*u16); + Void::Testing::require(u32.has_value()); + Void::Testing::expect_eq(u32->size(), std::size_t{5}); + Void::Testing::expect((*u32)[4] == 0x1F680u); + Void::Testing::expect(validate_utf32(*u32).has_value()); + + const auto back_u8_from_32 = utf32_to_utf8(*u32); + Void::Testing::require(back_u8_from_32.has_value()); + Void::Testing::expect(*back_u8_from_32 == utf8_src); + + const auto back_u8_from_16 = utf16_to_utf8(*u16); + Void::Testing::require(back_u8_from_16.has_value()); + Void::Testing::expect(*back_u8_from_16 == utf8_src); + + const auto back_u16_from_32 = utf32_to_utf16(*u32); + Void::Testing::require(back_u16_from_32.has_value()); + Void::Testing::expect(*back_u16_from_32 == *u16); + + const auto direct_u32 = utf8_to_utf32(utf8_src); + Void::Testing::require(direct_u32.has_value()); + Void::Testing::expect(*direct_u32 == *u32); + + // Encode single scalar into small buffer checks + const auto rocket = *Scalar::from_code_point(0x1F680u); + std::array too_small_8{}; + Void::Testing::expect(!encode_utf8(rocket, too_small_8).has_value()); + std::array exact_8{}; + const auto enc8 = encode_utf8(rocket, exact_8); + Void::Testing::require(enc8.has_value()); + Void::Testing::expect_eq(*enc8, std::size_t{4}); + + std::array too_small_16{}; + Void::Testing::expect(!encode_utf16(rocket, too_small_16).has_value()); + std::array exact_16{}; + const auto enc16 = encode_utf16(rocket, exact_16); + Void::Testing::require(enc16.has_value()); + Void::Testing::expect_eq(*enc16, std::size_t{2}); +} + +Void::Testing::Test utf_strict_rejects_all_malformed_classes() +{ + using Void::Unicode::UtfErrorKind; + using Void::Unicode::utf16_to_utf8; + using Void::Unicode::utf32_to_utf8; + using Void::Unicode::utf8_to_utf32; + using Void::Unicode::validate_utf16; + using Void::Unicode::validate_utf32; + using Void::Unicode::validate_utf8; + + // Overlong 2-, 3-, and 4-byte UTF-8 encodings + Void::Testing::expect(validate_utf8("\xC0\xAF").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xC1\xBF").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xE0\x80\xAF").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xF0\x80\x80\xAF").error().kind == UtfErrorKind::invalid_utf8); + + // UTF-8 encoded surrogates (U+D800, U+DFFF) + Void::Testing::expect(validate_utf8("\xED\xA0\x80").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xED\xBF\xBF").error().kind == UtfErrorKind::invalid_utf8); + + // Out-of-range UTF-8 (> U+10FFFF) + Void::Testing::expect(validate_utf8("\xF4\x90\x80\x80").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xF5\x80\x80\x80").error().kind == UtfErrorKind::invalid_utf8); + + // Unexpected continuation byte and truncated tail + Void::Testing::expect(validate_utf8("ab\x80").error().unit_offset == std::size_t{2}); + const auto trunc8 = utf8_to_utf32("ok\xE2\x82"); + Void::Testing::expect(!trunc8.has_value()); + Void::Testing::expect(trunc8.error().kind == UtfErrorKind::truncated); + Void::Testing::expect_eq(trunc8.error().unit_offset, std::size_t{2}); + + // UTF-16 unpaired high/low surrogates and truncation + const std::u16string unpaired_high{u'a', char16_t{0xD800}, u'b'}; + const auto err16_hi = utf16_to_utf8(unpaired_high); + Void::Testing::expect(!err16_hi.has_value()); + Void::Testing::expect(err16_hi.error().kind == UtfErrorKind::invalid_utf16); + Void::Testing::expect_eq(err16_hi.error().unit_offset, std::size_t{1}); + + const std::u16string unpaired_low{char16_t{0xDC00}, u'z'}; + Void::Testing::expect(validate_utf16(unpaired_low).error().kind == UtfErrorKind::invalid_utf16); + + const std::u16string trunc16{u'a', char16_t{0xD83D}}; + Void::Testing::expect(validate_utf16(trunc16).error().kind == UtfErrorKind::truncated); + + // UTF-32 surrogates and > 0x10FFFF + const std::u32string sur32{U'a', char32_t{0xD800}}; + Void::Testing::expect(validate_utf32(sur32).error().kind == UtfErrorKind::invalid_scalar); + const std::u32string big32{char32_t{0x110000}}; + Void::Testing::expect(utf32_to_utf8(big32).error().kind == UtfErrorKind::invalid_scalar); +} + +Void::Testing::Test utf_one_unit_repair_and_into_span_limits() +{ + using Void::Unicode::UtfErrorKind; + using Void::Unicode::UtfLimits; + using Void::Unicode::UtfPolicy; + using Void::Unicode::utf16_to_utf32; + using Void::Unicode::utf32_to_utf8; + using Void::Unicode::utf8_repair; + using Void::Unicode::utf8_to_utf16_into; + using Void::Unicode::utf8_to_utf32; + + // Invalid lead byte followed by valid ASCII preserves ASCII cleanly. + const auto rep_ascii = utf8_to_utf32("a\xFF" "b\xE2\x82" "c", UtfPolicy::replace_one_unit); + Void::Testing::require(rep_ascii.has_value()); + const std::u32string expected_rep{U'a', U'\uFFFD', U'b', U'\uFFFD', U'\uFFFD', U'c'}; + Void::Testing::expect(*rep_ascii == expected_rep); + + const auto repaired_u8 = utf8_repair("ok\x80!"); + Void::Testing::require(repaired_u8.has_value()); + Void::Testing::expect(*repaired_u8 == std::string{"ok\xEF\xBF\xBD!"}); + + // UTF-16 repair: lone low, lone high, valid surrogate pair + const std::u16string bad16{ + char16_t{0xDC00}, + char16_t{0xD800}, + u'Z', + char16_t{0xD83D}, + char16_t{0xDE80}, + }; + const auto rep16 = utf16_to_utf32(bad16, UtfPolicy::replace_one_unit); + Void::Testing::require(rep16.has_value()); + const std::u32string exp16{U'\uFFFD', U'\uFFFD', U'Z', U'\U0001F680'}; + Void::Testing::expect(*rep16 == exp16); + + // UTF-32 repair + const auto rep32 = utf32_to_utf8( + std::u32string_view{U"X"} , UtfPolicy::replace_one_unit); + Void::Testing::require(rep32.has_value()); + const std::u32string invalid32{U'X', char32_t{0xD801}, char32_t{0x200000}, U'Y'}; + const auto rep32_bad = utf32_to_utf8(invalid32, UtfPolicy::replace_one_unit); + Void::Testing::require(rep32_bad.has_value()); + Void::Testing::expect(*rep32_bad == std::string{"X\xEF\xBF\xBD\xEF\xBF\xBDY"}); + + // Non-allocating _into transcoding + output_too_small + input/output limits + cancellation + std::array buf16{}; + const auto fit = utf8_to_utf16_into("A\xF0\x9F\x9A\x80", std::span{buf16}); + Void::Testing::require(fit.has_value()); + Void::Testing::expect_eq(fit->units_written, std::size_t{3}); + Void::Testing::expect_eq(fit->scalars_decoded, std::size_t{2}); + + std::array small16{}; + const auto too_small = utf8_to_utf16_into("A\xF0\x9F\x9A\x80", std::span{small16}); + Void::Testing::expect(!too_small.has_value()); + Void::Testing::expect(too_small.error().kind == UtfErrorKind::output_too_small); + + const auto lim_in = utf8_to_utf32("abcdef", UtfPolicy::reject, UtfLimits{.max_input_units = 4}); + Void::Testing::expect(lim_in.error().kind == UtfErrorKind::limit_exceeded); + + const auto lim_out = utf8_to_utf32("abcdef", UtfPolicy::reject, UtfLimits{.max_output_units = 3}); + Void::Testing::expect(lim_out.error().kind == UtfErrorKind::limit_exceeded); + + std::stop_source ssrc; + ssrc.request_stop(); + const auto cancelled = utf8_to_utf32("abc", UtfPolicy::reject, UtfLimits{}, ssrc.get_token()); + Void::Testing::expect(cancelled.error().kind == UtfErrorKind::cancelled); +} + +Void::Testing::Test utf_streaming_decoders_arbitrary_splits() +{ + using Void::Unicode::Scalar; + using Void::Unicode::Utf16StreamDecoder; + using Void::Unicode::Utf8StreamDecoder; + using Void::Unicode::UtfErrorKind; + using Void::Unicode::UtfPolicy; + using Void::Unicode::utf8_to_utf32; + + // 1-byte chunks across 1-, 2-, 3-, 4-byte UTF-8 and invalid bytes under repair + const std::string sample{"H\xC3\xA9\xE2\x82\xAC\xF0\x9F\x9A\x80!\xE2\x82" "X\xED\xA0\x80", 17}; + const auto expected_oneshot = utf8_to_utf32(sample, UtfPolicy::replace_one_unit); + Void::Testing::require(expected_oneshot.has_value()); + + Utf8StreamDecoder dec{UtfPolicy::replace_one_unit}; + std::u32string streamed; + for (std::size_t i = 0; i < sample.size(); ++i) { + const auto res = dec.push( + std::string_view{sample.data() + i, 1}, + [&](Scalar s) { streamed.push_back(s.code_point()); }); + Void::Testing::require(res.has_value()); + } + const auto fin = dec.finish([&](Scalar s) { streamed.push_back(s.code_point()); }); + Void::Testing::require(fin.has_value()); + Void::Testing::expect(!dec.has_pending()); + Void::Testing::expect(streamed == *expected_oneshot); + + // Strict UTF-8 streaming rejects truncated sequence at finish() + Utf8StreamDecoder strict_dec{UtfPolicy::reject}; + std::u32string tmp; + Void::Testing::require(strict_dec.push("\xE2\x82", [&](Scalar s) { tmp.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(strict_dec.has_pending()); + const auto trunc_fin = strict_dec.finish([&](Scalar s) { tmp.push_back(s.code_point()); }); + Void::Testing::expect(!trunc_fin.has_value()); + Void::Testing::expect(trunc_fin.error().kind == UtfErrorKind::truncated); + + // UTF-16 split surrogate pair across chunk boundary + Utf16StreamDecoder u16_dec{UtfPolicy::reject}; + std::u32string out16; + Void::Testing::require( + u16_dec.push(std::u16string_view{u"A\xD83D", 2}, [&](Scalar s) { out16.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(u16_dec.has_pending()); + Void::Testing::require( + u16_dec.push(std::u16string_view{u"\xDE80Z", 2}, [&](Scalar s) { out16.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(!u16_dec.has_pending()); + Void::Testing::require(u16_dec.finish([&](Scalar s) { out16.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(out16 == std::u32string{U'A', U'\U0001F680', U'Z'}); + + // UTF-16 repair with trailing high surrogate at EOF + Utf16StreamDecoder u16_rep{UtfPolicy::replace_one_unit}; + std::u32string out16_rep; + const std::u16string part1{char16_t{0xD800}}; + const std::u16string part2{u'B', char16_t{0xD83D}}; + Void::Testing::require(u16_rep.push(part1, [&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value()); + Void::Testing::require(u16_rep.push(part2, [&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value()); + Void::Testing::require(u16_rep.finish([&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(out16_rep == std::u32string{U'\uFFFD', U'B', U'\uFFFD'}); +} \ No newline at end of file From c75056fe07078a6704721a390a49ea86578f6bec Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:48:55 +0300 Subject: [PATCH 4/5] feat(Async): add OperationOptions, OperationState, ResumeTicket, TaskScope, and bounded executor tickets (M-ASYNC-02, M-ASYNC-03) --- include/Void/Async/Detail/Types.hpp | 138 ++++ include/Void/Async/Executor.hpp | 250 ++++++- include/Void/Async/Operation.hpp | 410 +++++++++++ include/Void/Async/TaskScope.hpp | 798 ++++++++++++++++++++++ src/Async/module.cmake | 4 +- tests/standalone/Async/OperationScope.cpp | 633 +++++++++++++++++ 6 files changed, 2229 insertions(+), 4 deletions(-) create mode 100644 include/Void/Async/Detail/Types.hpp create mode 100644 include/Void/Async/Operation.hpp create mode 100644 include/Void/Async/TaskScope.hpp create mode 100644 tests/standalone/Async/OperationScope.cpp diff --git a/include/Void/Async/Detail/Types.hpp b/include/Void/Async/Detail/Types.hpp new file mode 100644 index 0000000..d5512a3 --- /dev/null +++ b/include/Void/Async/Detail/Types.hpp @@ -0,0 +1,138 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Async +{ + +enum class AdmissionError { + overloaded, + stopped, + deadline_expired, + invalid_argument, + self_join +}; + +enum class AsyncErrorCode : std::int32_t { + none = 0, + cancelled = 1, + timeout = 2, + overloaded = 3, + stopped = 4, + invalid_argument = 5, + self_join = 6, + backend_error = 7, + limit_exceeded = 8 +}; + +enum class DomainOutcomeKind { + pending, + succeeded, + not_committed, + unknown, + failed, + cancelled +}; + +struct OperationOptions { + std::stop_token stop{}; + std::optional deadline{}; +}; + +[[nodiscard]] inline bool is_deadline_expired( + const OperationOptions& options, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) noexcept +{ + return options.deadline.has_value() && clock.now() >= *options.deadline; +} + +[[nodiscard]] inline Void::Result::Error + make_async_error(AsyncErrorCode code, std::string message = {}) +{ + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case AsyncErrorCode::none: + kind = ErrorKind::internal; + break; + case AsyncErrorCode::cancelled: + case AsyncErrorCode::stopped: + kind = ErrorKind::cancelled; + break; + case AsyncErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case AsyncErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case AsyncErrorCode::invalid_argument: + kind = ErrorKind::invalid_argument; + break; + case AsyncErrorCode::self_join: + kind = ErrorKind::conflict; + break; + case AsyncErrorCode::backend_error: + kind = ErrorKind::internal; + break; + case AsyncErrorCode::limit_exceeded: + kind = ErrorKind::exhausted; + break; + } + + const ErrorCode domain_code{ + Void::Result::kAsyncErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code}; +} + +[[nodiscard]] inline Void::Result::Error + make_async_error(AdmissionError adm, std::string message = {}) +{ + AsyncErrorCode code = AsyncErrorCode::invalid_argument; + switch (adm) { + case AdmissionError::overloaded: + code = AsyncErrorCode::overloaded; + if (message.empty()) { + message = "Async executor or scope capacity exceeded"; + } + break; + case AdmissionError::stopped: + code = AsyncErrorCode::stopped; + if (message.empty()) { + message = "Async executor or scope is stopped"; + } + break; + case AdmissionError::deadline_expired: + code = AsyncErrorCode::timeout; + if (message.empty()) { + message = "Async operation deadline expired"; + } + break; + case AdmissionError::invalid_argument: + code = AsyncErrorCode::invalid_argument; + if (message.empty()) { + message = "Invalid async admission argument"; + } + break; + case AdmissionError::self_join: + code = AsyncErrorCode::self_join; + if (message.empty()) { + message = "Cannot blocking-join from inside the active executor thread"; + } + break; + } + return make_async_error(code, std::move(message)); +} + +} // namespace Void::Async \ No newline at end of file diff --git a/include/Void/Async/Executor.hpp b/include/Void/Async/Executor.hpp index f3866ba..e8d6497 100644 --- a/include/Void/Async/Executor.hpp +++ b/include/Void/Async/Executor.hpp @@ -1,15 +1,56 @@ #pragma once +#include #include #include +#include #include #include #include +#include +#include namespace Void::Async { +class Executor; + +namespace detail +{ +struct ActiveExecutorFrame { + const Executor* exec{nullptr}; + const ActiveExecutorFrame* prev{nullptr}; + + [[nodiscard]] static inline const ActiveExecutorFrame*& head() noexcept + { + thread_local const ActiveExecutorFrame* slot = nullptr; + return slot; + } +}; + +class ExecutorThreadGuard +{ +public: + explicit ExecutorThreadGuard(const Executor* exec) noexcept + : frame_{exec, ActiveExecutorFrame::head()} + { + ActiveExecutorFrame::head() = &frame_; + } + + ~ExecutorThreadGuard() + { + ActiveExecutorFrame::head() = frame_.prev; + } + + ExecutorThreadGuard(const ExecutorThreadGuard&) = delete; + ExecutorThreadGuard& operator=(const ExecutorThreadGuard&) = delete; + +private: + ActiveExecutorFrame frame_; +}; +} // namespace detail + // ── Executor ────────────────────────────────────────────────────────────────── // Minimal scheduling interface bridging Coro::Task to a driving thread. // post() must be safe to call from any thread. @@ -21,6 +62,54 @@ public: // Schedule a coroutine for resumption on this executor. Thread-safe. virtual void post(std::coroutine_handle<> handle) = 0; + + // Bounded non-blocking admission. Subclasses may override with queue caps. + [[nodiscard]] virtual std::expected + try_post(std::coroutine_handle<> handle) + { + if (!handle) { + return std::unexpected{AdmissionError::invalid_argument}; + } + post(handle); + return {}; + } + + // Reserved lane for resuming waiting/joining continuations without normal + // work-queue backpressure rejections. + virtual void post_completion(std::coroutine_handle<> handle) + { + if (handle) { + post(handle); + } + } + + [[nodiscard]] virtual bool is_executor_thread() const noexcept + { + for (const auto* f = detail::ActiveExecutorFrame::head(); + f != nullptr; + f = f->prev) { + if (f->exec == this) { + return true; + } + } + return false; + } + + [[nodiscard]] virtual bool supports_reservation() const noexcept { return false; } + + [[nodiscard]] virtual std::expected try_reserve_slot() + { + return {}; + } + + virtual void commit_reserved(std::coroutine_handle<> handle) + { + post_completion(handle); + } + + virtual void release_reserved() noexcept {} + + [[nodiscard]] virtual bool has_background_workers() const noexcept { return true; } }; // ── ManualExecutor ──────────────────────────────────────────────────────────── @@ -31,18 +120,111 @@ public: class ManualExecutor final : public Executor { public: + explicit ManualExecutor(std::size_t max_queue = 0) noexcept + : max_queue_(max_queue) + { + } + void post(std::coroutine_handle<> handle) override { + if (!handle) { + return; + } + pending_normal_.fetch_add(1, std::memory_order_acq_rel); queue_.push(handle); } + [[nodiscard]] std::expected + try_post(std::coroutine_handle<> handle) override + { + if (!handle) { + return std::unexpected{AdmissionError::invalid_argument}; + } + auto reserved = try_reserve_slot(); + if (!reserved.has_value()) { + return reserved; + } + queue_.push(handle); + return {}; + } + + void post_completion(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + completion_queue_.push(handle); + } + + [[nodiscard]] bool supports_reservation() const noexcept override { return true; } + + [[nodiscard]] std::expected try_reserve_slot() override + { + std::size_t cur = pending_normal_.load(std::memory_order_acquire); + for (;;) { + if (!accepting_.load(std::memory_order_acquire)) { + return std::unexpected{AdmissionError::stopped}; + } + if (max_queue_ != 0 && cur >= max_queue_) { + return std::unexpected{AdmissionError::overloaded}; + } + if (pending_normal_.compare_exchange_weak( + cur, + cur + 1, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return {}; + } + } + } + + void commit_reserved(std::coroutine_handle<> handle) override + { + if (!handle) { + pending_normal_.fetch_sub(1, std::memory_order_acq_rel); + return; + } + queue_.push(handle); + } + + void release_reserved() noexcept override + { + pending_normal_.fetch_sub(1, std::memory_order_acq_rel); + } + + [[nodiscard]] bool has_background_workers() const noexcept override { return false; } + + void shutdown() noexcept + { + accepting_.store(false, std::memory_order_release); + } + + [[nodiscard]] bool is_accepting() const noexcept + { + return accepting_.load(std::memory_order_acquire); + } + + [[nodiscard]] std::size_t pending_normal() const noexcept + { + return pending_normal_.load(std::memory_order_acquire); + } + + [[nodiscard]] std::size_t max_queue() const noexcept { return max_queue_; } + // Resume one pending coroutine. Returns false if none was pending. bool run_one() { + if (auto c = completion_queue_.try_pop(); c.has_value()) { + detail::ExecutorThreadGuard guard{this}; + c->resume(); + return true; + } auto h = queue_.try_pop(); if (!h) { return false; } + pending_normal_.fetch_sub(1, std::memory_order_acq_rel); + detail::ExecutorThreadGuard guard{this}; h->resume(); return true; } @@ -58,10 +240,17 @@ public: return count; } - [[nodiscard]] bool empty() const noexcept { return queue_.empty(); } + [[nodiscard]] bool empty() const noexcept + { + return completion_queue_.empty() && queue_.empty(); + } private: - MpscQueue> queue_; + std::size_t max_queue_{0}; + std::atomic pending_normal_{0}; + std::atomic accepting_{true}; + MpscQueue> queue_{}; + MpscQueue> completion_queue_{}; }; // ── schedule_on ─────────────────────────────────────────────────────────────── @@ -112,4 +301,61 @@ inline void spawn(Executor& executor, Coro::Task task) Detail::spawn_impl(executor, std::move(task)); } +struct ScheduleStatusAwaiter { + Executor& executor; + OperationOptions options{}; + const Void::Time::MonotonicClock* clock{&Void::Time::SystemMonotonicClock::instance()}; + Void::Result::Result pre_outcome{}; + + [[nodiscard]] bool await_ready() noexcept + { + if (options.stop.stop_requested()) { + pre_outcome = std::unexpected{make_async_error( + AsyncErrorCode::cancelled, "schedule_on cancelled before scheduling")}; + return true; + } + if (is_deadline_expired(options, *clock)) { + pre_outcome = std::unexpected{make_async_error( + AsyncErrorCode::timeout, "schedule_on deadline expired before scheduling")}; + return true; + } + return false; + } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) + { + const auto post_res = executor.try_post(handle); + if (!post_res.has_value()) { + pre_outcome = std::unexpected{make_async_error( + post_res.error(), "schedule_on rejected by executor")}; + return false; + } + return true; + } + + [[nodiscard]] Void::Result::Result await_resume() noexcept + { + if (!pre_outcome.has_value()) { + return pre_outcome; + } + if (options.stop.stop_requested()) { + return std::unexpected{make_async_error( + AsyncErrorCode::cancelled, "schedule_on cancelled before execution")}; + } + if (is_deadline_expired(options, *clock)) { + return std::unexpected{make_async_error( + AsyncErrorCode::timeout, "schedule_on deadline expired before execution")}; + } + return {}; + } +}; + +[[nodiscard]] inline ScheduleStatusAwaiter schedule_on( + Executor& executor, + OperationOptions options, + const Void::Time::MonotonicClock& clock = Void::Time::SystemMonotonicClock::instance()) noexcept +{ + return ScheduleStatusAwaiter{executor, std::move(options), &clock}; +} + } // namespace Void::Async diff --git a/include/Void/Async/Operation.hpp b/include/Void/Async/Operation.hpp new file mode 100644 index 0000000..81bbc02 --- /dev/null +++ b/include/Void/Async/Operation.hpp @@ -0,0 +1,410 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Async +{ + +enum class StopBehavior { + notify_only, + settle_cancelled +}; + +// Move-only, single-delivery handle for resuming a suspended continuation on +// its bound completion lane (or inline when no executor was supplied). +class ResumeTicket +{ +public: + ResumeTicket() noexcept = default; + + explicit ResumeTicket(std::coroutine_handle<> handle, + Executor* executor = nullptr) noexcept + : handle_(handle) + , executor_(executor) + { + } + + ResumeTicket(ResumeTicket&& other) noexcept + : handle_(std::exchange(other.handle_, {})) + , executor_(std::exchange(other.executor_, nullptr)) + { + } + + ResumeTicket& operator=(ResumeTicket&& other) noexcept + { + if (this != &other) { + handle_ = std::exchange(other.handle_, {}); + executor_ = std::exchange(other.executor_, nullptr); + } + return *this; + } + + ResumeTicket(const ResumeTicket&) = delete; + ResumeTicket& operator=(const ResumeTicket&) = delete; + + [[nodiscard]] explicit operator bool() const noexcept + { + return static_cast(handle_); + } + + [[nodiscard]] std::coroutine_handle<> handle() const noexcept { return handle_; } + [[nodiscard]] Executor* executor() const noexcept { return executor_; } + + void dispatch() + { + auto h = std::exchange(handle_, {}); + auto* ex = std::exchange(executor_, nullptr); + if (!h) { + return; + } + if (ex != nullptr) { + ex->post_completion(h); + } else { + h.resume(); + } + } + + void resume_inline() + { + auto h = std::exchange(handle_, {}); + executor_ = nullptr; + if (h) { + h.resume(); + } + } + + [[nodiscard]] std::coroutine_handle<> release() noexcept + { + executor_ = nullptr; + return std::exchange(handle_, {}); + } + +private: + std::coroutine_handle<> handle_{}; + Executor* executor_{nullptr}; +}; + +// Thread-safe shared operation state arbitrating backend work refs, external +// stop intent, single-winner outcome selection, and post-backend-release +// continuation delivery. +template +class OperationState : public std::enable_shared_from_this> +{ +public: + using OutcomeType = std::expected; + + struct Awaitable { + std::shared_ptr> state; + Executor* resume_executor{nullptr}; + + [[nodiscard]] bool await_ready() const noexcept { return false; } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> handle) noexcept + { + return state->try_arm_suspend(handle, resume_executor); + } + + [[nodiscard]] OutcomeType await_resume() + { + return state->take_result(); + } + }; + + [[nodiscard]] static std::shared_ptr> create( + OperationOptions options = {}, + Executor* resume_executor = nullptr, + StopBehavior stop_behavior = StopBehavior::notify_only) + { + auto ptr = std::shared_ptr>( + new OperationState(resume_executor, stop_behavior, options.deadline)); + if (options.stop.stop_possible()) { + ptr->stop_cb_.emplace(options.stop, StopForwarder{ptr.get()}); + } + return ptr; + } + + OperationState(const OperationState&) = delete; + OperationState& operator=(const OperationState&) = delete; + OperationState(OperationState&&) = delete; + OperationState& operator=(OperationState&&) = delete; + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return stop_source_.get_token(); + } + + [[nodiscard]] bool stop_requested() const noexcept + { + return (sync_.load(std::memory_order_acquire) & kStopRequestedFlag) != 0 || + stop_source_.stop_requested(); + } + + [[nodiscard]] const std::optional& + deadline() const noexcept + { + return deadline_; + } + + [[nodiscard]] bool is_deadline_expired( + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) const noexcept + { + return deadline_.has_value() && clock.now() >= *deadline_; + } + + bool request_stop() noexcept + { + sync_.fetch_or(kStopRequestedFlag, std::memory_order_acq_rel); + const bool triggered = stop_source_.request_stop(); + if (stop_behavior_ == StopBehavior::settle_cancelled) { + if (auto ticket = try_commit_cancelled("Operation cancelled"); + ticket.has_value()) { + ticket->dispatch(); + } + } + return triggered; + } + + void acquire_backend_ref() noexcept + { + sync_.fetch_add(kRefStep, std::memory_order_acq_rel); + } + + [[nodiscard]] std::optional release_backend_ref() noexcept + { + const std::uint64_t prev = sync_.fetch_sub(kRefStep, std::memory_order_acq_rel); + const std::uint64_t cur = prev - kRefStep; + if ((cur >> kRefShift) != 0) { + return std::nullopt; + } + return maybe_claim_ticket(); + } + + void release_backend_ref_and_dispatch() + { + if (auto ticket = release_backend_ref(); ticket.has_value()) { + ticket->dispatch(); + } + } + + template + requires (!std::is_void_v) + [[nodiscard]] std::optional try_commit_value(U value) + { + return settle_with(DomainOutcomeKind::succeeded, + [&](std::optional& slot) { + slot.emplace(std::in_place, std::move(value)); + }); + } + + template + requires (std::is_void_v) + [[nodiscard]] std::optional try_commit_value() + { + return settle_with(DomainOutcomeKind::succeeded, + [](std::optional& slot) { + slot.emplace(); + }); + } + + [[nodiscard]] std::optional try_commit_error( + Void::Result::Error err, + DomainOutcomeKind kind = DomainOutcomeKind::failed) + { + return settle_with(kind, [&](std::optional& slot) { + slot.emplace(std::unexpected{std::move(err)}); + }); + } + + [[nodiscard]] std::optional try_commit_not_committed( + std::string message = "Operation stopped before commit") + { + return try_commit_error( + make_async_error(AsyncErrorCode::cancelled, std::move(message)), + DomainOutcomeKind::not_committed); + } + + [[nodiscard]] std::optional try_commit_unknown( + std::string message = "Commit state unknown after backend failure") + { + return try_commit_error( + make_async_error(AsyncErrorCode::backend_error, std::move(message)), + DomainOutcomeKind::unknown); + } + + [[nodiscard]] std::optional try_commit_cancelled( + std::string message = "Operation cancelled") + { + return try_commit_error( + make_async_error(AsyncErrorCode::cancelled, std::move(message)), + DomainOutcomeKind::cancelled); + } + + [[nodiscard]] std::optional try_commit_timeout( + std::string message = "Operation deadline expired") + { + return try_commit_error( + make_async_error(AsyncErrorCode::timeout, std::move(message)), + DomainOutcomeKind::failed); + } + + [[nodiscard]] bool try_arm_suspend(std::coroutine_handle<> continuation, + Executor* resume_exec = nullptr) noexcept + { + continuation_ = continuation; + if (resume_exec != nullptr) { + resume_executor_ = resume_exec; + } + + std::uint64_t cur = sync_.load(std::memory_order_acquire); + for (;;) { + if ((cur & kSettledFlag) != 0 && + (cur >> kRefShift) == 0 && + (cur & kDispatchedFlag) == 0) { + if (sync_.compare_exchange_weak( + cur, + cur | kSuspendedFlag | kDispatchedFlag, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + continuation_ = {}; + resume_executor_ = nullptr; + return false; + } + } else { + if (sync_.compare_exchange_weak( + cur, + cur | kSuspendedFlag, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return true; + } + } + } + } + + [[nodiscard]] bool is_settled() const noexcept + { + return (sync_.load(std::memory_order_acquire) & kSettledFlag) != 0; + } + + [[nodiscard]] std::uint64_t backend_ref_count() const noexcept + { + return sync_.load(std::memory_order_acquire) >> kRefShift; + } + + [[nodiscard]] DomainOutcomeKind outcome_kind() const noexcept + { + return domain_outcome_.load(std::memory_order_acquire); + } + + [[nodiscard]] OutcomeType take_result() + { + // Acquire on sync_ ensures visibility of the winner's write to outcome_. + (void)sync_.load(std::memory_order_acquire); + if (!outcome_.has_value()) { + return std::unexpected{make_async_error( + AsyncErrorCode::backend_error, + "OperationState result accessed before settlement")}; + } + return std::move(*outcome_); + } + + [[nodiscard]] Awaitable awaitable(Executor* resume_exec = nullptr) noexcept + { + return Awaitable{this->shared_from_this(), resume_exec}; + } + + [[nodiscard]] Awaitable operator co_await() noexcept + { + return awaitable(nullptr); + } + +private: + static constexpr std::uint64_t kSettledFlag = 1ULL << 0; + static constexpr std::uint64_t kSuspendedFlag = 1ULL << 1; + static constexpr std::uint64_t kDispatchedFlag = 1ULL << 2; + static constexpr std::uint64_t kStopRequestedFlag = 1ULL << 3; + static constexpr std::uint64_t kRefShift = 4; + static constexpr std::uint64_t kRefStep = 1ULL << kRefShift; + + struct StopForwarder { + OperationState* self{nullptr}; + void operator()() const noexcept + { + if (self != nullptr) { + self->request_stop(); + } + } + }; + + OperationState(Executor* resume_executor, + StopBehavior stop_behavior, + std::optional deadline) noexcept + : stop_behavior_(stop_behavior) + , deadline_(deadline) + , resume_executor_(resume_executor) + { + } + + template + [[nodiscard]] std::optional settle_with( + DomainOutcomeKind kind, InitFn&& init_fn) + { + if (outcome_claimed_.exchange(true, std::memory_order_acq_rel)) { + return std::nullopt; + } + init_fn(outcome_); + domain_outcome_.store(kind, std::memory_order_release); + sync_.fetch_or(kSettledFlag, std::memory_order_acq_rel); + return maybe_claim_ticket(); + } + + [[nodiscard]] std::optional maybe_claim_ticket() noexcept + { + std::uint64_t cur = sync_.load(std::memory_order_acquire); + for (;;) { + if ((cur & kSettledFlag) == 0 || + (cur & kSuspendedFlag) == 0 || + (cur & kDispatchedFlag) != 0 || + (cur >> kRefShift) != 0) { + return std::nullopt; + } + if (sync_.compare_exchange_weak( + cur, + cur | kDispatchedFlag, + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return ResumeTicket{ + std::exchange(continuation_, {}), + std::exchange(resume_executor_, nullptr)}; + } + } + } + + std::stop_source stop_source_{}; + StopBehavior stop_behavior_{StopBehavior::notify_only}; + std::optional deadline_{}; + std::atomic sync_{0}; + std::atomic outcome_claimed_{false}; + std::atomic domain_outcome_{DomainOutcomeKind::pending}; + std::optional outcome_{}; + std::coroutine_handle<> continuation_{}; + Executor* resume_executor_{nullptr}; + // MUST stay LAST: destroyed first in ~OperationState() to synchronize any + // in-flight external stop callback before members above are torn down. + std::optional> stop_cb_{}; +}; + +} // namespace Void::Async \ No newline at end of file diff --git a/include/Void/Async/TaskScope.hpp b/include/Void/Async/TaskScope.hpp new file mode 100644 index 0000000..4e2c834 --- /dev/null +++ b/include/Void/Async/TaskScope.hpp @@ -0,0 +1,798 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Async +{ + +struct TaskScopeOptions { + std::size_t max_tasks{1024}; + std::stop_token parent_stop{}; + bool stop_on_first_error{true}; + + [[nodiscard]] static constexpr TaskScopeOptions unlimited( + std::stop_token parent_stop = {}, + bool stop_on_first_error = true) noexcept + { + return TaskScopeOptions{ + std::numeric_limits::max(), + parent_stop, + stop_on_first_error}; + } +}; + +namespace detail +{ + +class ScopeControl; + +class ChildTaskControl : public std::enable_shared_from_this +{ +public: + explicit ChildTaskControl(Executor& executor) noexcept + : executor_(executor) + { + } + + ChildTaskControl(const ChildTaskControl&) = delete; + ChildTaskControl& operator=(const ChildTaskControl&) = delete; + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return stop_source_.get_token(); + } + + bool request_stop() noexcept + { + return stop_source_.request_stop(); + } + + void attach_stops(std::stop_token scope_stop, std::stop_token option_stop) + { + if (scope_stop.stop_possible()) { + scope_stop_cb_.emplace(scope_stop, StopForwarder{this}); + } + if (option_stop.stop_possible()) { + option_stop_cb_.emplace(option_stop, StopForwarder{this}); + } + } + + void set_error(Void::Result::Error err) + { + std::lock_guard lk{mu_}; + error_ = std::move(err); + } + + void mark_finished() + { + std::coroutine_handle<> waiter{}; + { + std::lock_guard lk{mu_}; + finished_ = true; + waiter = std::exchange(async_waiter_, {}); + } + cv_.notify_all(); + if (waiter) { + executor_.post_completion(waiter); + } + } + + [[nodiscard]] bool done() const + { + std::lock_guard lk{mu_}; + return finished_; + } + + [[nodiscard]] bool try_register_waiter(std::coroutine_handle<> waiter) + { + std::lock_guard lk{mu_}; + if (finished_) { + return false; + } + async_waiter_ = waiter; + return true; + } + + [[nodiscard]] Void::Result::Result take_outcome() const + { + std::lock_guard lk{mu_}; + if (error_.has_value()) { + return std::unexpected{*error_}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result join_blocking() + { + if (executor_.is_executor_thread()) { + return std::unexpected{make_async_error( + AdmissionError::self_join, + "JoinHandle::join_blocking called on active executor thread")}; + } + std::unique_lock lk{mu_}; + cv_.wait(lk, [this] { return finished_; }); + if (error_.has_value()) { + return std::unexpected{*error_}; + } + return {}; + } + +private: + struct StopForwarder { + ChildTaskControl* self{nullptr}; + void operator()() const noexcept + { + if (self != nullptr) { + self->request_stop(); + } + } + }; + + Executor& executor_; + std::stop_source stop_source_{}; + mutable std::mutex mu_{}; + std::condition_variable cv_{}; + bool finished_{false}; + std::optional error_{}; + std::coroutine_handle<> async_waiter_{}; + // MUST stay LAST so stop callbacks synchronize before members destruct. + std::optional> scope_stop_cb_{}; + std::optional> option_stop_cb_{}; +}; + +class ScopeControl : public std::enable_shared_from_this +{ +public: + [[nodiscard]] static std::shared_ptr create( + Executor& executor, TaskScopeOptions options) + { + auto ptr = std::shared_ptr( + new ScopeControl(executor, options)); + if (options.parent_stop.stop_possible()) { + ptr->parent_stop_cb_.emplace(options.parent_stop, StopForwarder{ptr.get()}); + } + return ptr; + } + + ScopeControl(const ScopeControl&) = delete; + ScopeControl& operator=(const ScopeControl&) = delete; + + [[nodiscard]] Executor& executor() noexcept { return executor_; } + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return stop_source_.get_token(); + } + + bool request_stop() noexcept + { + return stop_source_.request_stop(); + } + + void close() noexcept + { + std::lock_guard lk{mu_}; + closed_ = true; + } + + [[nodiscard]] std::expected try_reserve( + const OperationOptions& op, + const Void::Time::MonotonicClock& clock) + { + if (max_tasks_ == 0) { + return std::unexpected{AdmissionError::invalid_argument}; + } + if (op.stop.stop_requested()) { + return std::unexpected{AdmissionError::stopped}; + } + if (is_deadline_expired(op, clock)) { + return std::unexpected{AdmissionError::deadline_expired}; + } + std::lock_guard lk{mu_}; + if (closed_ || stop_source_.stop_requested()) { + return std::unexpected{AdmissionError::stopped}; + } + if (active_tasks_ >= max_tasks_) { + return std::unexpected{AdmissionError::overloaded}; + } + ++active_tasks_; + return {}; + } + + void release_reservation() + { + on_task_finished(); + } + + void record_exception(std::exception_ptr ex, std::string_view what) + { + bool trigger_stop = false; + { + std::lock_guard lk{mu_}; + ++failure_count_; + if (!first_exception_) { + first_exception_ = ex; + first_error_ = make_async_error( + AsyncErrorCode::backend_error, + what.empty() + ? std::string{"Unhandled exception in TaskScope task"} + : std::string{what}); + trigger_stop = stop_on_first_error_; + } + } + if (trigger_stop) { + request_stop(); + } + } + + void on_task_finished() + { + std::coroutine_handle<> waiter{}; + bool notify = false; + { + std::lock_guard lk{mu_}; + --active_tasks_; + if (active_tasks_ == 0) { + notify = true; + waiter = std::exchange(async_join_waiter_, {}); + } + } + if (notify) { + cv_.notify_all(); + if (waiter) { + executor_.post_completion(waiter); + } + } + } + + [[nodiscard]] bool try_begin_async_join(std::coroutine_handle<> waiter) + { + std::lock_guard lk{mu_}; + closed_ = true; + if (active_tasks_ == 0) { + return false; + } + async_join_waiter_ = waiter; + return true; + } + + [[nodiscard]] Void::Result::Result finish_outcome() const + { + std::lock_guard lk{mu_}; + if (first_error_.has_value()) { + return std::unexpected{*first_error_}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result join_blocking() + { + if (executor_.is_executor_thread()) { + return std::unexpected{make_async_error( + AdmissionError::self_join, + "TaskScope::join_blocking called on active executor thread")}; + } + std::unique_lock lk{mu_}; + closed_ = true; + cv_.wait(lk, [this] { return active_tasks_ == 0; }); + if (first_error_.has_value()) { + return std::unexpected{*first_error_}; + } + return {}; + } + + [[nodiscard]] std::size_t active_count() const + { + std::lock_guard lk{mu_}; + return active_tasks_; + } + + [[nodiscard]] std::size_t failure_count() const + { + std::lock_guard lk{mu_}; + return failure_count_; + } + + [[nodiscard]] bool has_exception() const + { + std::lock_guard lk{mu_}; + return static_cast(first_exception_); + } + + [[nodiscard]] std::exception_ptr first_exception() const + { + std::lock_guard lk{mu_}; + return first_exception_; + } + +private: + struct StopForwarder { + ScopeControl* self{nullptr}; + void operator()() const noexcept + { + if (self != nullptr) { + self->request_stop(); + } + } + }; + + ScopeControl(Executor& executor, TaskScopeOptions options) noexcept + : executor_(executor) + , max_tasks_(options.max_tasks) + , stop_on_first_error_(options.stop_on_first_error) + { + } + + Executor& executor_; + std::size_t max_tasks_{1024}; + bool stop_on_first_error_{true}; + std::stop_source stop_source_{}; + mutable std::mutex mu_{}; + std::condition_variable cv_{}; + std::size_t active_tasks_{0}; + std::size_t failure_count_{0}; + bool closed_{false}; + std::exception_ptr first_exception_{}; + std::optional first_error_{}; + std::coroutine_handle<> async_join_waiter_{}; + // MUST stay LAST: waits for any active parent stop callback on destruction. + std::optional> parent_stop_cb_{}; +}; + +struct TakePromiseTaskTag {}; +struct GetScopePtrTag {}; +struct GetChildPtrTag {}; + +struct ScopeRunner { + struct promise_type { + std::shared_ptr scope{}; + std::shared_ptr child{}; + std::optional> task{}; + + ScopeRunner get_return_object() noexcept + { + return ScopeRunner{ + std::coroutine_handle::from_promise(*this)}; + } + + std::suspend_always initial_suspend() noexcept { return {}; } + + struct FinalAwaiter { + bool await_ready() const noexcept { return false; } + void await_suspend(std::coroutine_handle h) noexcept + { + auto sc = std::move(h.promise().scope); + auto ch = std::move(h.promise().child); + h.promise().task.reset(); + // Destroy the coroutine frame completely before decrementing active + // task counters or waking any join waiter. + h.destroy(); + if (ch) { + ch->mark_finished(); + } + if (sc) { + sc->on_task_finished(); + } + } + void await_resume() const noexcept {} + }; + + FinalAwaiter final_suspend() noexcept { return {}; } + void return_void() noexcept {} + void unhandled_exception() noexcept {} + + auto await_transform(TakePromiseTaskTag) noexcept + { + struct Awaiter { + promise_type* p; + bool await_ready() const noexcept { return true; } + void await_suspend(std::coroutine_handle<>) noexcept {} + Coro::Task await_resume() noexcept + { + auto t = std::move(*p->task); + p->task.reset(); + return t; + } + }; + return Awaiter{this}; + } + + auto await_transform(GetScopePtrTag) noexcept + { + struct Awaiter { + promise_type* p; + bool await_ready() const noexcept { return true; } + void await_suspend(std::coroutine_handle<>) noexcept {} + std::shared_ptr await_resume() noexcept + { + return p->scope; + } + }; + return Awaiter{this}; + } + + auto await_transform(GetChildPtrTag) noexcept + { + struct Awaiter { + promise_type* p; + bool await_ready() const noexcept { return true; } + void await_suspend(std::coroutine_handle<>) noexcept {} + std::shared_ptr await_resume() noexcept + { + return p->child; + } + }; + return Awaiter{this}; + } + + template + decltype(auto) await_transform(A&& awaitable) noexcept + { + return std::forward(awaitable); + } + }; + + std::coroutine_handle handle{}; +}; + +inline ScopeRunner make_scope_runner() +{ + auto task = co_await TakePromiseTaskTag{}; + auto scope = co_await GetScopePtrTag{}; + auto child = co_await GetChildPtrTag{}; + try { + co_await std::move(task); + } catch (const std::exception& ex) { + if (child) { + child->set_error(make_async_error(AsyncErrorCode::backend_error, ex.what())); + } + if (scope) { + scope->record_exception(std::current_exception(), ex.what()); + } + } catch (...) { + constexpr std::string_view kUnknown = + "Unhandled non-std exception in TaskScope task"; + if (child) { + child->set_error( + make_async_error(AsyncErrorCode::backend_error, std::string{kUnknown})); + } + if (scope) { + scope->record_exception(std::current_exception(), kUnknown); + } + } +} + +} // namespace detail + +class JoinHandle +{ +public: + explicit JoinHandle(std::shared_ptr control) noexcept + : control_(std::move(control)) + { + } + + [[nodiscard]] bool done() const + { + return !control_ || control_->done(); + } + + bool request_stop() noexcept + { + return control_ ? control_->request_stop() : false; + } + + [[nodiscard]] std::stop_token stop_token() const noexcept + { + return control_ ? control_->stop_token() : std::stop_token{}; + } + + struct JoinAwaiter { + std::shared_ptr control; + + [[nodiscard]] bool await_ready() const noexcept + { + return !control || control->done(); + } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter) + { + return control->try_register_waiter(waiter); + } + + [[nodiscard]] Void::Result::Result await_resume() const + { + return control ? control->take_outcome() : Void::Result::Result{}; + } + }; + + [[nodiscard]] JoinAwaiter join() const noexcept + { + return JoinAwaiter{control_}; + } + + [[nodiscard]] JoinAwaiter operator co_await() const noexcept + { + return join(); + } + + [[nodiscard]] Void::Result::Result join_blocking() const + { + return control_ ? control_->join_blocking() : Void::Result::Result{}; + } + +private: + std::shared_ptr control_{}; +}; + +class TaskScope +{ +public: + explicit TaskScope( + Executor& executor, + TaskScopeOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) + : control_(detail::ScopeControl::create(executor, options)) + , clock_(clock) + { + } + + ~TaskScope() + { + control_->request_stop(); + control_->close(); + if (control_->active_count() > 0) { + if (!control_->executor().has_background_workers()) { + if (auto* manual = dynamic_cast(&control_->executor())) { + (void)join_pumping(*manual); + } + } else if (!control_->executor().is_executor_thread()) { + (void)control_->join_blocking(); + } + } + } + + TaskScope(const TaskScope&) = delete; + TaskScope& operator=(const TaskScope&) = delete; + TaskScope(TaskScope&&) = delete; + TaskScope& operator=(TaskScope&&) = delete; + + // Reserve-then-transfer spawn: failed admission preserves `task` intact in + // the caller without destroying or losing its coroutine frame. + [[nodiscard]] std::expected + spawn(Coro::Task&& task, OperationOptions options = {}) + { + if (!task.handle() || task.done()) { + return std::unexpected{AdmissionError::invalid_argument}; + } + return admit_and_launch(options, &task, nullptr); + } + + template + requires (!std::same_as, Coro::Task>) && + std::invocable && + std::same_as, Coro::Task> + [[nodiscard]] std::expected + spawn(F&& factory, OperationOptions options = {}) + { + return admit_and_launch( + options, + nullptr, + [&](std::stop_token st) -> Coro::Task { + return std::invoke(std::forward(factory), st); + }); + } + + bool request_stop() noexcept { return control_->request_stop(); } + void close() noexcept { control_->close(); } + [[nodiscard]] std::stop_token stop_token() const noexcept { return control_->stop_token(); } + [[nodiscard]] std::size_t active_count() const { return control_->active_count(); } + [[nodiscard]] std::size_t failure_count() const { return control_->failure_count(); } + [[nodiscard]] bool has_exception() const { return control_->has_exception(); } + [[nodiscard]] std::exception_ptr first_exception() const { return control_->first_exception(); } + + struct ScopeJoinAwaiter { + std::shared_ptr control; + + [[nodiscard]] bool await_ready() const noexcept + { + return false; + } + + [[nodiscard]] bool await_suspend(std::coroutine_handle<> waiter) + { + return control->try_begin_async_join(waiter); + } + + [[nodiscard]] Void::Result::Result await_resume() const + { + return control->finish_outcome(); + } + }; + + [[nodiscard]] ScopeJoinAwaiter join() noexcept + { + return ScopeJoinAwaiter{control_}; + } + + [[nodiscard]] Void::Result::Result join_blocking() + { + return control_->join_blocking(); + } + + [[nodiscard]] Void::Result::Result join_pumping(ManualExecutor& manual) + { + control_->close(); + while (control_->active_count() > 0) { + if (manual.drain() == 0 && control_->active_count() > 0) { + std::this_thread::yield(); + } + } + return control_->finish_outcome(); + } + + [[nodiscard]] Void::Result::Result join_pumping() + { + auto* manual = dynamic_cast(&control_->executor()); + if (manual == nullptr) { + return std::unexpected{make_async_error( + AsyncErrorCode::invalid_argument, + "TaskScope::join_pumping requires ManualExecutor")}; + } + return join_pumping(*manual); + } + +private: + template + [[nodiscard]] std::expected + admit_and_launch(const OperationOptions& options, + Coro::Task* existing_task, + FactoryFn&& factory) + { + if (auto sr = control_->try_reserve(options, clock_); !sr.has_value()) { + return std::unexpected{sr.error()}; + } + + Executor& exec = control_->executor(); + const bool use_reserved = exec.supports_reservation(); + if (use_reserved) { + if (auto er = exec.try_reserve_slot(); !er.has_value()) { + control_->release_reservation(); + return std::unexpected{er.error()}; + } + } + + auto child = std::make_shared(exec); + child->attach_stops(control_->stop_token(), options.stop); + + detail::ScopeRunner runner{}; + try { + runner = detail::make_scope_runner(); + auto& prom = runner.handle.promise(); + prom.scope = control_; + prom.child = child; + if (existing_task != nullptr) { + prom.task.emplace(std::move(*existing_task)); + } else if constexpr (!std::is_null_pointer_v>) { + prom.task.emplace(factory(child->stop_token())); + } + } catch (...) { + if (runner.handle) { + if (existing_task != nullptr && runner.handle.promise().task.has_value()) { + *existing_task = std::move(*runner.handle.promise().task); + } + runner.handle.promise().scope.reset(); + runner.handle.promise().child.reset(); + runner.handle.destroy(); + } + if (use_reserved) { + exec.release_reserved(); + } + control_->release_reservation(); + throw; + } + + auto rollback_unstarted = [&]() { + if (existing_task != nullptr && runner.handle.promise().task.has_value()) { + *existing_task = std::move(*runner.handle.promise().task); + } + runner.handle.promise().scope.reset(); + runner.handle.promise().child.reset(); + runner.handle.destroy(); + if (use_reserved) { + exec.release_reserved(); + } + control_->release_reservation(); + }; + + if (use_reserved) { + try { + exec.commit_reserved(runner.handle); + } catch (...) { + rollback_unstarted(); + return std::unexpected{AdmissionError::overloaded}; + } + } else { + auto post_res = exec.try_post(runner.handle); + if (!post_res.has_value()) { + rollback_unstarted(); + return std::unexpected{post_res.error()}; + } + } + + return JoinHandle{std::move(child)}; + } + + std::shared_ptr control_; + const Void::Time::MonotonicClock& clock_; +}; + +// Explicit structured lifetime owner for detached/background fire-and-forget work. +class DetachedOwner +{ +public: + explicit DetachedOwner( + Executor& executor, + TaskScopeOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()) + : scope_(executor, options, clock) + { + } + + [[nodiscard]] std::expected + spawn(Coro::Task&& task, OperationOptions options = {}) + { + return scope_.spawn(std::move(task), std::move(options)); + } + + template + requires (!std::same_as, Coro::Task>) && + std::invocable && + std::same_as, Coro::Task> + [[nodiscard]] std::expected + spawn(F&& factory, OperationOptions options = {}) + { + return scope_.spawn(std::forward(factory), std::move(options)); + } + + bool request_stop() noexcept { return scope_.request_stop(); } + void close() noexcept { scope_.close(); } + [[nodiscard]] std::stop_token stop_token() const noexcept { return scope_.stop_token(); } + [[nodiscard]] std::size_t active_count() const { return scope_.active_count(); } + [[nodiscard]] std::size_t failure_count() const { return scope_.failure_count(); } + + [[nodiscard]] Void::Result::Result drain_blocking() { return scope_.join_blocking(); } + [[nodiscard]] Void::Result::Result drain_pumping() { return scope_.join_pumping(); } + [[nodiscard]] Void::Result::Result drain_pumping(ManualExecutor& manual) + { + return scope_.join_pumping(manual); + } + +private: + TaskScope scope_; +}; + +} // namespace Void::Async \ No newline at end of file diff --git a/src/Async/module.cmake b/src/Async/module.cmake index 8267522..a7835e3 100644 --- a/src/Async/module.cmake +++ b/src/Async/module.cmake @@ -1,3 +1,3 @@ void_add_module(Async - INTERNAL_DEPS LogState -) + INTERNAL_DEPS Functional Time LogState +) \ No newline at end of file diff --git a/tests/standalone/Async/OperationScope.cpp b/tests/standalone/Async/OperationScope.cpp new file mode 100644 index 0000000..3105329 --- /dev/null +++ b/tests/standalone/Async/OperationScope.cpp @@ -0,0 +1,633 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using namespace Void::Async; + +class ThreadedWorkerExecutor final : public Executor +{ +public: + ThreadedWorkerExecutor() + { + worker_ = std::thread([this] { run_loop(); }); + } + + ~ThreadedWorkerExecutor() override + { + shutdown(); + if (worker_.joinable()) { + worker_.join(); + } + } + + void post(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + { + std::lock_guard lk{mu_}; + if (stop_) { + return; + } + normal_.push(handle); + } + cv_.notify_one(); + } + + [[nodiscard]] std::expected + try_post(std::coroutine_handle<> handle) override + { + if (!handle) { + return std::unexpected{AdmissionError::invalid_argument}; + } + { + std::lock_guard lk{mu_}; + if (stop_) { + return std::unexpected{AdmissionError::stopped}; + } + normal_.push(handle); + } + cv_.notify_one(); + return {}; + } + + void post_completion(std::coroutine_handle<> handle) override + { + if (!handle) { + return; + } + { + std::lock_guard lk{mu_}; + completions_.push(handle); + } + cv_.notify_one(); + } + + [[nodiscard]] bool is_executor_thread() const noexcept override + { + return std::this_thread::get_id() == worker_id_.load(std::memory_order_acquire); + } + + void shutdown() + { + { + std::lock_guard lk{mu_}; + stop_ = true; + } + cv_.notify_all(); + } + +private: + void run_loop() + { + worker_id_.store(std::this_thread::get_id(), std::memory_order_release); + for (;;) { + std::coroutine_handle<> next{}; + { + std::unique_lock lk{mu_}; + cv_.wait(lk, [this] { + return !completions_.empty() || !normal_.empty() || stop_; + }); + if (!completions_.empty()) { + next = completions_.front(); + completions_.pop(); + } else if (!normal_.empty()) { + next = normal_.front(); + normal_.pop(); + } else if (stop_) { + return; + } + } + if (next) { + next.resume(); + } + } + } + + std::atomic worker_id_{}; + std::mutex mu_{}; + std::condition_variable cv_{}; + std::queue> completions_{}; + std::queue> normal_{}; + bool stop_{false}; + std::thread worker_; +}; + +class NonReservingBoundedExecutor final : public Executor +{ +public: + explicit NonReservingBoundedExecutor(std::size_t cap) : cap_(cap) {} + + void post(std::coroutine_handle<> h) override { inner_.post(h); } + + [[nodiscard]] std::expected + try_post(std::coroutine_handle<> h) override + { + if (inner_.pending_normal() >= cap_) { + return std::unexpected{AdmissionError::overloaded}; + } + return inner_.try_post(h); + } + + void post_completion(std::coroutine_handle<> h) override { inner_.post_completion(h); } + [[nodiscard]] bool is_executor_thread() const noexcept override { return inner_.is_executor_thread(); } + [[nodiscard]] bool has_background_workers() const noexcept override { return false; } + + std::size_t drain() { return inner_.drain(); } + +private: + std::size_t cap_; + ManualExecutor inner_; +}; + +Void::Coro::Task increment_task(int* counter) +{ + ++(*counter); + co_return; +} + +Void::Coro::Task await_op_u64_task( + std::shared_ptr> op, + int* resumes, + DomainOutcomeKind* observed_kind, + std::optional* err_code, + std::uint64_t* receipt) +{ + const auto res = co_await *op; + ++(*resumes); + *observed_kind = op->outcome_kind(); + if (res.has_value()) { + if (receipt != nullptr) { + *receipt = *res; + } + } else if (err_code != nullptr) { + *err_code = static_cast(res.error().code().value); + } +} + +Void::Coro::Task await_op_void_task( + std::shared_ptr> op, + int* resumes, + DomainOutcomeKind* observed_kind, + bool* has_val) +{ + const auto res = co_await *op; + ++(*resumes); + *observed_kind = op->outcome_kind(); + if (has_val != nullptr) { + *has_val = res.has_value(); + } +} + +Void::Coro::Task await_op_int_task( + std::shared_ptr> op, + int expected, + int* waiter_resumed) +{ + const auto res = co_await *op; + Void::Testing::require(res.has_value()); + Void::Testing::expect_eq(*res, expected); + ++(*waiter_resumed); +} + +Void::Coro::Task schedule_with_options_task( + Executor* exec, + OperationOptions opts, + const Void::Time::MonotonicClock* clock, + Void::Result::Result* out) +{ + *out = co_await schedule_on(*exec, std::move(opts), *clock); +} + +} // namespace + +Void::Testing::Test operation_scope_failed_spawn_preserves_task_ownership() +{ + ManualExecutor bounded_exec{1}; + TaskScope scope{bounded_exec, TaskScopeOptions{.max_tasks = 1}}; + + int ran_first = 0; + const auto h1 = scope.spawn(increment_task(&ran_first)); + Void::Testing::require(h1.has_value()); + + // 1. Scope capacity exhausted -> task preserved intact! + int ran_preserved = 0; + auto preserved = increment_task(&ran_preserved); + const auto full_scope = scope.spawn(std::move(preserved)); + Void::Testing::expect(!full_scope.has_value()); + Void::Testing::expect(full_scope.error() == AdmissionError::overloaded); + Void::Testing::expect(static_cast(preserved.handle())); + Void::Testing::expect(!preserved.done()); + + // 2. Bounded executor queue full (reserve-then-transfer rollback) + TaskScope roomier_scope{bounded_exec, TaskScopeOptions{.max_tasks = 4}}; + const auto full_exec = roomier_scope.spawn(std::move(preserved)); + Void::Testing::expect(!full_exec.has_value()); + Void::Testing::expect(full_exec.error() == AdmissionError::overloaded); + Void::Testing::expect(static_cast(preserved.handle())); + Void::Testing::expect(!preserved.done()); + + // 3. Non-reserving executor try_post failure also restores task via rollback + NonReservingBoundedExecutor non_res_exec{0}; + TaskScope non_res_scope{non_res_exec}; + const auto non_res_reject = non_res_scope.spawn(std::move(preserved)); + Void::Testing::expect(!non_res_reject.has_value()); + Void::Testing::expect(non_res_reject.error() == AdmissionError::overloaded); + Void::Testing::expect(static_cast(preserved.handle())); + Void::Testing::expect(!preserved.done()); + + // 4. Stopped options and expired clock deadline reject without consuming task + std::stop_source ssrc; + ssrc.request_stop(); + const auto stopped_res = roomier_scope.spawn( + std::move(preserved), OperationOptions{.stop = ssrc.get_token()}); + Void::Testing::expect(!stopped_res.has_value()); + Void::Testing::expect(stopped_res.error() == AdmissionError::stopped); + Void::Testing::expect(static_cast(preserved.handle())); + + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}}; + TaskScope clocked_scope{bounded_exec, TaskScopeOptions{.max_tasks = 4}, clock}; + const auto expired_res = clocked_scope.spawn( + std::move(preserved), + OperationOptions{.deadline = Void::Time::MonotonicClock::time_point{std::chrono::seconds{50}}}); + Void::Testing::expect(!expired_res.has_value()); + Void::Testing::expect(expired_res.error() == AdmissionError::deadline_expired); + Void::Testing::expect(static_cast(preserved.handle())); + + // 5. Invalid max_tasks == 0 + TaskScope zero_scope{bounded_exec, TaskScopeOptions{.max_tasks = 0}}; + const auto zero_res = zero_scope.spawn(std::move(preserved)); + Void::Testing::expect(!zero_res.has_value()); + Void::Testing::expect(zero_res.error() == AdmissionError::invalid_argument); + Void::Testing::expect(static_cast(preserved.handle())); + + // Drain `scope` (closes `scope`), then prove caller still owns `preserved` via `roomier_scope`! + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect_eq(ran_first, 1); + + // Closed `scope` rejects spawn cleanly while still preserving `preserved` + const auto closed_res = scope.spawn(std::move(preserved)); + Void::Testing::expect(!closed_res.has_value()); + Void::Testing::expect(closed_res.error() == AdmissionError::stopped); + Void::Testing::expect(static_cast(preserved.handle())); + + const auto ok_after = roomier_scope.spawn(std::move(preserved)); + Void::Testing::require(ok_after.has_value()); + Void::Testing::require(roomier_scope.join_pumping().has_value()); + Void::Testing::expect_eq(ran_preserved, 1); +} + +Void::Testing::Test operation_scope_committing_adapter_races_and_backend_refs() +{ + ManualExecutor exec; + TaskScope scope{exec}; + + // Scenario A: stop-before-append -> NotCommitted after backend ref releases + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::notify_only); + op->acquire_backend_ref(); + + int resumes = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + std::optional err_code{}; + + Void::Testing::require( + scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, &err_code, nullptr)) + .has_value()); + + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + stop_src.request_stop(); + Void::Testing::expect(op->stop_requested()); + Void::Testing::expect(op->stop_token().stop_requested()); + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + if (op->stop_token().stop_requested()) { + if (auto t = op->try_commit_not_committed(); t.has_value()) { + t->dispatch(); + } + } + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(observed_kind == DomainOutcomeKind::not_committed); + Void::Testing::expect(err_code == AsyncErrorCode::cancelled); + } + + // Scenario B: stop-during-sync + sync succeeds -> receipt preserved, never cancelled + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::notify_only); + op->acquire_backend_ref(); + + int resumes = 0; + std::uint64_t receipt = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + + Void::Testing::require( + scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, nullptr, &receipt)) + .has_value()); + + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + stop_src.request_stop(); + Void::Testing::expect(op->stop_requested()); + + auto t1 = op->try_commit_value(std::uint64_t{9001}); + Void::Testing::expect(!t1.has_value()); + auto t_dup = op->try_commit_cancelled("late cancel"); + Void::Testing::expect(!t_dup.has_value()); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(observed_kind == DomainOutcomeKind::succeeded); + Void::Testing::expect_eq(receipt, std::uint64_t{9001}); + } + + // Scenario C: stop-during-sync + sync failure -> Unknown outcome after release + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::notify_only); + op->acquire_backend_ref(); + + int resumes = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + std::optional err_code{}; + + Void::Testing::require( + scope.spawn(await_op_u64_task(op, &resumes, &observed_kind, &err_code, nullptr)) + .has_value()); + + exec.drain(); + stop_src.request_stop(); + if (auto t = op->try_commit_unknown("fsync EIO"); t.has_value()) { + t->dispatch(); + } + Void::Testing::expect_eq(resumes, 0); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(err_code == AsyncErrorCode::backend_error); + Void::Testing::expect(observed_kind == DomainOutcomeKind::unknown); + } + + // Scenario D: Side-effect-free StopBehavior::settle_cancelled waits for backend_ref == 0 + { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + StopBehavior::settle_cancelled); + op->acquire_backend_ref(); + + int resumes = 0; + DomainOutcomeKind observed_kind = DomainOutcomeKind::pending; + bool has_val = true; + Void::Testing::require( + scope.spawn(await_op_void_task(op, &resumes, &observed_kind, &has_val)) + .has_value()); + + exec.drain(); + stop_src.request_stop(); + exec.drain(); + Void::Testing::expect_eq(resumes, 0); + + op->release_backend_ref_and_dispatch(); + exec.drain(); + Void::Testing::expect_eq(resumes, 1); + Void::Testing::expect(!has_val); + Void::Testing::expect(observed_kind == DomainOutcomeKind::cancelled); + } + + Void::Testing::require(scope.join_pumping().has_value()); +} + +Void::Testing::Test operation_scope_reserved_completion_lane_and_schedule_on_clock() +{ + ManualExecutor exec{1}; + TaskScope scope{exec}; + + auto op = OperationState::create({}, &exec); + int waiter_resumed = 0; + Void::Testing::require( + scope.spawn(await_op_int_task(op, 77, &waiter_resumed)).has_value()); + + // Advance waiter until it suspends on `op`. + Void::Testing::expect(exec.run_one()); + Void::Testing::expect_eq(waiter_resumed, 0); + + // Fill the normal queue capacity (max_queue = 1) completely! + std::coroutine_handle<> dummy_h = std::noop_coroutine(); + Void::Testing::require(exec.try_post(dummy_h).has_value()); + Void::Testing::expect(exec.try_post(dummy_h).error() == AdmissionError::overloaded); + + // Even with normal queue 100% saturated, reserved completion lane wakes `op`! + if (auto ticket = op->try_commit_value(77); ticket.has_value()) { + ticket->dispatch(); + } + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect_eq(waiter_resumed, 1); + + // Cancellable clock-aware schedule_on tests + Void::Time::ManualClock clock{Void::Time::MonotonicClock::time_point{std::chrono::seconds{10}}}; + const auto t_dl = clock.now() + std::chrono::seconds{5}; + Void::Result::Result sched_timeout_res{}; + Void::Result::Result sched_cancel_res{}; + std::stop_source cancel_src; + + TaskScope sched_scope{exec, TaskScopeOptions{.max_tasks = 4}, clock}; + Void::Testing::require( + sched_scope.spawn( + schedule_with_options_task( + &exec, OperationOptions{.deadline = t_dl}, &clock, &sched_timeout_res)) + .has_value()); + + // First run enters coroutine body and suspends inside schedule_on(exec, opts, clock) + Void::Testing::expect(exec.run_one()); + // Advance clock past deadline WHILE queued! + Void::Testing::require(clock.advance(std::chrono::seconds{5}).has_value()); + Void::Testing::require(sched_scope.join_pumping().has_value()); + Void::Testing::expect(!sched_timeout_res.has_value()); + Void::Testing::expect( + sched_timeout_res.error().code().value == + static_cast(AsyncErrorCode::timeout)); + + // Pre-cancelled schedule_on in fresh scope + cancel_src.request_stop(); + TaskScope cancel_scope{exec, TaskScopeOptions{.max_tasks = 4}, clock}; + Void::Testing::require( + cancel_scope.spawn( + schedule_with_options_task( + &exec, OperationOptions{.stop = cancel_src.get_token()}, &clock, &sched_cancel_res)) + .has_value()); + Void::Testing::require(cancel_scope.join_pumping().has_value()); + Void::Testing::expect(!sched_cancel_res.has_value()); + Void::Testing::expect( + sched_cancel_res.error().code().value == + static_cast(AsyncErrorCode::cancelled)); +} + +Void::Testing::Test operation_scope_join_exceptions_self_join_and_detached_owner() +{ + // 1. Nested co_await scope.join(), exception sink + stop_on_first_error + { + ManualExecutor exec; + TaskScope parent{exec}; + bool child1_saw_stop = false; + Void::Result::Result nested_join_status{}; + + auto parent_task = [](Executor* ex, + bool* saw_stop_out, + Void::Result::Result* join_status_out) -> Void::Coro::Task { + TaskScope inner{*ex}; + auto op = OperationState::create( + OperationOptions{.stop = inner.stop_token()}, + ex, + StopBehavior::settle_cancelled); + + auto wait_stop = [](std::shared_ptr> s, bool* out) -> Void::Coro::Task { + const auto res = co_await *s; + *out = !res.has_value(); + }; + auto throw_child = []() -> Void::Coro::Task { + throw std::runtime_error{"boom inside inner"}; + co_return; + }; + + Void::Testing::require(inner.spawn(wait_stop(op, saw_stop_out)).has_value()); + Void::Testing::require(inner.spawn(throw_child()).has_value()); + + *join_status_out = co_await inner.join(); + Void::Testing::expect(inner.has_exception()); + Void::Testing::expect_eq(inner.failure_count(), std::size_t{1}); + }; + + Void::Testing::require( + parent.spawn(parent_task(&exec, &child1_saw_stop, &nested_join_status)).has_value()); + Void::Testing::require(parent.join_pumping().has_value()); + Void::Testing::expect(child1_saw_stop); + Void::Testing::expect(!nested_join_status.has_value()); + } + + // 2. self_join detection when join_blocking() called inside active executor thread + { + ManualExecutor exec; + TaskScope scope{exec}; + Void::Result::Result self_res{}; + + auto self_joiner = [](Executor* ex, Void::Result::Result* out) -> Void::Coro::Task { + TaskScope dummy{*ex}; + *out = dummy.join_blocking(); + co_return; + }; + Void::Testing::require(scope.spawn(self_joiner(&exec, &self_res)).has_value()); + + Void::Testing::require(scope.join_pumping().has_value()); + Void::Testing::expect(!self_res.has_value()); + Void::Testing::expect( + self_res.error().code().value == + static_cast(AsyncErrorCode::self_join)); + } + + // 3. Individual JoinHandle co_await + DetachedOwner bounded drain + { + ManualExecutor exec; + DetachedOwner owner{exec, TaskScopeOptions{.max_tasks = 8}}; + int completed = 0; + + auto h = owner.spawn(increment_task(&completed)); + Void::Testing::require(h.has_value()); + + bool awaited_ok = false; + auto await_child = [](JoinHandle handle, bool* ok_out) -> Void::Coro::Task { + const auto res = co_await handle; + *ok_out = res.has_value(); + }; + Void::Testing::require(owner.spawn(await_child(*h, &awaited_ok)).has_value()); + + Void::Testing::require(owner.drain_pumping().has_value()); + Void::Testing::expect_eq(completed, 1); + Void::Testing::expect(h->done()); + Void::Testing::expect(awaited_ok); + } +} + +Void::Testing::Test operation_scope_concurrent_stress_tsan() +{ + ThreadedWorkerExecutor exec; + constexpr int kRounds = 64; + + for (int i = 0; i < kRounds; ++i) { + std::stop_source stop_src; + auto op = OperationState::create( + OperationOptions{.stop = stop_src.get_token()}, + &exec, + (i % 2 == 0) ? StopBehavior::notify_only : StopBehavior::settle_cancelled); + op->acquire_backend_ref(); + + std::atomic resumes{0}; + TaskScope scope{exec}; + auto awaiter = [](std::shared_ptr> state, + std::atomic* count) -> Void::Coro::Task { + const auto r = co_await *state; + (void)r; + count->fetch_add(1, std::memory_order_acq_rel); + }; + auto jh = scope.spawn(awaiter(op, &resumes)); + Void::Testing::require(jh.has_value()); + + std::thread cancel_thr([&] { + if (i % 3 != 0) { + stop_src.request_stop(); + } + }); + std::thread backend_thr([&] { + if (auto t = op->try_commit_value(i); t.has_value()) { + t->dispatch(); + } + op->release_backend_ref_and_dispatch(); + }); + + cancel_thr.join(); + backend_thr.join(); + Void::Testing::require(scope.join_blocking().has_value()); + Void::Testing::expect_eq(resumes.load(std::memory_order_acquire), 1); + } +} \ No newline at end of file From b0cb598aadafb8f65ba02af3d543901d18e0fdd1 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 03:53:02 +0300 Subject: [PATCH 5/5] docs(workflow): record Wave 4A (P1 Algorithms, Unicode, Async) verification evidence --- docs/agent-workflow/STATE.md | 35 ++++++++++++++++++++++++----- docs/agent-workflow/TASKS.md | 8 +++++++ docs/agent-workflow/VERIFICATION.md | 13 +++++++++++ 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 2f48b2b..98b83b1 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,8 @@ # Workflow state Updated: 2026-11-24. -Repository: VoidLibrary; active branch `feat/roadmap-p0-p1-foundations` (from `main` -at `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`). +Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4a` (from `main` +at `5754a7f`, merged Waves 1–3 from `feat/roadmap-p0-p1-foundations`). ## Completed objective @@ -124,9 +124,32 @@ pushing to remote) while leaving local untracked files untouched. `containers_lru_get_put` 20.59 ns, `binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 325.73 ns, `data_json_serialize_small_object` 164.76 ns. +## Verification already observed (Wave 4A — P1 Algorithms, Unicode, Async) + +- Standalone `Algorithms;Testing` (`-Werror`, `/tmp/void-w4a-alg`, `bfd6246`): `Graph` + 4/4 passed (64.2ms); `ctest` 2/2 passed (including `AlgorithmsOnly` installed consumer). +- Standalone `Unicode;Testing` (`-Werror`, `/tmp/void-w4a-unicode`, `4369fde`): `Utf` + 4/4 passed (0.3ms); `ctest` 2/2 passed (including `UnicodeOnly` installed consumer). +- Standalone `Async;Testing` (`-Werror`, `/tmp/void-w4a-async`, `c75056f`): + `OperationScope*|Executor*|Coro*` 28/28 passed (4.1ms); `ctest` 2/2 passed. +- Debug TSan subset (`Async;Testing`, `/tmp/void-w4a-async-tsan`, `c75056f`): + `OperationScope*|Executor*|ThreadPool*` 20/20 passed (34.6ms), 0 TSan races. +- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w4a-full`, 31 modules, + `c75056f`): `VoidTests` 1,345 tests — 1,342 passed, 3 intentional skips + (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (3.75s); + `ctest` 2/2 passed (`VoidTests` 3.77s, `VoidInstalledComponentConsumers` 14.45s, total + 18.21s). +- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w4a-asan`, 31 modules, + `c75056f`): `VoidTests` 1,345 tests — 1,342 passed, 3 skipped, 0 failed (11.00s), 0 leaks, + 0 UB. +- `VoidFoundationBench` post-W4A (`rev=c75056fe0707`, `/tmp/void-w4a-full/post-w4a.json`): + `harness_empty_loop` 0.39 ns, `core_uuid_parse_hyphenated` 25.48 ns, + `core_uuid_to_string` 17.09 ns, `containers_spsc_ring_push_pop` 9.16 ns, + `containers_lru_get_put` 21.81 ns, `binary_reader_u64_be` 1.36 ns, + `data_json_parse_small_object` 319.83 ns, `data_json_serialize_small_object` 168.13 ns. + ## Ownership and next step -Waves 1–3 (`P0`, `P1 Gate 1`, and `P1 Text/Containers/Binary/Data`) are complete and -verified on `feat/roadmap-p0-p1-foundations` and ready to merge locally into `main`, -before planning and executing Wave 4 (`Algorithms`, `Unicode`, `Async`, `IO`, `Runtime`, -`Testing`). +Waves 1–4A (`P0`, `P1 Gate 1`, `P1 Text/Containers/Binary/Data`, and `P1 Algorithms/Unicode/Async`) +are complete and verified on `feat/roadmap-p1-wave4a` and ready to merge locally into `main`, +before planning and executing Wave 4B (`IO`, `Runtime`, `Testing` P1). diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index dd8c9c9..25d2877 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -43,6 +43,14 @@ These tasks author plans. Future feature task IDs inside those plans remain plan | M-BINARY-02, M-BINARY-03 | `Budget.hpp`, `Writer.hpp`, `ByteBuffer.hpp`, upgraded `Reader.hpp`, expanded `Binary` consumer (`eacb8a4`) | [M-BINARY-02-03](tasks/M-BINARY-02-03.md) | VERIFIED | `Reader` 4/4, `Writer` 2/2, `ByteBuffer` 1/1 passed; `VoidInstalledComponentConsumers` (`Binary`, `RelocatedBinary`) passed | | M-DATA-02 | Exact `int64`/`uint64` JSON numbers, `number_as`, strict parser, exact `operator==`, `try_serialize`, SAX `on_int`/`on_uint`, exact reflection/config (`692f5ba`) | [M-DATA-02](tasks/M-DATA-02.md) | VERIFIED | `Json` 34/34, `Reflect` 14/14, `StrictJson` 3/3, `Update` 22/22, `Config` 12/12 passed in full RelWithDebInfo & ASan+UBSan | +## Wave 4A — P1 Algorithms, Unicode, Async (`feat/roadmap-p1-wave4a`) + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| S-ALGORITHMS-02 | `src/Algorithms/module.cmake`, `Graph.hpp` (`WorkLimits`, `IndexedGraphView`, `HasVersionStamp`, `AdjacencyView`, iterative `bfs`/`dfs`/`shortest_path_unweighted`/`topological_order` + cycle witness), `AlgorithmsOnly` consumer (`bfd6246`) | [S-ALGORITHMS-02](tasks/S-ALGORITHMS-02.md) | VERIFIED | `Graph` 4/4 and `AlgorithmsOnly` passed in `Algorithms;Testing`, full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) | +| S-UNICODE-01, S-UNICODE-02 | `src/Unicode/module.cmake`, `MANIFEST.md` (Unicode 17.0.0), `Utf.hpp` (`data_version`, `Scalar`, `UtfPolicy`, strict/one-unit-repair codecs, `_into` span transcoders, `Utf8StreamDecoder`/`Utf16StreamDecoder`), `UnicodeOnly` consumer (`4369fde`) | [S-UNICODE-01-02](tasks/S-UNICODE-01-02.md) | VERIFIED | `Utf` 4/4 and `UnicodeOnly` passed in `Unicode;Testing`, full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) | +| M-ASYNC-02, M-ASYNC-03 | `src/Async/module.cmake` (`INTERNAL_DEPS Functional Time LogState`), `Detail/Types.hpp`, `Operation.hpp` (`ResumeTicket`, `OperationState`), upgraded `Executor.hpp` (`try_post`, `post_completion`, bounded `ManualExecutor`, clock/stop `schedule_on`), `TaskScope.hpp` (`TaskScope`, `JoinHandle`, `DetachedOwner`) (`c75056f`) | [M-ASYNC-02-03](tasks/M-ASYNC-02-03.md) | VERIFIED | `OperationScope*|Executor*|Coro*` 28/28, Debug TSan 20/20 (0 races), full RelWithDebInfo (1,342 ✔), & ASan+UBSan (0 leaks/UB) | + All workers share the checkout and have disjoint file ownership defined in their persisted task specifications. Root owns all cross-cutting files and resolves contract changes. No worker owns application code, build files, existing docs/short-url.md, or Git diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index b2e8e35..ef89ac8 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -188,3 +188,16 @@ Branch: `feat/roadmap-p0-p1-foundations`. Toolchain via `dev cpp-gcc`: GCC 16.2. | Full Integrated ASan+UBSan (`692f5ba`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w3-asan/tests/VoidTests` | 1,332 tests — 1,329 passed, 3 skipped, 0 failed (10.83s), 0 leaks, 0 UB | | Wave 3 TSan Subset (`692f5ba`) | `dev cpp-gcc -c` Debug (`Containers;Async;Time;Testing`, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w3-tsan/tests/VoidTests --filter "Ring*\|Pool*\|BufferPool*\|Clock*\|Stopwatch*"` | 67/67 passed (69.8ms), 0 TSan races (`ThreadPool` 7, `ThreadPoolBackpressure` 2, `BufferPoolTests` 8, `Pool` 13, `Ring` 15, `BlockPool` 2, `Clock` 6, `Stopwatch` 14) | | Post-W3 Benchmark (`692f5ba`) | `/tmp/void-w3-full/benchmarks/VoidFoundationBench --json /tmp/void-w3-full/post-w3.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 24.94ns, `core_uuid_to_string` 16.88ns, `core_hash_fnv1a64_256b` 181.90ns, `core_hash_murmur3_256b` 68.26ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.86ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.85ns, `containers_lru_get_put` 20.59ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 325.73ns, `data_json_serialize_small_object` 164.76ns | + +## Wave 4A / P1 Algorithms, Unicode, Async Verification (2026-11-24) + +Branch: `feat/roadmap-p1-wave4a` (branched from `main` at `5754a7f`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2. + +| Scope | Command & configuration | Observed outcome | +| --- | --- | --- | +| S-ALGORITHMS-02 (`bfd6246`) | `Algorithms;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4a-alg` (`VoidTests --filter "Graph*"` & `ctest`) | `Graph` 4/4 passed (64.2ms); `ctest` 2/2 passed (`VoidTests` 0.17s, `VoidInstalledComponentConsumers` including `AlgorithmsOnly` 2.55s) | +| S-UNICODE-01..02 (`4369fde`) | `Unicode;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4a-unicode` (`VoidTests --filter "Utf*"` & `ctest`) | `Utf` 4/4 passed (0.3ms); `ctest` 2/2 passed (`VoidTests` 0.11s, `VoidInstalledComponentConsumers` including `UnicodeOnly` 2.25s) | +| M-ASYNC-02..03 (`c75056f`) | `Async;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w4a-async` & Debug TSan `/tmp/void-w4a-async-tsan` | RelWithDebInfo `OperationScope*\|Executor*\|Coro*` 28/28 (4.1ms) & `ctest` 2/2 (2.74s); Debug TSan `OperationScope*\|Executor*\|ThreadPool*` 20/20 passed (34.6ms, 0 races) | +| Full Integrated RelWithDebInfo (`c75056f`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w4a-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w4a-full --output-on-failure --timeout 180` | 31 active modules; `VoidTests`: 1,345 tests — 1,342 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (3.75s); `ctest`: 2/2 passed (`VoidTests` 3.77s + `VoidInstalledComponentConsumers` 14.45s, total 18.21s) | +| Full Integrated ASan+UBSan (`c75056f`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w4a-asan/tests/VoidTests` | 1,345 tests — 1,342 passed, 3 skipped, 0 failed (11.00s), 0 leaks, 0 UB | +| Post-W4A Benchmark (`c75056f`) | `/tmp/void-w4a-full/benchmarks/VoidFoundationBench --json /tmp/void-w4a-full/post-w4a.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.48ns, `core_uuid_to_string` 17.09ns, `core_hash_fnv1a64_256b` 185.25ns, `core_hash_murmur3_256b` 69.37ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.77ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 9.16ns, `containers_lru_get_put` 21.81ns, `binary_reader_u64_be` 1.36ns, `data_json_parse_small_object` 319.83ns, `data_json_serialize_small_object` 168.13ns |