Remove the two old FSMs ahead of the inheritance-based rewrite

Deletes the compile-time Void::StateMachine and the builder-based runtime
Void::Fsm (Definition/Machine/Event/PluginBehavior + their standalone
tests, the FSM behaviour plugins, and the FSM x Plugin integration test
and its CMake wiring). The general-purpose Plugin module and its stateful
hot-reload tests are untouched.

Both are being replaced by a single inheritance + coroutine workflow FSM
(next phase). 936 tests green (51 old FSM/StateMachine tests removed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 00:26:30 +03:00
1 parent 6b5f61f00a
commit 04cf1998bd
20 files changed
+3 -3793

No files matched your search

-323
View File
@@ -1,323 +0,0 @@
#pragma once
#include <Void/Async/Task.hpp>
#include <Void/Detail/Enum.hpp>
#include <Void/Fsm/Event.hpp>
#include <chrono>
#include <cstddef>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Void::Fsm
{
class Machine;
/// Guards run synchronously on the machine worker; keep them cheap.
using Guard = std::function<bool(const Machine&, const Event&)>;
/// Actions may be coroutines: the run-to-completion step finishes only
/// when the returned task completes (events arriving meanwhile queue).
using Action = std::function<Coro::Task<void>(Machine&, const Event&)>;
/// Plain function convenience form, wrapped into an Action.
using SyncAction = std::function<void(Machine&, const Event&)>;
enum class History : std::uint8_t { None, Shallow, Deep };
struct DefError {
std::string message;
};
/// Lightweight handle to a state being defined / addressed.
class StateRef
{
public:
constexpr StateRef() = default;
constexpr explicit StateRef(StateId id) : m_id(id) {}
[[nodiscard]] constexpr StateId id() const noexcept { return m_id; }
[[nodiscard]] constexpr bool valid() const noexcept
{
return m_id != kInvalidState;
}
constexpr bool operator==(const StateRef&) const = default;
private:
StateId m_id{kInvalidState};
};
// ── MachineDef ────────────────────────────────────────────────────────
// Immutable, flattened machine description produced by Builder::build.
// Shared by Machines via shared_ptr; hot-swap replaces the pointer.
class MachineDef
{
public:
struct Timeout {
std::chrono::milliseconds after{};
EventId fires{kInvalidEvent};
};
struct StateNode {
std::string name;
StateId parent{kInvalidState};
std::vector<StateId> children;
StateId initial{kInvalidState}; // composites only
bool parallel{false};
History history{History::None};
Action entry; // may be empty
Action exit; // may be empty
std::vector<EventId> deferred;
std::optional<Timeout> timeout;
int depth{0};
};
struct TransitionDef {
StateId from{kInvalidState};
EventId on{kInvalidEvent};
StateId to{kInvalidState}; // kInvalidState => internal
Guard guard; // may be empty (always true)
Action action; // may be empty
bool internal{false};
};
[[nodiscard]] const StateNode& state(StateId id) const
{
return m_states[id];
}
[[nodiscard]] std::size_t state_count() const noexcept
{
return m_states.size();
}
/// Transitions leaving `from`, in definition order.
[[nodiscard]] const std::vector<std::size_t>&
transitions_from(StateId from) const
{
return m_transitions_by_state[from];
}
[[nodiscard]] const TransitionDef&
transition(std::size_t index) const
{
return m_transitions[index];
}
[[nodiscard]] std::optional<StateId>
state_id(std::string_view name) const
{
const auto it = m_state_ids.find(std::string{name});
if (it == m_state_ids.end()) {
return std::nullopt;
}
return it->second;
}
[[nodiscard]] std::optional<EventId>
event_id(std::string_view name) const
{
const auto it = m_event_ids.find(std::string{name});
if (it == m_event_ids.end()) {
return std::nullopt;
}
return it->second;
}
/// Enum overload: matches the enumerator's identifier name.
template <typename E>
requires std::is_enum_v<E>
[[nodiscard]] std::optional<EventId> event_id(E e) const
{
#ifdef VOID_HAS_ENUM_REFLECTION
return event_id(Void::Detail::enum_name(e));
#else
(void)e;
return std::nullopt;
#endif
}
[[nodiscard]] std::string_view event_name(EventId id) const
{
return m_event_names[id];
}
[[nodiscard]] std::size_t event_count() const noexcept
{
return m_event_names.size();
}
/// True if `ancestor` is `state` or one of its ancestors.
[[nodiscard]] bool is_ancestor_or_self(StateId ancestor,
StateId state) const;
/// Lowest common ancestor of two states.
[[nodiscard]] StateId lca(StateId a, StateId b) const;
private:
friend class Builder;
friend class TransitionBuilder;
std::vector<StateNode> m_states;
std::vector<TransitionDef> m_transitions;
std::vector<std::vector<std::size_t>> m_transitions_by_state;
std::unordered_map<std::string, StateId> m_state_ids;
std::unordered_map<std::string, EventId> m_event_ids;
std::vector<std::string> m_event_names;
};
// ── TransitionBuilder ─────────────────────────────────────────────────
class Builder;
class TransitionBuilder
{
public:
TransitionBuilder& guard(Guard g);
TransitionBuilder& action(Action a);
TransitionBuilder& action(SyncAction a);
private:
friend class Builder;
TransitionBuilder(Builder& builder, std::size_t index)
: m_builder(&builder), m_index(index)
{
}
Builder* m_builder;
std::size_t m_index;
};
// ── Builder ───────────────────────────────────────────────────────────
// Fluent definition of states, transitions, and behaviors. build()
// validates and produces an immutable MachineDef.
class Builder
{
public:
Builder();
/// The implicit root pseudo-state (parent of all top-level
/// states).
[[nodiscard]] static constexpr StateRef root() noexcept
{
return StateRef{kRootState};
}
/// Declare (or look up) a state. Names are globally unique.
StateRef state(std::string_view name, StateRef parent = root());
/// Declare (or look up) an event by name.
EventId event(std::string_view name);
/// Declare an event from an enum value's identifier.
template <typename E>
requires std::is_enum_v<E>
EventId event(E e)
{
#ifdef VOID_HAS_ENUM_REFLECTION
return event(Void::Detail::enum_name(e));
#else
static_assert(std::is_enum_v<E> && false,
"enum events require P2996 reflection");
#endif
}
/// Declare one leaf state per enumerator of E under `parent`.
template <typename E>
requires std::is_enum_v<E>
Builder& states_from_enum(StateRef parent = root())
{
#ifdef VOID_HAS_ENUM_REFLECTION
static constexpr auto enumerators =
std::define_static_array(std::meta::enumerators_of(^^E));
template for (constexpr auto e : enumerators)
{
(void)state(std::meta::identifier_of(e), parent);
}
return *this;
#else
static_assert(std::is_enum_v<E> && false,
"states_from_enum requires P2996 reflection");
#endif
}
/// Resolve an already-declared state by enum value.
template <typename E>
requires std::is_enum_v<E>
StateRef state_of(E e)
{
#ifdef VOID_HAS_ENUM_REFLECTION
return state(Void::Detail::enum_name(e));
#else
static_assert(std::is_enum_v<E> && false,
"enum states require P2996 reflection");
#endif
}
/// Mark `child` as the initial state of its parent.
Builder& initial(StateRef child);
/// Mark a composite as a parallel (orthogonal-region) holder:
/// entering it activates every child region simultaneously.
Builder& parallel(StateRef composite);
Builder& on_entry(StateRef state, Action action);
Builder& on_entry(StateRef state, SyncAction action);
Builder& on_exit(StateRef state, Action action);
Builder& on_exit(StateRef state, SyncAction action);
/// Remember the last active substate(s) of `composite` and
/// restore them when it is re-entered.
Builder& history(StateRef composite, History kind);
/// While `state` is active, events with `id` are stashed and
/// re-injected after the next state change.
Builder& defer(StateRef state, EventId id);
/// After `after` continuously active in `state`, synthesize
/// the `fires` event.
Builder& timeout(StateRef state,
std::chrono::milliseconds after,
EventId fires);
/// External transition. Returns a fluent handle for attaching
/// .guard() / .action().
TransitionBuilder transition(StateRef from, EventId on,
StateRef to);
/// Internal transition: action fires without exit/entry.
TransitionBuilder internal(StateRef in, EventId on);
/// Validate and produce the immutable definition.
[[nodiscard]] std::expected<std::shared_ptr<const MachineDef>,
DefError>
build();
private:
friend class TransitionBuilder;
MachineDef m_def; // built up in place
bool m_consumed{false}; // build() may only be called once
};
/// Wrap a plain function into a coroutine Action.
[[nodiscard]] Action wrap_sync(SyncAction fn);
} // namespace Void::Fsm
-42
View File
@@ -1,42 +0,0 @@
#pragma once
#include <any>
#include <cstdint>
#include <string>
#include <utility>
namespace Void::Fsm
{
/// Interned identifiers. Both are assigned by the Builder; names are
/// the stable identity (they survive definition swaps and serialize
/// into hot-reload state), ids are the fast runtime currency.
using StateId = std::uint32_t;
using EventId = std::uint32_t;
inline constexpr StateId kInvalidState = ~StateId{0};
inline constexpr EventId kInvalidEvent = ~EventId{0};
/// The root pseudo-state always has id 0.
inline constexpr StateId kRootState = 0;
/// A type-erased event instance. The payload is optional; guards and
/// actions retrieve it with std::any_cast against the type they
/// expect.
struct Event {
EventId id{kInvalidEvent};
std::any payload{};
};
/// Outcome of one run-to-completion step for a posted event.
enum class SendResult : std::uint8_t {
Handled, // at least one transition fired
Deferred, // stashed by an active state's defer list
Unhandled, // no active state had a matching transition
Dropped // machine stopped before processing
};
struct FsmError {
std::string message;
};
} // namespace Void::Fsm
-273
View File
@@ -1,273 +0,0 @@
#pragma once
#include <Void/Async/Executor.hpp>
#include <Void/Async/MpscQueue.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <Void/Fsm/Definition.hpp>
#include <Void/Fsm/Event.hpp>
#include <array>
#include <atomic>
#include <chrono>
#include <coroutine>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <semaphore>
#include <thread>
#include <unordered_map>
#include <vector>
namespace Void::Fsm
{
/// Lock-free observable snapshot of the active configuration. Holds
/// the active *leaf* states (compositions are implied by ancestry);
/// fixed-size so the seqlock copy is trivial.
struct StateSnapshot {
static constexpr std::size_t kMaxLeaves = 16;
std::array<StateId, kMaxLeaves> leaves{};
std::uint32_t leaf_count{0};
std::uint64_t step{0}; // run-to-completion step counter
bool running{false};
[[nodiscard]] bool contains(StateId id) const noexcept
{
for (std::uint32_t i = 0; i < leaf_count; ++i) {
if (leaves[i] == id) {
return true;
}
}
return false;
}
};
// ── Machine ───────────────────────────────────────────────────────────
// Runtime engine driving one MachineDef.
//
// Concurrency model (MPSC): any thread may post()/send(); exactly one
// consumer — the owned worker thread (default) or the embedding thread
// via run_one()/run_pending() — executes run-to-completion steps. All
// mutable machine state is owned by that consumer; observers read a
// seqlock-protected snapshot.
//
// Hot path costs: post() = wait-free queue push (+ a semaphore release
// only when the worker parked); current()/is_in() = seqlock read,
// retry on contention; no mutexes anywhere on these paths.
struct MachineOptions {
/// Spawn a worker thread in start(). When false the embedder
/// drives the machine with run_pending().
bool own_worker = true;
};
class Machine
{
public:
using Options = MachineOptions;
explicit Machine(std::shared_ptr<const MachineDef> def,
Options options = {});
/// Stops the machine (drains nothing; pending events are
/// dropped) and joins the worker.
~Machine();
Machine(const Machine&) = delete;
Machine& operator=(const Machine&) = delete;
Machine(Machine&&) = delete;
Machine& operator=(Machine&&) = delete;
// ── lifecycle ─────────────────────────────────────────────────
/// Enter the initial configuration (entry actions run on the
/// consumer). With own_worker the worker starts here.
void start();
/// Process queued events, then stop. Joins the worker.
void stop();
[[nodiscard]] bool running() const noexcept;
// ── event submission (any thread) ─────────────────────────────
/// Fire-and-forget. Lock-free. Returns false if the machine
/// is not accepting events (not started or stopped).
bool post(Event event);
template <typename E>
requires std::is_enum_v<E>
bool post(E e, std::any payload = {})
{
const auto def = definition();
const auto id = def->event_id(e);
if (!id.has_value()) {
return false;
}
return post(Event{*id, std::move(payload)});
}
/// Awaitable submission: co_await machine.send(ev) resumes
/// after the event's run-to-completion step with its result.
/// Resumption runs on the machine's consumer thread unless a
/// resume executor is given.
class SendAwaitable
{
public:
[[nodiscard]] bool await_ready() const noexcept
{
return m_result.has_value();
}
void await_suspend(std::coroutine_handle<> h);
[[nodiscard]] SendResult await_resume() const noexcept
{
return m_result.value_or(SendResult::Dropped);
}
private:
friend class Machine;
SendAwaitable(Machine& machine, Event event,
Async::Executor* resume_on)
: m_machine(&machine), m_event(std::move(event)),
m_resume_on(resume_on)
{
}
Machine* m_machine;
Event m_event;
Async::Executor* m_resume_on;
std::optional<SendResult> m_result;
};
[[nodiscard]] SendAwaitable
send(Event event, Async::Executor* resume_on = nullptr)
{
return SendAwaitable{*this, std::move(event), resume_on};
}
/// Blocking submission: returns once the event's step ran.
SendResult send_wait(Event event);
// ── observation (any thread, lock-free) ───────────────────────
[[nodiscard]] StateSnapshot current() const noexcept;
/// True if `state` (leaf or composite) is in the active
/// configuration.
[[nodiscard]] bool is_in(StateId state) const;
[[nodiscard]] bool is_in(std::string_view state) const;
[[nodiscard]] std::shared_ptr<const MachineDef> definition() const
{
return m_def.load(std::memory_order_acquire);
}
// ── hot swap / persistence ────────────────────────────────────
/// Replace the definition between run-to-completion steps.
/// Active states are re-mapped by name; the queue keeps
/// flowing. States whose names vanished fall back to the new
/// definition's initial configuration for that region.
void swap_definition(std::shared_ptr<const MachineDef> def);
/// Serialize the active configuration + history (by state
/// name) for hot-reload / persistence. Processed as a control
/// step on the consumer; safe from any thread while running.
[[nodiscard]] Json::Value serialize_state();
/// Restore a configuration produced by serialize_state()
/// (optionally migrated). Must be called before start().
[[nodiscard]] std::expected<void, FsmError>
restore_state(const Json::Value& state);
// ── embedder-driven mode (own_worker = false) ─────────────────
/// Process queued events/control work; returns the number of
/// envelopes handled. Single consumer only.
std::size_t run_pending();
/// Block the calling thread (the consumer) until `until`
/// returns true, processing events as they arrive. Intended
/// for tests and simple embedders.
void run_until(const std::function<bool()>& until);
private:
struct Envelope; // Event + completion plumbing
struct HistoryRecord {
std::vector<StateId> leaves; // deep: leaves; shallow: child
};
// consumer-side core
void consumer_loop();
std::size_t drain_once();
bool handle_envelope(Envelope& env);
SendResult dispatch_event(const Event& event);
void enter_initial_configuration();
void perform_transition(const MachineDef::TransitionDef& t,
StateId source_leaf,
const Event& event);
void enter_target(StateId lca, StateId target, const Event& event);
void descend_into(StateId state, const Event& event);
void exit_to_lca(StateId leaf, StateId lca, const Event& event);
void exit_single(StateId state, const Event& event);
void enter_single(StateId state, const Event& event);
void run_action(const Action& action, const Event& event);
void publish_snapshot();
void rearm_timers();
void fire_due_timers();
void reinject_deferred();
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
next_deadline() const;
void apply_swap(std::shared_ptr<const MachineDef> next);
std::vector<std::string> active_leaf_names() const;
void wake_consumer() noexcept;
// immutable-ish shared state
std::atomic<std::shared_ptr<const MachineDef>> m_def;
Options m_options;
// MPSC queue + parking
Async::MpscQueue<Envelope*> m_queue;
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_accepting{false};
std::atomic<bool> m_stop{false};
std::thread m_worker;
// seqlock snapshot
mutable std::atomic<std::uint64_t> m_seq{0};
StateSnapshot m_snapshot{};
// ── consumer-owned state (no synchronization) ─────────────────
std::shared_ptr<const MachineDef> m_active_def;
std::vector<bool> m_active; // by StateId
std::vector<StateId> m_leaves; // active leaves, region order
std::unordered_map<StateId, HistoryRecord> m_history;
std::vector<Envelope*> m_deferred; // stashed events
bool m_deferred_dirty{false}; // re-inject after change
std::uint64_t m_step{0};
Async::ManualExecutor m_executor; // drives coroutine actions
struct TimerArm {
StateId state;
std::chrono::steady_clock::time_point deadline;
EventId fires;
std::uint64_t generation;
};
std::vector<TimerArm> m_timers;
std::vector<std::uint64_t> m_activation; // per state
// configuration captured by restore_state(), applied silently
// (no entry actions) when start() runs
std::optional<Json::Value> m_pending_restore;
};
} // namespace Void::Fsm
-53
View File
@@ -1,53 +0,0 @@
#pragma once
#include <Void/Fsm/Definition.hpp>
#include <expected>
#include <memory>
namespace Void::Fsm
{
// ── IFsmBehaviorPack ──────────────────────────────────────────────────
// A plugin exposes FSM states/events/guards/actions by implementing
// this interface and returning it from the optional C entry point
//
// extern "C" Void::Fsm::IFsmBehaviorPack* void_plugin_fsm_behaviors();
//
// The host calls register_into(builder) while assembling a machine
// definition, then build()s it. Because the actions/guards the pack
// installs are std::functions whose code lives in the plugin .so, the
// machine (and its MachineDef) must not outlive the plugin: keep a
// Plugin::PluginHandle pinned for the machine's lifetime, and rely on
// PluginManager's dlclose_on_swap=false so the code pages stay mapped
// across reloads. See tests/internal/FsmPluginHotReload.cpp.
//
// The interface is a same-compiler C++ ABI (like IPlugin): the host and
// plugin must be built with the same toolchain, which they are within
// this project.
class IFsmBehaviorPack
{
public:
virtual ~IFsmBehaviorPack() = default;
/// Declare this pack's states, events, and transitions on the
/// builder. Called once per machine-definition build.
virtual void register_into(Builder& builder) = 0;
};
using fsm_behaviors_fn = IFsmBehaviorPack* (*)();
inline constexpr const char* kFsmBehaviorsSymbol =
"void_plugin_fsm_behaviors";
/// Build an immutable machine definition from a behaviour pack.
[[nodiscard]] inline std::expected<std::shared_ptr<const MachineDef>,
DefError>
build_machine_def(IFsmBehaviorPack& pack)
{
Builder builder;
pack.register_into(builder);
return builder.build();
}
} // namespace Void::Fsm
-209
View File
@@ -1,209 +0,0 @@
#pragma once
#include <concepts>
#include <functional>
#include <optional>
#include <stdexcept>
#include <string_view>
#include <type_traits>
#include <variant>
namespace Void::StateMachine
{
// ── Concepts ──────────────────────────────────────────────────────────────────
template <typename S>
concept State = std::is_default_constructible_v<S>;
template <typename E>
concept Event = std::copyable<E>;
// ── Transition helper ─────────────────────────────────────────────────────────
// A transition<From, Ev, To> captures one arc: From --[Ev]--> To.
// The user specializes `transitions` for their state machine type.
template <typename From, typename Ev, typename To>
struct Transition
{
using from = From;
using event = Ev;
using to = To;
};
// ── StateMachine ──────────────────────────────────────────────────────────────
//
// Template parameters:
// States — type list of all states, first element is the initial state
// Transitions — type list of Transition<F,E,T> arcs
//
// Usage:
// using MyFSM = StateMachine<
// std::tuple<Idle, Running, Done>,
// std::tuple<
// Transition<Idle, StartEvent, Running>,
// Transition<Running, StopEvent, Done>
// >
// >;
template <typename StatesTuple, typename TransitionsTuple>
class StateMachine;
namespace Detail
{
// Collect all states from the transitions tuple
template <typename... Ts>
struct StateVariantOf;
template <typename... States>
struct StateVariantOf<std::tuple<States...>>
{
using type = std::variant<States...>;
};
// Does the Transition list contain a matching arc?
template <typename CurrentState, typename Ev, typename TransTuple>
struct FindTransition;
template <typename CS, typename Ev>
struct FindTransition<CS, Ev, std::tuple<>>
{
using to = void; // no match
};
template <typename CS, typename Ev, typename Head, typename... Tail>
struct FindTransition<CS, Ev, std::tuple<Head, Tail...>>
{
using to = std::conditional_t<
std::is_same_v<typename Head::from, CS> &&
std::is_same_v<typename Head::event, Ev>,
typename Head::to,
typename FindTransition<CS, Ev, std::tuple<Tail...>>::to>;
};
} // namespace Detail
template <typename... States, typename... Transitions>
class StateMachine<std::tuple<States...>, std::tuple<Transitions...>>
{
public:
using StateVariant = std::variant<States...>;
using TransitionTuple = std::tuple<Transitions...>;
StateMachine() = default;
// Current state index (0-based, matches variant index).
[[nodiscard]] std::size_t state_index() const noexcept
{
return state_.index();
}
// True if current state is S.
template <typename S>
[[nodiscard]] bool is() const noexcept
{
return std::holds_alternative<S>(state_);
}
// Access current state as S (throws std::bad_variant_access if wrong).
template <typename S>
[[nodiscard]] const S& as() const
{
return std::get<S>(state_);
}
template <typename S>
[[nodiscard]] S& as()
{
return std::get<S>(state_);
}
// Try to access state, returns nullptr if wrong state.
template <typename S>
[[nodiscard]] const S* try_as() const noexcept
{
return std::get_if<S>(&state_);
}
// Send an event. Returns true if a transition was found and taken.
template <typename Ev>
bool send(const Ev& ev)
{
bool transitioned = false;
std::visit(
[&]<typename CurState>(CurState& cur) {
using To =
typename Detail::FindTransition<CurState, Ev,
TransitionTuple>::to;
if constexpr (!std::is_void_v<To>) {
on_exit(cur);
state_ = To{};
on_enter(std::get<To>(state_), ev);
transitioned = true;
}
},
state_);
return transitioned;
}
// Register a callback fired when entering state S.
template <typename S, std::invocable<const S&> F>
void on_enter(F&& f)
{
// Store as type-erased function in a small array indexed by variant alt.
entry_callbacks_[variant_index_of<S>()] =
[fn = std::forward<F>(f)](const StateVariant& v) {
fn(std::get<S>(v));
};
}
// Register a callback fired when leaving state S.
template <typename S, std::invocable<const S&> F>
void on_exit(F&& f)
{
exit_callbacks_[variant_index_of<S>()] =
[fn = std::forward<F>(f)](const StateVariant& v) {
fn(std::get<S>(v));
};
}
private:
template <typename S>
static constexpr std::size_t variant_index_of() noexcept
{
return []<std::size_t... Is>(std::index_sequence<Is...>) {
std::size_t idx = 0;
((std::is_same_v<S, States> ? (idx = Is, true) : false) || ...);
return idx;
}(std::index_sequence_for<States...>{});
}
template <typename S>
void on_exit(const S& s)
{
const auto idx = variant_index_of<S>();
if (exit_callbacks_[idx]) {
StateVariant tmp = s;
exit_callbacks_[idx](tmp);
}
}
template <typename S, typename Ev>
void on_enter(const S& s, const Ev&)
{
const auto idx = variant_index_of<S>();
if (entry_callbacks_[idx]) {
StateVariant tmp = s;
entry_callbacks_[idx](tmp);
}
}
StateVariant state_{std::in_place_index<0>};
std::function<void(const StateVariant&)>
entry_callbacks_[sizeof...(States)]{};
std::function<void(const StateVariant&)>
exit_callbacks_[sizeof...(States)]{};
};
} // namespace Void::StateMachine