FSM v2 (D): hierarchy ergonomics — composite regions, await_any, state_path
- run_region<Sub>() — run_child plus introspection: shares the parent's executor/event mailbox/services, the calling state's on_enter/on_exit wrap it, and the parent's state_path() reports the parent->child chain while it runs. The caller maps the child's Outcome to a sibling transition. - await_any<Es...>() — typed multi-event await yielding std::variant<Es...>, so one state handles several event types at a single level (parent-level watching alongside a child region's own events). - state_path() now appends an active region child's path (consumer- consistent; deterministic in pump() mode). current_state() stays the lock-free cross-thread read. Coroutines aren't preemptible mid-flight, so composite 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. Documented in CLAUDE.md. 3 new tests (Hierarchy): region result drives the parent transition, parent cancel routes to a sibling, state_path reports parent->child. 982 green, ASan+UBSan clean, stable across 10 runs, -Werror clean. Completes the FSM v2 plan (A-D). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d9842129c7
commit
667045564e
3 files changed
+226
-5
No files matched your search
@@ -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<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>`).
|
||||
- **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.
|
||||
- **Services**: `set_services(registry)`; `state.service<I>()` 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<bool>` sub-step), `next_or<Fallback>(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<I>()` call without being patched.
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@@ -26,6 +27,7 @@
|
||||
#include <typeinfo>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
@@ -214,6 +216,30 @@ namespace Void::Fsm
|
||||
std::forward<Args>(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<Work>();
|
||||
/// co_return r ? next<Done>() : next<Recover>();
|
||||
template <typename Sub, typename... Args>
|
||||
[[nodiscard]] auto run_region(Args&&... args) const
|
||||
{
|
||||
return m_machine->template run_region<Sub>(
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// child region's own events).
|
||||
template <typename... Es>
|
||||
[[nodiscard]] auto await_any() const
|
||||
{
|
||||
return m_machine->template await_any<Es...>();
|
||||
}
|
||||
|
||||
template <typename S> [[nodiscard]] bool has_state() const
|
||||
{
|
||||
return m_machine->template has_state<S>();
|
||||
@@ -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<Es...>. Lets one state react to
|
||||
/// several event types (parent-level handling for child regions).
|
||||
template <typename... Es> [[nodiscard]] auto await_any()
|
||||
{
|
||||
struct Awaiter {
|
||||
Detail::ExecutionContext* ctx;
|
||||
std::array<const std::type_info*, sizeof...(Es)> 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<Es...> await_resume()
|
||||
{
|
||||
std::optional<std::variant<Es...>> out;
|
||||
((env.type != nullptr && *env.type == typeid(Es)
|
||||
? (out.emplace(std::in_place_type<Es>,
|
||||
std::any_cast<Es>(
|
||||
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 <typename Rep, typename Period>
|
||||
[[nodiscard]] auto delay(std::chrono::duration<Rep, Period> 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 <typename Sub, typename... Args>
|
||||
[[nodiscard]] Coro::Task<typename Sub::Outcome>
|
||||
run_region(Args&&... args)
|
||||
{
|
||||
Sub child{std::forward<Args>(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<std::size_t>(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<std::string> state_path() const
|
||||
{
|
||||
std::vector<std::string> 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<void(const Transition&)> m_observer;
|
||||
std::vector<Interceptor> 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<std::vector<std::string>()> m_region_probe;
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
@@ -0,0 +1,124 @@
|
||||
#include <Void/Fsm/Fsm.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
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<Work, std::string>
|
||||
{
|
||||
public:
|
||||
|
||||
struct Waiting : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto ev = co_await await_any<Tick, Cancel>();
|
||||
if (std::holds_alternative<Cancel>(ev)) {
|
||||
co_return fail("cancelled");
|
||||
}
|
||||
co_return succeed(std::string{"ticked"});
|
||||
}
|
||||
};
|
||||
using States = Void::Fsm::States<Waiting>;
|
||||
|
||||
explicit Work(MachineOptions opts = {})
|
||||
: Void::Fsm::Machine<Work, std::string>(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<Job, std::string>
|
||||
{
|
||||
public:
|
||||
|
||||
struct Running : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
auto r = co_await run_region<Work>();
|
||||
if (r.has_value()) {
|
||||
co_return succeed(*r);
|
||||
}
|
||||
co_return next<Aborted>();
|
||||
}
|
||||
};
|
||||
struct Aborted : State {
|
||||
Task<Step> run() override
|
||||
{
|
||||
co_return succeed(std::string{"aborted"});
|
||||
}
|
||||
};
|
||||
using States = Void::Fsm::States<Running, Aborted>;
|
||||
|
||||
explicit Job(MachineOptions opts = {})
|
||||
: Void::Fsm::Machine<Job, std::string>(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<std::string> 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});
|
||||
}
|
||||
Reference in new issue
Block a user