FSM (4): one signature-inferred State (drops Reactive/Continue bases)

There is now a single state base, `State`. The engine infers each state's
role purely from member signatures via P2996 — no `override`, no
framework-mandated names:

  struct Work : State {                          // entry
    Coro::Task<Step> run() { ... }
    Coro::Task<Step> run(Cfg c) { ... }          // startup-entry (launch data)
  };
  struct Idle : State {                          // reactive
    void transitions(TransitionBuilder& on) { on.event<Go>().to<Run>(); }
  };
  struct After : State {                         // continuation
    Coro::Task<Step> ok(ChildSuccess auto s) { use s.value; }
    Coro::Task<Step> no(ChildFailure auto f) { use f.value; }
  };

- Detail/Roles.hpp: ChildSuccess/ChildFailure concepts over boxes, plus the
  reflection selectors (invoke_entry / invoke_startup / invoke_handler /
  dispatch_result / has_transitions / make_driver). At add<S>() a per-state
  driver thunk is stored (reactive table vs entry, by whether S has a
  TransitionBuilder& member); drive() calls it. startMachine<Sub, Next>(data)
  builds a Launch step carrying a launcher (injects data into Sub's initial
  startup-entry) + a dispatcher (dispatch_result<Next, Sub>) that builds the
  ChildSuccess/Failure box and calls Next's matching handler.
- Removed Reactive/Continue<R> bases, StateKind/kind(), StateBase::run/resume
  (only on_enter/on_exit remain virtual). Reactive states keep the same DSL.
- Toolchain note: template-for + member splicing fails inside a coroutine
  body in this GCC build, so the selectors are non-coroutines returning a
  Task<Step> (plain Step wrapped via ready_task). Discovery is
  invocability-based — no parameter-type reflection (P3096). Probe-verified.

All FSM tests migrated to the nameless style (SubMachine: Continue ->
ChildSuccess/Failure handlers + startup-entry seeding; reactive states drop
the Reactive base/override). 995 tests (992 green, 3 skipped), ASan clean,
-Werror clean; lone intermittent failure remains the pre-existing racy
plugin hot-reload-under-load test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-15 01:20:56 +03:00
1 parent 9e9eb838ea
commit ec9e466d7a
20 files changed
+536 -358

No files matched your search

+120 -134
View File
@@ -4,11 +4,11 @@
#include <Void/Async/Task.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Fsm/Detail/Awaiter.hpp>
#include <Void/Fsm/Detail/Continuation.hpp>
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Detail/Introspect.hpp>
#include <Void/Fsm/Detail/Reactive.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/Roles.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Log/Log.hpp>
@@ -70,21 +70,23 @@ namespace Void::Fsm
std::uint64_t step{0};
};
// ── Machine<Derived, ResultT> ─────────────────────────────────────────
// ── Machine<Derived> ──────────────────────────────────────────────────
//
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive
// it, declare states as nested structs deriving `State`, list them in
// `using States = Fsm::States<...>`, and implement each state's async
// run() to return next<S>() / succeed(...) / fail(...). States reach
// their owning machine (and its data + sub-methods) via self().
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it,
// declare states as nested structs deriving the single `State`, list them
// in `using States = Fsm::States<...>`. The engine infers each state's role
// from member signatures (entry / reactive table / continuation handlers);
// states reach their machine (data + sub-methods) via self(). Result types
// are the nested `Success`/`Failure` (default void).
//
// class Login : public Void::Fsm::Machine<Login, bool> {
// class Login : public Void::Fsm::Machine<Login> {
// public:
// using Success = Token;
// int attempts = 0;
// struct Check : State {
// Coro::Task<Step> run() override {
// if (++self().attempts > 3) co_return fail("locked");
// co_return self().service<IAuth>().ok() ? succeed(true)
// struct Check : State { // entry by signature
// Coro::Task<Step> run() {
// if (++self().attempts > 3) co_return fail();
// co_return self().service<IAuth>().ok() ? succeed(Token{})
// : next<Check>();
// }
// };
@@ -282,19 +284,16 @@ namespace Void::Fsm
return m_machine->template await_any<Es...>();
}
/// Launch a sub-machine `Sub` (constructed from `args`,
/// sharing this machine's executor/events/services), then
/// transition to `Next` — which must derive
/// Continue<Sub::result_type>. When Sub finishes the engine
/// calls Next's on_success(result) or on_failure(error):
/// co_return startMachine<Login, AfterLogin>(user, 3);
/// Launch a sub-machine `Sub` (startup data routed to its
/// initial-state startup-entry; shares this machine's
/// executor/events/services), then transition to `Next`.
/// When Sub finishes the engine calls Next's signature
/// -matched handler — a member taking `ChildSuccess auto`
/// (Sub succeeded) or `ChildFailure auto` (Sub failed):
/// co_return startMachine<Login, AfterLogin>(seed);
template <typename Sub, typename Next, typename... Args>
[[nodiscard]] Step startMachine(Args&&... args) const
{
static_assert(
std::is_base_of_v<Continue<Sub>, Next>,
"startMachine<Sub, Next>: Next must derive "
"Continue<Sub>");
return m_machine->template start_machine<Sub, Next>(
std::forward<Args>(args)...);
}
@@ -310,106 +309,33 @@ namespace Void::Fsm
Machine* m_machine{nullptr};
};
// ── continuation states ───────────────────────────────────────
// ── one State, signature-inferred roles ───────────────────────
//
// A state that resumes from a launched sub-machine. Reach it with
// `co_return startMachine<Sub, Next>(args...)`; the engine runs Sub
// then enters Next, dispatching to on_success / on_failure by the
// outcome:
// There is a single base, `State`. The engine infers what each
// state does from member signatures (no `override`, no fixed
// names):
// - entry : a member returning Step/Coro::Task<Step>,
// no params (a startup-data overload may take
// the sub's startup argument);
// - reactive : a member taking `TransitionBuilder&` (the
// declarative table below);
// - continuation : members taking `ChildSuccess auto` /
// `ChildFailure auto` (the sub's typed result
// after `startMachine<Sub, This>()`).
//
// struct AfterLogin : Continue<bool> { // Sub =
// Machine<..,bool>
// Coro::Task<Step> on_success(bool ok) override {
// co_return ok ? next<Home>() : next<Locked>(); }
// Coro::Task<Step> on_failure(FsmError e) override {
// co_return fail(e.message); }
// };
template <typename Sub>
using Continue = Detail::Continuation<State, Sub>;
// ── reactive (declarative) states ─────────────────────────────
// struct Idle : State { // reactive
// void transitions(TransitionBuilder& on) {
// on.event<Go>().to<Running>();
// on.after(5s).to<TimedOut>(); } };
// struct After : State { // continuation
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
// Coro::Task<Step> no(ChildFailure auto f){ ... } };
//
// A reactive state declares a transition table instead of an
// imperative run(): it waits for the declared events (or a
// timeout), checks guards in order, runs actions, and
// transitions. Mix freely with imperative State subclasses.
//
// struct Idle : Reactive {
// void transitions(TransitionBuilder& on) override {
// on.event<Go>().guard([](Idle& s, const Go& g){...})
// .action([](Idle& s, const Go&){...})
// .to<Running>();
// on.event<Stop>().to<Done>();
// on.after(5s).to<TimedOut>();
// }
// };
// The declarative transition DSL lives in Detail/Reactive.hpp;
// these aliases give reactive states the ergonomic nested names.
// The declarative DSL lives in Detail/Reactive.hpp; these aliases
// give the `transitions(TransitionBuilder&)` member its type.
using TransitionTable = Detail::TransitionTable<Derived>;
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
class Reactive : public State
{
public:
[[nodiscard]] Detail::StateKind
kind() const noexcept override
{
return Detail::StateKind::Reactive;
}
/// Declare this state's event/timeout transitions.
virtual void transitions(TransitionBuilder& on) = 0;
/// Build this state's table without running it — used by
/// describe()/to_mermaid() for introspection.
void collect(TransitionTable& table)
{
TransitionBuilder builder{table};
transitions(builder);
}
Coro::Task<Step> run() final
{
TransitionTable table;
collect(table);
std::vector<const std::type_info*> types;
types.reserve(table.events.size());
for (const auto& e : table.events) {
types.push_back(e.type);
}
for (;;) {
std::optional<std::chrono::steady_clock::time_point>
deadline;
if (table.has_timeout) {
deadline = std::chrono::steady_clock::now() +
table.timeout_after;
}
auto ev = co_await this->machine().await_any_event(
types, deadline);
if (!ev) {
co_return std::move(table.timeout_step);
}
Derived& d = this->self();
bool matched = false;
for (auto& e : table.events) {
if (*e.type != *ev->type) {
continue;
}
if (e.guard && !e.guard(d, ev->value)) {
continue;
}
if (e.action) {
co_await e.action(d, ev->value);
}
co_return std::move(e.step);
}
(void)matched; // unmatched event is dropped
}
}
};
// ── construction ──────────────────────────────────────────────
explicit Machine(Options options = {}) : m_options(options)
{
@@ -448,6 +374,20 @@ namespace Void::Fsm
s->m_machine = this;
return s;
});
// Signature-inferred driver thunk (entry or reactive table).
m_drivers.emplace(key, Detail::make_driver<S>());
// describe() collector: fills a table if S is reactive.
m_collectors.emplace(
key,
[](Detail::StateBase& base,
TransitionTable& table) -> bool {
if constexpr (Detail::has_transitions<S>()) {
Detail::collect_transitions(static_cast<S&>(base),
table);
return true;
}
return false;
});
}
template <typename S> void initial()
@@ -495,6 +435,8 @@ namespace Void::Fsm
m_name_to_type.erase(m_names[static_cast<std::size_t>(idx)]);
m_names.erase(m_names.begin() + idx);
m_factories.erase(key);
m_drivers.erase(key);
m_collectors.erase(key);
m_index.erase(idxIt);
// Re-pack the indices of states that followed S.
for (auto& [k, v] : m_index) {
@@ -838,14 +780,24 @@ namespace Void::Fsm
Derived::States::template contains<Next>(),
"startMachine<Sub, Next>: Next is not in States<...>");
}
using Init = Detail::InitialStateOf<Sub>;
auto launcher =
[this,
tup = std::make_tuple(std::forward<Args>(
args)...)]() mutable -> Coro::Task<LaunchResult> {
// Run Sub on the shared executor and read its raw result so
// Success / Failure / Fault are all distinguishable.
Sub child = std::make_from_tuple<Sub>(std::move(tup));
[this, ... data = std::forward<Args>(
args)]() mutable -> Coro::Task<LaunchResult> {
// Run Sub on the shared executor. Startup data (if any) is
// delivered to Sub's initial-state startup-entry via an
// injector, not the constructor.
Sub child;
child.attach(m_ctx, m_services);
if constexpr (sizeof...(Args) > 0) {
child.m_startup_injector =
[... d = std::move(data)](
Detail::StateBase& base) mutable
-> Coro::Task<Step> {
return Detail::invoke_startup<Init>(
static_cast<Init&>(base), std::move(d)...);
};
}
co_await child.drive();
LaunchResult lr;
switch (child.m_status.load(std::memory_order_acquire)) {
@@ -865,7 +817,14 @@ namespace Void::Fsm
}
co_return lr;
};
return Step::launch(typeid(Next), std::move(launcher));
Step::Dispatch dispatch =
[](Detail::StateBase& base,
LaunchResult lr) -> Coro::Task<Step> {
return Detail::dispatch_result<Next, Sub>(
static_cast<Next&>(base), std::move(lr));
};
return Step::launch(typeid(Next), std::move(launcher),
std::move(dispatch));
}
// ── observation ───────────────────────────────────────────────
@@ -924,11 +883,11 @@ namespace Void::Fsm
si.name = name;
si.initial = (name == initial_name);
const auto* ti = m_name_to_type.at(name);
auto state = m_factories.at(std::type_index{*ti})();
si.reactive = state->kind() == Detail::StateKind::Reactive;
if (auto* reactive = dynamic_cast<Reactive*>(state.get())) {
TransitionTable table;
reactive->collect(table);
const std::type_index key{*ti};
auto state = m_factories.at(key)();
TransitionTable table;
si.reactive = m_collectors.at(key)(*state, table);
if (si.reactive) {
for (const auto& e : table.events) {
si.edges.push_back(
EdgeInfo{e.event_name, e.target_name,
@@ -1102,6 +1061,7 @@ namespace Void::Fsm
fault("no initial state");
co_return;
}
bool first = true;
for (;;) {
// Apply an external jump<S>() at this transition boundary.
if (const auto* j =
@@ -1109,6 +1069,7 @@ namespace Void::Fsm
j != nullptr) {
cur = j;
m_pending_result.reset();
m_pending_dispatch = nullptr;
}
const auto it = m_factories.find(std::type_index{*cur});
if (it == m_factories.end()) {
@@ -1118,20 +1079,29 @@ namespace Void::Fsm
set_current(cur);
auto state = it->second();
co_await state->on_enter();
// A state entered via startMachine resumes from the sub's
// result; otherwise it runs.
// Decide how the state runs: a launched sub's result (via
// the bound dispatcher), the startup injector for the first
// state, or the signature-inferred driver thunk.
Step step;
if (m_pending_result.has_value()) {
if (m_pending_dispatch) {
LaunchResult pending = std::move(*m_pending_result);
auto dispatch = std::move(m_pending_dispatch);
m_pending_result.reset();
m_pending_dispatch = nullptr;
if (pending.kind == LaunchResult::Kind::Fault) {
fault(std::move(pending.fault.message));
co_return;
}
step = co_await state->resume(std::move(pending));
step = co_await dispatch(*state, std::move(pending));
} else if (first && m_startup_injector) {
auto inject = std::move(m_startup_injector);
m_startup_injector = nullptr;
step = co_await inject(*state);
} else {
step = co_await state->run();
step = co_await m_drivers.at(std::type_index{*cur})(
*state);
}
first = false;
co_await state->on_exit();
fire_after(current_state());
switch (step.kind()) {
@@ -1141,6 +1111,7 @@ namespace Void::Fsm
case Step::Kind::Launch:
m_pending_result.emplace(
co_await step.run_launch());
m_pending_dispatch = step.take_dispatch();
cur = step.target();
continue;
case Step::Kind::Success:
@@ -1214,6 +1185,15 @@ namespace Void::Fsm
std::type_index,
std::function<std::unique_ptr<Detail::StateBase>()>>
m_factories;
// Per-state signature-inferred driver thunk (entry / reactive).
std::unordered_map<std::type_index, std::function<Coro::Task<Step>(
Detail::StateBase&)>>
m_drivers;
// Per-state describe() collector (reactive table, if any).
std::unordered_map<
std::type_index,
std::function<bool(Detail::StateBase&, TransitionTable&)>>
m_collectors;
std::unordered_map<std::type_index, int> m_index;
std::vector<std::string> m_names;
std::unordered_map<std::string, const std::type_info*>
@@ -1235,8 +1215,14 @@ namespace Void::Fsm
std::function<std::vector<std::string>()> m_region_probe;
// Set by a Launch step's sub-machine result; consumed by the next
// state's resume() (a Continue<R> dispatch).
// state via the bound dispatcher below.
std::optional<LaunchResult> m_pending_result;
Step::Dispatch m_pending_dispatch;
// Seeds the initial state's startup-entry with launch data (set by
// the parent's launcher before driving this machine).
std::function<Coro::Task<Step>(Detail::StateBase&)>
m_startup_injector;
// External jump request (jump<S>()); applied by drive() at the
// next transition boundary.