FSM (6): parallel / orthogonal regions (run_parallel, run_parallel_any)

Builds on the multi-waiter mailbox: a state can run several sub-machines
concurrently on the shared executor.

- co_await run_parallel<A, B, ...>() spawns each child (Async::spawn) and
  joins ALL, yielding std::tuple<A::Outcome, ...>. Children run interleaved
  on the single executor — when one parks on an event, another runs (only
  possible now that the mailbox holds multiple waiters).
- co_await run_parallel_any<A, B, ...>() resolves on the FIRST to finish,
  yielding std::variant<A::Outcome, ...> of the winner. Losers keep running
  cooperatively (coroutines aren't preemptible), so the children are kept
  alive by the spawned tasks (shared_ptr keepalive) until they finish — a
  loser parked forever leaks its frame until the machine stops (documented).
- Join is a small latch coroutine (completion counter + a parked parent
  handle posted when it reaches zero / on first arrival); single-consumer,
  no lock. Children default-constructed, share events/services.

3 new tests (Parallel): join-all (worker + deterministic embedder, both
children park concurrently), first-finisher race. 998 tests (995 green, 3
skipped), ASan/UBSan clean (validates the spawned-task lifetimes — no UAF/
leak), -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-15 01:34:48 +03:00
1 parent c6b7306614
commit 9d6be56847
3 files changed
+309

No files matched your search

+1
View File
@@ -164,6 +164,7 @@ Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp`
- **Events**: `co_await await_event<E>()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post<E>(e)` is lock-free from any thread.
- **Nesting**: `co_await run_child<Sub>(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected<R, FsmError>`) — the imperative form, branch on it yourself.
- **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(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<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (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<R>`) dispatches — a plain state entered with a pending result just `run()`s.
- **Parallel / orthogonal regions**: `co_await run_parallel<A, B, …>()` 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<A::Outcome, …>`. `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<Sub>()` 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<Done>() : next<Recover>()`). Parent-level multi-event handling via `co_await await_any<E1, E2, …>()` → `std::variant<Es...>` (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<S>()` / `add_if<S>(cond)`; `next<unregistered>` fails; `has_state<S>()` lets a state branch.
- **Direct control**: fluent `send(e1, e2, …)` (variadic `post`); free in-state jumps via `goto_state<S>()` (any registered state, no declared transition); external `jump<S>()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at<S>()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove<S>()` / `set_initial<S>()` / `replace<S, T>()`.
+165
View File
@@ -274,6 +274,25 @@ namespace Void::Fsm
std::forward<Args>(args)...);
}
/// Orthogonal regions: run `Subs...` concurrently on the
/// shared executor and join all, yielding a
/// std::tuple<Subs::Outcome...> (children share events/
/// services; map the tuple to a sibling transition).
template <typename... Subs>
[[nodiscard]] auto run_parallel() const
{
return m_machine->template run_parallel<Subs...>();
}
/// Race orthogonal regions: resolve on the first to finish,
/// yielding std::variant<Subs::Outcome...> (losers keep
/// running cooperatively).
template <typename... Subs>
[[nodiscard]] auto run_parallel_any() const
{
return m_machine->template run_parallel_any<Subs...>();
}
/// Await whichever of several event types arrives first,
/// yielding a std::variant<Es...>. 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<Sub>();
}
/// 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 <typename... Subs>
[[nodiscard]] Coro::Task<std::tuple<Detail::OutcomeOf<Subs>...>>
run_parallel()
{
auto children = std::make_unique<std::tuple<Subs...>>();
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<Latch>(
static_cast<int>(sizeof...(Subs)),
std::coroutine_handle<>{}, &m_ctx->executor());
std::apply(
[&](auto&... c) {
(Async::spawn(m_ctx->executor(),
[](auto& child, std::shared_ptr<Latch> l)
-> Coro::Task<void> {
co_await child.drive();
l->arrive();
}(c, latch)),
...);
},
*children);
struct Awaiter {
std::shared_ptr<Latch> 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<Detail::OutcomeOf<Subs>...>{
c.template take_outcome<Subs>()...};
},
*children);
}
/// Like run_parallel but resolves on the **first** child to finish,
/// yielding a std::variant<Subs::Outcome...> 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 <typename... Subs>
[[nodiscard]] Coro::Task<std::variant<Detail::OutcomeOf<Subs>...>>
run_parallel_any()
{
// Shared so losers (which outlive this call) keep it alive.
auto children = std::make_shared<std::tuple<Subs...>>();
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<Latch>(
-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<std::tuple<Subs...>>
keep,
std::shared_ptr<Latch>
l,
int i) -> Coro::Task<void> {
co_await child.drive();
l->arrive(i);
(void)keep;
}(c, children, latch, my));
}(),
...);
},
*children);
struct Awaiter {
std::shared_ptr<Latch> 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<std::size_t>(latch->first);
co_return [&]<std::size_t... I>(std::index_sequence<I...>)
-> std::variant<Detail::OutcomeOf<Subs>...> {
std::variant<Detail::OutcomeOf<Subs>...> v;
((I == winner ? (void)(v.template emplace<I>(
std::get<I>(*children)
.template take_outcome<Subs>()))
: void()),
...);
return v;
}(std::index_sequence_for<Subs...>{});
}
/// 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.
+143
View File
@@ -0,0 +1,143 @@
#include <Void/Fsm/Fsm.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
using Void::Coro::Task;
using Void::Fsm::Step;
namespace Fsm = Void::Fsm;
// Orthogonal regions: run_parallel<A, B>() 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<Left>
{
public:
using Success = int;
struct W : State {
Task<Step> run()
{
co_await await_event<GoLeft>();
co_return succeed(1);
}
};
using States = Fsm::States<W>;
};
class Right : public Fsm::Machine<Right>
{
public:
using Success = int;
struct W : State {
Task<Step> run()
{
co_await await_event<GoRight>();
co_return succeed(2);
}
};
using States = Fsm::States<W>;
};
// Joins both children: their results sum to 3.
class Both : public Fsm::Machine<Both>
{
public:
using Success = int;
struct Run : State {
Task<Step> run()
{
auto [a, b] = co_await run_parallel<Left, Right>();
co_return succeed((a.has_value() ? *a : 0) +
(b.has_value() ? *b : 0));
}
};
using States = Fsm::States<Run>;
explicit Both(Fsm::MachineOptions o = {}) : Fsm::Machine<Both>(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<Race>
{
public:
using Success = int;
struct Run : State {
Task<Step> run()
{
auto v = co_await run_parallel_any<Left, Right>();
// 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<Run>;
explicit Race(Fsm::MachineOptions o = {}) : Fsm::Machine<Race>(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
}