diff --git a/CLAUDE.md b/CLAUDE.md index 47684ac..3113d1f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -164,6 +164,7 @@ Header layout (include `` — a thin umbrella): `Machine.hpp` - **Events**: `co_await await_event()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post(e)` is lock-free from any thread. - **Nesting**: `co_await run_child(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected`) — the imperative form, branch on it yourself. - **Sub-machine continuations (declarative)**: `co_return startMachine(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue` takes a nullary `on_success()`). `Next` must derive `Continue` (a `static_assert` enforces it) and be in `States<>`. A `Continue` handler may itself return another `startMachine` (chaining) or any normal `Step`. Mechanics: a `Step::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's `resume()` (overridden by `Continue`) dispatches — a plain state entered with a pending result just `run()`s. +- **Parallel / orthogonal regions**: `co_await run_parallel()` runs several sub-machines concurrently on the shared executor (interleaved — when one parks on an event, another runs; **multi-waiter mailbox**) and joins **all**, yielding `std::tuple`. `run_parallel_any<…>()` resolves on the **first** to finish → `std::variant<…::Outcome…>`; losers keep running cooperatively (not preemptible), so they're kept alive by the spawned tasks until they finish — a loser parked forever leaks its frame until the machine stops. Children are default-constructed and share events/services. Join uses a small latch coroutine (`Async::spawn` + a completion counter); single-consumer ⇒ no lock. - **Composite sub-states (hierarchy)**: `co_await run_region()` is `run_child` with introspection — the calling state's `on_enter`/`on_exit` wrap the child region, and the parent's `state_path()` reports the parent→child chain (`{Composite, …child leaf}`) while it runs. Map the child's `Outcome` to a sibling transition (`r ? next() : next()`). Parent-level multi-event handling via `co_await await_any()` → `std::variant` (e.g. a region waits for `Tick` or `Cancel` at one level). Coroutines aren't preemptible mid-flight, so child cancellation is **cooperative**: the region awaits a shared `Cancel` event (events route to the deepest awaiter) and returns a failing `Outcome` the parent maps — no frame is abandoned. - **Dynamic**: `add()` / `add_if(cond)`; `next` fails; `has_state()` lets a state branch. - **Direct control**: fluent `send(e1, e2, …)` (variadic `post`); free in-state jumps via `goto_state()` (any registered state, no declared transition); external `jump()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove()` / `set_initial()` / `replace()`. diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index 180358a..ac4140a 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -274,6 +274,25 @@ namespace Void::Fsm std::forward(args)...); } + /// Orthogonal regions: run `Subs...` concurrently on the + /// shared executor and join all, yielding a + /// std::tuple (children share events/ + /// services; map the tuple to a sibling transition). + template + [[nodiscard]] auto run_parallel() const + { + return m_machine->template run_parallel(); + } + + /// Race orthogonal regions: resolve on the first to finish, + /// yielding std::variant (losers keep + /// running cooperatively). + template + [[nodiscard]] auto run_parallel_any() const + { + return m_machine->template run_parallel_any(); + } + /// Await whichever of several event types arrives first, /// yielding a std::variant. Handles multiple events /// at one level (e.g. a parent watching Cancel alongside a @@ -769,6 +788,152 @@ namespace Void::Fsm co_return child.template take_outcome(); } + /// Orthogonal regions: run `Subs...` concurrently on the shared + /// executor (interleaved — when one parks on an event, another + /// runs) and join all, yielding a tuple of their Outcomes. Children + /// are default-constructed and share this machine's + /// events/services. + template + [[nodiscard]] Coro::Task...>> + run_parallel() + { + auto children = std::make_unique>(); + std::apply( + [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, + *children); + + struct Latch { + int remaining; + std::coroutine_handle<> waiter{}; + Async::Executor* exec; + void arrive() + { + if (--remaining == 0 && waiter) { + exec->post(waiter); + } + } + }; + auto latch = std::make_shared( + static_cast(sizeof...(Subs)), + std::coroutine_handle<>{}, &m_ctx->executor()); + + std::apply( + [&](auto&... c) { + (Async::spawn(m_ctx->executor(), + [](auto& child, std::shared_ptr l) + -> Coro::Task { + co_await child.drive(); + l->arrive(); + }(c, latch)), + ...); + }, + *children); + + struct Awaiter { + std::shared_ptr latch; + [[nodiscard]] bool await_ready() const noexcept + { + return latch->remaining == 0; + } + void await_suspend(std::coroutine_handle<> h) const + { + latch->waiter = h; + } + void await_resume() const noexcept {} + }; + co_await Awaiter{latch}; + + co_return std::apply( + [](auto&... c) { + return std::tuple...>{ + c.template take_outcome()...}; + }, + *children); + } + + /// Like run_parallel but resolves on the **first** child to finish, + /// yielding a std::variant holding the winner's + /// outcome. The losers keep running cooperatively (coroutines + /// aren't preemptible) — the children are kept alive by the spawned + /// tasks until they finish, so a loser parked forever leaks its + /// frame until the machine stops. Document at call sites. + template + [[nodiscard]] Coro::Task...>> + run_parallel_any() + { + // Shared so losers (which outlive this call) keep it alive. + auto children = std::make_shared>(); + std::apply( + [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, + *children); + + struct Latch { + int first{-1}; + std::coroutine_handle<> waiter{}; + Async::Executor* exec; + void arrive(int idx) + { + if (first < 0) { + first = idx; + if (waiter) { + exec->post(waiter); + } + } + } + }; + auto latch = std::make_shared( + -1, std::coroutine_handle<>{}, &m_ctx->executor()); + + int idx = 0; + std::apply( + [&](auto&... c) { + ( + [&] { + const int my = idx++; + Async::spawn( + m_ctx->executor(), + [](auto& child, + std::shared_ptr> + keep, + std::shared_ptr + l, + int i) -> Coro::Task { + co_await child.drive(); + l->arrive(i); + (void)keep; + }(c, children, latch, my)); + }(), + ...); + }, + *children); + + struct Awaiter { + std::shared_ptr latch; + [[nodiscard]] bool await_ready() const noexcept + { + return latch->first >= 0; + } + void await_suspend(std::coroutine_handle<> h) const + { + latch->waiter = h; + } + void await_resume() const noexcept {} + }; + co_await Awaiter{latch}; + + const auto winner = static_cast(latch->first); + co_return [&](std::index_sequence) + -> std::variant...> { + std::variant...> v; + ((I == winner ? (void)(v.template emplace( + std::get(*children) + .template take_outcome())) + : void()), + ...); + return v; + }(std::index_sequence_for{}); + } + /// Build a Launch step: run `Sub` (constructed from `args`) on this /// machine's shared executor, then enter `Next` carrying Sub's /// outcome as a LaunchResult. Reached via State::startMachine. diff --git a/tests/standalone/Fsm/Parallel.cpp b/tests/standalone/Fsm/Parallel.cpp new file mode 100644 index 0000000..a492987 --- /dev/null +++ b/tests/standalone/Fsm/Parallel.cpp @@ -0,0 +1,143 @@ +#include +#include +#include + +using Void::Coro::Task; +using Void::Fsm::Step; +namespace Fsm = Void::Fsm; + +// Orthogonal regions: run_parallel() runs both sub-machines concurrently +// on the shared executor and joins all. Each child parks on its own event at +// the same time — only possible with the multi-waiter mailbox. + +namespace +{ + struct GoLeft { + }; + struct GoRight { + }; + + class Left : public Fsm::Machine + { + public: + + using Success = int; + struct W : State { + Task run() + { + co_await await_event(); + co_return succeed(1); + } + }; + using States = Fsm::States; + }; + + class Right : public Fsm::Machine + { + public: + + using Success = int; + struct W : State { + Task run() + { + co_await await_event(); + co_return succeed(2); + } + }; + using States = Fsm::States; + }; + + // Joins both children: their results sum to 3. + class Both : public Fsm::Machine + { + public: + + using Success = int; + struct Run : State { + Task run() + { + auto [a, b] = co_await run_parallel(); + co_return succeed((a.has_value() ? *a : 0) + + (b.has_value() ? *b : 0)); + } + }; + using States = Fsm::States; + + explicit Both(Fsm::MachineOptions o = {}) : Fsm::Machine(o) {} + }; +} // namespace + +// @tag integration +Void::Testing::Test parallel_regions_join_all() +{ + Both fsm; + fsm.start(); + // Both children are parked on their own events at the same time. + fsm.send(GoLeft{}, GoRight{}); + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 3); +} + +// @tag integration +Void::Testing::Test parallel_regions_join_all_embedder() +{ + // Deterministic: drive in embedder mode, both children park, then release. + Both fsm{Fsm::MachineOptions{.own_worker = false}}; + fsm.start(); + while (fsm.pump() > 0) { + } // Run -> spawns Left+Right -> both park on events + fsm.send(GoRight{}); // release right first + while (fsm.pump() > 0) { + } + Void::Testing::expect(!fsm.finished()); // left still parked + fsm.send(GoLeft{}); + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 3); +} + +// ── run_parallel_any (first to finish) ────────────────────────────────────── + +namespace +{ + // Races Left and Right; reports which won and its value. + class Race : public Fsm::Machine + { + public: + + using Success = int; + struct Run : State { + Task run() + { + auto v = co_await run_parallel_any(); + // index 1 == Right (value 2); index 0 == Left (value 1) + if (v.index() == 1 && std::get<1>(v).has_value()) { + co_return succeed(100 + *std::get<1>(v)); + } + if (v.index() == 0 && std::get<0>(v).has_value()) { + co_return succeed(*std::get<0>(v)); + } + co_return succeed(-1); + } + }; + using States = Fsm::States; + + explicit Race(Fsm::MachineOptions o = {}) : Fsm::Machine(o) {} + }; +} // namespace + +// @tag integration +Void::Testing::Test parallel_any_resolves_on_first_finisher() +{ + Race fsm{Fsm::MachineOptions{.own_worker = false}}; + fsm.start(); + while (fsm.pump() > 0) { + } // both park + // Right's resume is posted first, so Right finishes first and wins; both + // events are delivered so neither child leaks a parked frame. + fsm.send(GoRight{}, GoLeft{}); + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 102); // 100 + Right's 2 +}