diff --git a/CLAUDE.md b/CLAUDE.md index 6fb1145..04de146 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -152,9 +152,12 @@ 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`). +- **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. -- **Observation**: `current_state()` is a lock-free atomic-index read of an immutable name table (P2996 `identifier_of`, fallback to indexed names). +- **Observation**: `current_state()` is a lock-free atomic-index read of an immutable name table (P2996 `identifier_of`, fallback to indexed names). `state_path()` is the same but appends an active `run_region` child's path — consumer-consistent (read it from within the machine or once settled; deterministic in `pump()` mode). +- **Introspection**: `describe()` lists registered states (name, reactive?, initial?) plus the transitions declared by reactive states (event/target names, guard-present); imperative `run()`-chosen edges aren't statically knowable so those states are edgeless nodes. `to_mermaid()` renders a `stateDiagram-v2` string. +- **Error policies / middleware**: state helpers `delay(d)`, `with_retry(times, backoff, attempt)` (retries a `Coro::Task` sub-step), `next_or(step)` (route a failing `Step` to a fallback state). `add_interceptor({before(Transition), after(state_name)})` runs ordered hooks around each transition; `observe(fn)` is the single read-only observer. - **Persistence**: `serialize()` → `{state name, on_serialize data}`; `restore()` on an un-started machine resumes at the named state (override `on_serialize`/`on_restore` for derived data, reflection-JSON friendly). - Hot-plug + state-saving are re-expressed via services: plugins provide `IService` impls; `PluginServiceBinding` swaps the registry entry on reload (state migrated by the plugin's v2 ABI), so running FSMs pick up the new impl on the next `service()` call without being patched. diff --git a/include/Void/Fsm/Fsm.hpp b/include/Void/Fsm/Fsm.hpp index 2c03073..b3b68ce 100644 --- a/include/Void/Fsm/Fsm.hpp +++ b/include/Void/Fsm/Fsm.hpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -26,6 +27,7 @@ #include #include #include +#include #include #if __has_include() @@ -214,6 +216,30 @@ namespace Void::Fsm std::forward(args)...); } + /// Enter a child region (composite sub-state): a nested + /// machine sharing this machine's executor, event mailbox + /// and services. This state's on_enter/on_exit wrap it, and + /// state_path() reports the parent→child chain while it + /// runs. Map the child's Outcome to a sibling transition: + /// auto r = co_await run_region(); + /// co_return r ? next() : next(); + template + [[nodiscard]] auto run_region(Args&&... args) const + { + return m_machine->template run_region( + std::forward(args)...); + } + + /// 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 + /// child region's own events). + template + [[nodiscard]] auto await_any() const + { + return m_machine->template await_any(); + } + template [[nodiscard]] bool has_state() const { return m_machine->template has_state(); @@ -747,6 +773,41 @@ namespace Void::Fsm m_ctx.get(), std::move(types), {}, false, deadline}; } + /// Typed multi-event await: suspend until one of `Es...` arrives, + /// returning it as std::variant. Lets one state react to + /// several event types (parent-level handling for child regions). + template [[nodiscard]] auto await_any() + { + struct Awaiter { + Detail::ExecutionContext* ctx; + std::array types; + Detail::EventEnvelope env; + + [[nodiscard]] bool await_ready() + { + return ctx->try_take_any(types, env); + } + void await_suspend(std::coroutine_handle<> h) + { + ctx->set_waiter(types, h, &env, nullptr, + std::nullopt); + } + [[nodiscard]] std::variant await_resume() + { + std::optional> out; + ((env.type != nullptr && *env.type == typeid(Es) + ? (out.emplace(std::in_place_type, + std::any_cast( + std::move(env.value))), + true) + : false) || + ...); + return std::move(*out); + } + }; + return Awaiter{m_ctx.get(), {(&typeid(Es))...}, {}}; + } + /// Suspend for `duration`, then resume (timer-driven). template [[nodiscard]] auto delay(std::chrono::duration d) @@ -781,6 +842,24 @@ namespace Void::Fsm co_return co_await child.drive(); } + /// Composite sub-state: run `Sub` as a child region sharing this + /// machine's executor, event mailbox and services, and expose its + /// active state through this machine's state_path() while it runs + /// (parent→child chain). Returns the child's Outcome, which the + /// caller maps to a sibling transition. The calling state's + /// on_enter/on_exit naturally wrap the region. + template + [[nodiscard]] Coro::Task + run_region(Args&&... args) + { + Sub child{std::forward(args)...}; + child.attach(m_ctx, m_services); + m_region_probe = [&child] { return child.state_path(); }; + auto outcome = co_await child.drive(); + m_region_probe = nullptr; + co_return std::move(outcome); + } + // ── observation ─────────────────────────────────────────────── [[nodiscard]] std::string current_state() const { @@ -791,14 +870,25 @@ namespace Void::Fsm return m_names[static_cast(idx)]; } - /// Active state chain (root → leaf). Currently a single entry; - /// hierarchy (Phase D) extends it. + /// Active state chain (root → leaf). When a child region is + /// running (run_region), its path is appended, so a composite + /// state reports {composite, ...child leaf}. Unlike the lock-free + /// current_state(), the region part is consumer-consistent: read + /// it from within the machine or once it has settled (it is + /// deterministic in embedder/pump mode). [[nodiscard]] std::vector state_path() const { + std::vector path; if (auto s = current_state(); !s.empty()) { - return {std::move(s)}; + path.push_back(std::move(s)); } - return {}; + if (m_region_probe) { + auto sub = m_region_probe(); + path.insert(path.end(), + std::make_move_iterator(sub.begin()), + std::make_move_iterator(sub.end())); + } + return path; } /// All registered state names (registration order). @@ -1097,6 +1187,10 @@ namespace Void::Fsm std::function m_observer; std::vector m_interceptors; std::uint64_t m_step{0}; + + // Active child region's path provider (run_region); consulted by + // state_path(). Set/cleared on the consumer thread. + std::function()> m_region_probe; }; } // namespace Void::Fsm diff --git a/tests/standalone/Fsm/Hierarchy.cpp b/tests/standalone/Fsm/Hierarchy.cpp new file mode 100644 index 0000000..bc162e4 --- /dev/null +++ b/tests/standalone/Fsm/Hierarchy.cpp @@ -0,0 +1,124 @@ +#include +#include +#include + +#include +#include +#include + +using Void::Coro::Task; +using Void::Fsm::MachineOptions; +using Void::Fsm::Step; + +// Composite sub-states: a parent state runs a child region (run_region) that +// shares the parent's executor, event mailbox and services. The child's +// Outcome drives the parent's next transition; a parent-level await_any lets +// the region react to several event types (cooperative cancel). + +namespace +{ + struct Tick { + }; + struct Cancel { + }; + + // Child region: waits for either Tick (succeed) or Cancel (fail), + // handling both at one level via await_any. + class Work : public Void::Fsm::Machine + { + public: + + struct Waiting : State { + Task run() override + { + auto ev = co_await await_any(); + if (std::holds_alternative(ev)) { + co_return fail("cancelled"); + } + co_return succeed(std::string{"ticked"}); + } + }; + using States = Void::Fsm::States; + + explicit Work(MachineOptions opts = {}) + : Void::Fsm::Machine(opts) + { + } + }; + + // Parent: a composite Running state enters the Work region and maps its + // result — success passes the value through, failure routes to a sibling. + class Job : public Void::Fsm::Machine + { + public: + + struct Running : State { + Task run() override + { + auto r = co_await run_region(); + if (r.has_value()) { + co_return succeed(*r); + } + co_return next(); + } + }; + struct Aborted : State { + Task run() override + { + co_return succeed(std::string{"aborted"}); + } + }; + using States = Void::Fsm::States; + + explicit Job(MachineOptions opts = {}) + : Void::Fsm::Machine(opts) + { + } + }; +} // namespace + +// @tag integration +Void::Testing::Test composite_region_result_drives_parent() +{ + Job fsm; + fsm.start(); + fsm.post(Tick{}); // region succeeds -> parent passes "ticked" through + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, std::string{"ticked"}); +} + +// @tag integration +Void::Testing::Test parent_cancel_routes_to_sibling() +{ + Job fsm; + fsm.start(); + fsm.post(Cancel{}); // region fails -> parent transitions to Aborted + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, std::string{"aborted"}); +} + +// state_path() reports the parent→child chain while a region is active. +// Embedder mode keeps the single consumer on this thread, so the read is +// deterministic. +Void::Testing::Test state_path_reports_parent_child() +{ + Job fsm{MachineOptions{.own_worker = false}}; + fsm.start(); + + // Drive until the region parks on await_any: parent in Running, child in + // Waiting. + while (fsm.pump() > 0) { + } + const std::vector expected{"Running", "Waiting"}; + Void::Testing::expect(fsm.state_path() == expected); + + // Release the region and run to completion. + fsm.post(Tick{}); + const auto outcome = fsm.wait(); + Void::Testing::expect(outcome.has_value()); + Void::Testing::expect_eq(*outcome, std::string{"ticked"}); + // Region gone → path collapses to the (final) parent state only. + Void::Testing::expect_eq(fsm.state_path().size(), std::size_t{1}); +}