Add Void::Fsm - runtime hierarchical FSM with lock-free MPSC core

Definition (Builder -> immutable shared MachineDef):
- Named hierarchical states, events by name or enum identifier (P2996),
  states_from_enum, initial/parallel composites, shallow/deep history,
  deferred events, per-state timeouts, guards, entry/exit/transition
  actions (coroutine Task<void> or sync, wrapped), internal transitions.
- build() validates (initial children, transition endpoints) and
  flattens into index-addressed vectors with depth info for LCA.

Machine (one consumer, many producers):
- post() is lock-free from any thread: Vyukov MPSC push + counting-
  semaphore park/wake; the single consumer (owned worker, or embedder
  via run_pending) owns all mutable machine state with zero locks.
- Observation via seqlock over a trivially-copyable StateSnapshot of
  active leaves; readers retry, writer is wait-free, no heap.
- Run-to-completion: innermost-first transition resolution per region,
  LCA-based exit/entry ordering, history snapshotted at exit time,
  deferred events re-injected FIFO after each state change, timers via
  deadline park (generation counters kill stale fires), orthogonal
  regions dispatched independently on the single consumer.
- co_await machine.send(ev) / send_wait() resolve with SendResult after
  the step; actions are driven to completion on the consumer's
  ManualExecutor before the step ends.
- swap_definition: atomic<shared_ptr> definition swap between steps;
  identical active-leaf names adopt seamlessly (no entry re-runs, queue
  intact), otherwise initial configuration; history remapped by name.
- serialize_state()/restore_state(): JSON by state *names* for
  hot-reload and persistence; restore re-activates silently.
- start() returns only once the initial configuration is entered.

40 new tests: semantics (ordering, guards, internal/self transitions),
hierarchy + both history kinds, defer FIFO, parallel regions, timers,
coroutine actions, awaitable/blocking send, serialize/restore round
trips, seamless + fallback hot swap, and stress: 8 producers x 10k with
per-producer FIFO assertion, 4-reader seqlock tear check, 50 definition
swaps under sustained load. Green under ASan+UBSan, stable across
repeated runs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-13 00:49:45 +03:00
1 parent c74a02a5a5
commit 697e07843c
13 files changed
+3105

No files matched your search

+323
View File
@@ -0,0 +1,323 @@
#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
@@ -0,0 +1,42 @@
#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
@@ -0,0 +1,273 @@
#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