From b34226369aedc502d0d072499b356408cbd50ee3 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 14 Jun 2026 15:37:40 +0300 Subject: [PATCH] FSM (2): declarative sub-machine continuations (startMachine + Continue) A state can now launch a full sub-FSM and have the engine resume into a named state that handles the result, instead of awaiting+branching by hand: co_return startMachine(user, tries); struct AfterLogin : Continue { // Login = Machine Task on_success(bool ok) override { co_return ok ? next() : next(); } Task on_failure(FsmError e) override { co_return fail(e.message); } }; - Sub runs on the parent's shared executor/event-mailbox/services (reuses run_child); seed data is forwarded to Sub's constructor. - The engine dispatches on its own: on entry with a pending result it calls the state's resume(), which Continue overrides to pick on_success(R)/on_failure(FsmError) by the outcome. Continue takes a nullary on_success(). A Continue handler may itself return another startMachine (chaining) or any Step. - Type-safe: startMachine static_asserts Next derives Continue and is in States<>. Mechanics: Step gains Kind::Launch carrying the target + a type-erased launcher (a coroutine that runs the sub and maps its Outcome to a LaunchResult); drive() awaits it, stashes the result, and the entered state's resume() consumes it. StateBase::resume defaults to run(). 5 new tests (SubMachine): success/failure dispatch, void-result nullary on_success, chained startMachine through Continue states, and that the sub shares the parent's event mailbox. 987 green, ASan+UBSan clean, stable across 10 runs, -Werror clean. Co-Authored-By: Claude Fable 5 --- CLAUDE.md | 3 +- include/Void/Fsm/Detail/Continuation.hpp | 87 +++++++++ include/Void/Fsm/Detail/Engine.hpp | 5 + include/Void/Fsm/Machine.hpp | 95 +++++++++- include/Void/Fsm/Step.hpp | 38 +++- src/Fsm/Engine.cpp | 7 + tests/standalone/Fsm/SubMachine.cpp | 215 +++++++++++++++++++++++ 7 files changed, 447 insertions(+), 3 deletions(-) create mode 100644 include/Void/Fsm/Detail/Continuation.hpp create mode 100644 tests/standalone/Fsm/SubMachine.cpp diff --git a/CLAUDE.md b/CLAUDE.md index 04de146..ffca48b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -151,7 +151,8 @@ Other key points: - **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests). - **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`). +- **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. - **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. - **Services**: `set_services(registry)`; `state.service()` resolves through the injected context. diff --git a/include/Void/Fsm/Detail/Continuation.hpp b/include/Void/Fsm/Detail/Continuation.hpp new file mode 100644 index 0000000..acf300f --- /dev/null +++ b/include/Void/Fsm/Detail/Continuation.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace Void::Fsm::Detail +{ + namespace Coro = Void::Coro; + + // Base for a state that resumes from a sub-machine launched via + // startMachine(). `StateT` is the owning machine's nested State + // (so the continuation inherits self()/next/fail/...); `SubResult` is the + // sub-machine's result_type. The engine enters this state carrying the + // sub's LaunchResult and calls resume(), which dispatches to on_success / + // on_failure — the FSM "finds on its own which method to call". + // + // Machine exposes it as `Continue`; users derive it and implement + // on_success(R) (and optionally on_failure). + template + class Continuation : public StateT + { + public: + + Coro::Task resume(LaunchResult lr) final + { + if (lr.ok) { + co_return co_await on_success( + std::any_cast(std::move(lr.value))); + } + co_return co_await on_failure(std::move(lr.error)); + } + + Coro::Task run() override + { + co_return this->fail( + "Continue state entered without a sub-machine result " + "(reach it via startMachine())"); + } + + protected: + + /// The sub-machine succeeded with `result`. + virtual Coro::Task on_success(SubResult result) = 0; + + /// The sub-machine failed. Default: fail the parent with the same + /// message; override to recover. + virtual Coro::Task on_failure(FsmError error) + { + co_return this->fail(std::move(error.message)); + } + }; + + // Specialisation for a void-result sub-machine: on_success() takes no + // argument. + template class Continuation : public StateT + { + public: + + Coro::Task resume(LaunchResult lr) final + { + if (lr.ok) { + co_return co_await on_success(); + } + co_return co_await on_failure(std::move(lr.error)); + } + + Coro::Task run() override + { + co_return this->fail( + "Continue state entered without a sub-machine result " + "(reach it via startMachine())"); + } + + protected: + + virtual Coro::Task on_success() = 0; + + virtual Coro::Task on_failure(FsmError error) + { + co_return this->fail(std::move(error.message)); + } + }; +} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp index 45889d8..d39fb66 100644 --- a/include/Void/Fsm/Detail/Engine.hpp +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -54,6 +54,11 @@ namespace Void::Fsm::Detail /// Main body. Default fails (a state must define run() unless it /// is reactive, in which case the engine uses its table). virtual Coro::Task run(); + + /// Entered carrying a sub-machine result (from + /// startMachine()). Default ignores it and runs run(); + /// Continue states override to dispatch on_success / on_failure. + virtual Coro::Task resume(LaunchResult result); }; struct EventEnvelope { diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index a5722d2..cff5999 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -244,6 +245,24 @@ namespace Void::Fsm return m_machine->template await_any(); } + /// Launch a sub-machine `Sub` (constructed from `args`, + /// sharing this machine's executor/events/services), then + /// transition to `Next` — which must derive + /// Continue. When Sub finishes the engine + /// calls Next's on_success(result) or on_failure(error): + /// co_return startMachine(user, 3); + template + [[nodiscard]] Step startMachine(Args&&... args) const + { + static_assert( + std::is_base_of_v< + Continue, Next>, + "startMachine: Next must derive " + "Continue"); + return m_machine->template start_machine( + std::forward(args)...); + } + template [[nodiscard]] bool has_state() const { return m_machine->template has_state(); @@ -255,6 +274,23 @@ namespace Void::Fsm Machine* m_machine{nullptr}; }; + // ── continuation states ─────────────────────────────────────── + // + // A state that resumes from a launched sub-machine. Reach it with + // `co_return startMachine(args...)`; the engine runs Sub + // then enters Next, dispatching to on_success / on_failure by the + // outcome: + // + // struct AfterLogin : Continue { // Sub = + // Machine<..,bool> + // Coro::Task on_success(bool ok) override { + // co_return ok ? next() : next(); } + // Coro::Task on_failure(FsmError e) override { + // co_return fail(e.message); } + // }; + template + using Continue = Detail::Continuation; + // ── reactive (declarative) states ───────────────────────────── // // A reactive state declares a transition table instead of an @@ -617,6 +653,43 @@ namespace Void::Fsm co_return std::move(outcome); } + /// 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. + template + [[nodiscard]] Step start_machine(Args&&... args) + { + if constexpr (requires { typename Derived::States; }) { + static_assert( + Derived::States::template contains(), + "startMachine: Next is not in States<...>"); + } + auto launcher = + [this, + tup = std::make_tuple(std::forward( + args)...)]() mutable -> Coro::Task { + auto outcome = co_await std::apply( + [this](auto&&... a) { + return this->template run_child( + std::forward(a)...); + }, + std::move(tup)); + LaunchResult lr; + if (outcome.has_value()) { + lr.ok = true; + if constexpr (!std::is_void_v< + typename Sub::result_type>) { + lr.value = std::any{std::move(*outcome)}; + } + } else { + lr.ok = false; + lr.error = std::move(outcome.error()); + } + co_return lr; + }; + return Step::launch(typeid(Next), std::move(launcher)); + } + // ── observation ─────────────────────────────────────────────── [[nodiscard]] std::string current_state() const { @@ -847,13 +920,29 @@ namespace Void::Fsm set_current(cur); auto state = it->second(); co_await state->on_enter(); - Step step = co_await state->run(); + // A state entered via startMachine resumes from the sub's + // result (Continue dispatches); otherwise it runs. + Step step; + if (m_pending_result.has_value()) { + LaunchResult pending = std::move(*m_pending_result); + m_pending_result.reset(); + step = co_await state->resume(std::move(pending)); + } else { + step = co_await state->run(); + } co_await state->on_exit(); fire_after(current_state()); switch (step.kind()) { case Step::Kind::Transition: cur = step.target(); continue; + case Step::Kind::Launch: + // Run the sub-machine, stash its result, then enter + // the Next (Continue) state. + m_pending_result.emplace( + co_await step.run_launch()); + cur = step.target(); + continue; case Step::Kind::Success: if constexpr (std::is_void_v) { co_return Outcome{}; @@ -912,6 +1001,10 @@ namespace Void::Fsm // Active child region's path provider (run_region); consulted by // state_path(). Set/cleared on the consumer thread. std::function()> m_region_probe; + + // Set by a Launch step's sub-machine result; consumed by the next + // state's resume() (a Continue dispatch). + std::optional m_pending_result; }; } // namespace Void::Fsm diff --git a/include/Void/Fsm/Step.hpp b/include/Void/Fsm/Step.hpp index 489602b..299d354 100644 --- a/include/Void/Fsm/Step.hpp +++ b/include/Void/Fsm/Step.hpp @@ -1,16 +1,31 @@ #pragma once +#include + #include +#include #include #include #include namespace Void::Fsm { + namespace Coro = Void::Coro; + struct FsmError { std::string message; }; + /// The outcome of a sub-machine launched via startMachine(): + /// `ok` with the result in `value` (a `Sub::result_type`, empty for void), + /// or `!ok` with `error`. Delivered to the Next state's Continue + /// handlers (on_success / on_failure). + struct LaunchResult { + bool ok{false}; + std::any value; + FsmError error; + }; + enum class Status { Idle, // constructed, not started Running, // worker active @@ -25,7 +40,7 @@ namespace Void::Fsm { public: - enum class Kind { Transition, Success, Fail }; + enum class Kind { Transition, Success, Fail, Launch }; [[nodiscard]] static Step transition(const std::type_info& target) { @@ -35,6 +50,20 @@ namespace Void::Fsm return s; } + /// Launch a sub-machine, then enter `target` (a Continue state) + /// with the sub's LaunchResult. `launcher` runs the sub and yields + /// its result; the engine awaits it in drive(). + [[nodiscard]] static Step + launch(const std::type_info& target, + std::function()> launcher) + { + Step s; + s.m_kind = Kind::Launch; + s.m_target = ⌖ + s.m_launcher = std::move(launcher); + return s; + } + [[nodiscard]] static Step success(std::any result) { Step s; @@ -65,12 +94,19 @@ namespace Void::Fsm return m_error; } + /// Run the sub-machine for a Launch step (yields its LaunchResult). + [[nodiscard]] Coro::Task run_launch() + { + return m_launcher(); + } + private: Kind m_kind{Kind::Fail}; const std::type_info* m_target{nullptr}; std::any m_result; FsmError m_error; + std::function()> m_launcher; }; } // namespace Void::Fsm diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp index df01bed..11fe93a 100644 --- a/src/Fsm/Engine.cpp +++ b/src/Fsm/Engine.cpp @@ -13,6 +13,13 @@ namespace Void::Fsm::Detail co_return Step::failure(FsmError{"state defines no run()"}); } + Coro::Task StateBase::resume(LaunchResult /*result*/) + { + // A plain state entered with a pending sub-machine result just runs; + // Continue overrides this to dispatch on_success / on_failure. + co_return co_await run(); + } + ExecutionContext::~ExecutionContext() { stop(); } void ExecutionContext::post(EventEnvelope env) diff --git a/tests/standalone/Fsm/SubMachine.cpp b/tests/standalone/Fsm/SubMachine.cpp new file mode 100644 index 0000000..2a5d890 --- /dev/null +++ b/tests/standalone/Fsm/SubMachine.cpp @@ -0,0 +1,215 @@ +#include +#include +#include + +#include + +using Void::Coro::Task; +using Void::Fsm::FsmError; +using Void::Fsm::Step; +namespace Fsm = Void::Fsm; + +// startMachine(args...) launches a full sub-FSM on the parent's +// shared executor/events/services, then enters Next — a Continue +// state — and the engine dispatches to on_success / on_failure by the outcome. + +namespace +{ + // Sub-machine seeded by constructor arg: doubles `seed`, fails if negative. + class Doubler : public Fsm::Machine + { + public: + + int seed; + + struct Run : State { + Task run() override + { + if (self().seed < 0) { + co_return fail("negative"); + } + co_return succeed(self().seed * 2); + } + }; + using States = Fsm::States; + + explicit Doubler(int s = 0) : seed(s) {} + }; + + class Calc : public Fsm::Machine + { + public: + + int input = 0; + + struct Start : State { + Task run() override + { + co_return startMachine( + self().input); + } + }; + struct AfterDouble : Continue { + Task on_success(int v) override + { + co_return succeed("doubled:" + std::to_string(v)); + } + Task on_failure(FsmError e) override + { + co_return succeed("failed:" + e.message); + } + }; + using States = Fsm::States; + + explicit Calc(int in) : input(in) {} + }; +} // namespace + +// @tag integration +Void::Testing::Test submachine_success_dispatches_on_success() +{ + Calc fsm{5}; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, std::string{"doubled:10"}); +} + +// @tag integration +Void::Testing::Test submachine_failure_dispatches_on_failure() +{ + Calc fsm{-1}; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, std::string{"failed:negative"}); +} + +// ── void-result sub-machine ───────────────────────────────────────────────── + +namespace +{ + class Pinger : public Fsm::Machine + { + public: + + struct Ping : State { + Task run() override { co_return succeed(); } + }; + using States = Fsm::States; + }; + + class Host : public Fsm::Machine + { + public: + + struct Go : State { + Task run() override + { + co_return startMachine(); + } + }; + struct Done : Continue { + Task on_success() override { co_return succeed(42); } + }; + using States = Fsm::States; + }; +} // namespace + +// @tag integration +Void::Testing::Test submachine_void_result_calls_nullary_on_success() +{ + Host fsm; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 42); +} + +// ── chained startMachine (a Continue state launches another) ───────────────── + +namespace +{ + class Chain : public Fsm::Machine + { + public: + + struct A : State { + Task run() override + { + co_return startMachine(3); // 3 -> 6 + } + }; + struct B : Continue { + Task on_success(int v) override + { + co_return startMachine(v); // 6 -> 12 + } + }; + struct C : Continue { + Task on_success(int v) override + { + co_return succeed(v); + } + }; + using States = Fsm::States; + }; +} // namespace + +// @tag integration +Void::Testing::Test submachine_chains_through_continue_states() +{ + Chain fsm; + const auto outcome = fsm.run_blocking(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 12); +} + +// ── the sub-machine shares the parent's event mailbox ──────────────────────── + +namespace +{ + struct Tick { + }; + + class WaitSub : public Fsm::Machine + { + public: + + struct W : State { + Task run() override + { + co_await await_event(); + co_return succeed(7); + } + }; + using States = Fsm::States; + }; + + class Outer : public Fsm::Machine + { + public: + + struct Begin : State { + Task run() override + { + co_return startMachine(); + } + }; + struct Fin : Continue { + Task on_success(int v) override + { + co_return succeed(v); + } + }; + using States = Fsm::States; + }; +} // namespace + +// @tag integration +Void::Testing::Test submachine_shares_parent_event_mailbox() +{ + Outer fsm; + fsm.start(); + fsm.post(Tick{}); // delivered to the sub-machine awaiting on the shared ctx + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, 7); +}