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

+13
View File
@@ -48,6 +48,7 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules**
| `Stacktrace` | SHARED | Boost.Stacktrace capture, color helpers (kept separate to isolate the Boost dep) |
| `Plugin` | SHARED | dlopen loader, C ABI, hot reload |
| `StateMachine` | INTERFACE | compile-time variant-based FSM |
| `Fsm` | SHARED | runtime hierarchical FSM (see below) |
| `Testing` / `TestingMock` | STATIC / INTERFACE | test + mock frameworks |
`include/Void/Detail/` (e.g. `Enum.hpp` — P2996 enum reflection) is not a module; it is header-only and reachable from every module via the shared include root.
@@ -133,6 +134,18 @@ Other key points:
`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(cfg, prefix)` fills an aggregate via P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`).
### Fsm module (runtime FSM)
`Void::Fsm` — full-featured runtime state machine, distinct from the compile-time `StateMachine`:
- **Definition**: `Builder` declares states by name (`state("a", parent)` — hierarchical), events (`event("go")` or from enums via reflection), `initial`, `parallel` (orthogonal regions), `history(Shallow|Deep)`, `defer`, `timeout(state, ms, event)`, `transition(from, on, to).guard(...).action(...)`, `internal(in, on)`. `build()` validates into an immutable `shared_ptr<const MachineDef>`. Names are the stable identity; ids are per-definition.
- **Actions** are `std::function<Coro::Task<void>(Machine&, const Event&)>` (sync lambdas via `SyncAction` overloads). The run-to-completion step finishes only when the action's coroutine completes; the worker drives it on its own `ManualExecutor`.
- **Concurrency (MPSC)**: `post()` is lock-free from any thread (Vyukov queue + park semaphore); exactly one consumer — the owned worker (`start()` returns once the initial configuration is entered) or the embedder via `run_pending()` when constructed with `MachineOptions{.own_worker = false}` (the deterministic mode used by most tests; note `send_wait`/queued `serialize_state` would self-deadlock there — they're for the worker mode). Observation (`current()`, `is_in`) is a seqlock read of a trivially-copyable `StateSnapshot` (≤16 active leaves).
- **send paths**: `co_await machine.send(ev[, &executor])` resolves with `SendResult{Handled,Deferred,Unhandled,Dropped}` after the step; `send_wait` blocks; resumption defaults to the machine worker.
- **Hot swap**: `swap_definition(def)` applies between steps. If every active leaf name exists in the new def, the configuration is adopted without re-running entry actions (seamless); otherwise the machine re-enters the initial configuration. History is remapped by name.
- **Persistence**: `serialize_state()` → JSON with leaf/history *names*; `restore_state(json)` on a stopped machine re-activates silently (no entry actions).
- History records are snapshotted at exit time in `perform_transition` (not incrementally) — keep it that way; incremental recording accumulates stale leaves.
## Code style
Enforced by `.clang-format` (LLVM-based): 4-space indent (tabs), 80-column limit, Linux brace wrapping style, pointer alignment right.
+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
+5
View File
@@ -0,0 +1,5 @@
where possible for logger add colors, also add configurable patterns(like threadId, service\custom, time level, etc) and allow user to change their positions and apperance, and allow user define custom, also allow for file logger, have ability to
split by levels into differen files(have one file which gonna output all levels), add saving to history. I wanna that state machine\fsm is class which should be inherited, states should be define as class\struct inside class which inherited base class
of fsm\state machine, then user should write realisation how each state should behave and each state should return or another state, or fail, or success. You should make only one realisation FSM, it should async by default, have ability to nest other
state machines to enter to them and wait their result, fsm should be dynamic(this means not all states always gonna be, some of them can be optional on specific conditions). Also i wanna that your create service\manager which can be used as
archistrator of FSM. Also define base class for services with interfaces which allow to call them, without directly depending on them
+269
View File
@@ -0,0 +1,269 @@
#include <Void/Fsm/Definition.hpp>
#include <Void/Log/Log.hpp>
#include <format>
namespace Void::Fsm
{
// ── helpers ───────────────────────────────────────────────────────────
Action wrap_sync(SyncAction fn)
{
if (!fn) {
return {};
}
return [fn = std::move(fn)](Machine& m,
const Event& e) -> Coro::Task<void> {
fn(m, e);
co_return;
};
}
// ── MachineDef ────────────────────────────────────────────────────────
bool MachineDef::is_ancestor_or_self(StateId ancestor, StateId state) const
{
StateId cur = state;
while (cur != kInvalidState) {
if (cur == ancestor) {
return true;
}
cur = m_states[cur].parent;
}
return false;
}
StateId MachineDef::lca(StateId a, StateId b) const
{
// Equalize depths, then climb together.
StateId x = a;
StateId y = b;
while (m_states[x].depth > m_states[y].depth) {
x = m_states[x].parent;
}
while (m_states[y].depth > m_states[x].depth) {
y = m_states[y].parent;
}
while (x != y) {
x = m_states[x].parent;
y = m_states[y].parent;
}
return x;
}
// ── Builder ───────────────────────────────────────────────────────────
Builder::Builder()
{
// State 0 is the implicit root.
MachineDef::StateNode root;
root.name = "";
root.parent = kInvalidState;
root.depth = 0;
m_def.m_states.push_back(std::move(root));
m_def.m_state_ids.emplace("", kRootState);
}
StateRef Builder::state(std::string_view name, StateRef parent)
{
if (const auto it = m_def.m_state_ids.find(std::string{name});
it != m_def.m_state_ids.end()) {
return StateRef{it->second};
}
const auto id = static_cast<StateId>(m_def.m_states.size());
MachineDef::StateNode node;
node.name = std::string{name};
node.parent = parent.valid() ? parent.id() : kRootState;
node.depth = m_def.m_states[node.parent].depth + 1;
m_def.m_states.push_back(std::move(node));
m_def.m_states[parent.valid() ? parent.id() : kRootState]
.children.push_back(id);
m_def.m_state_ids.emplace(std::string{name}, id);
return StateRef{id};
}
EventId Builder::event(std::string_view name)
{
if (const auto it = m_def.m_event_ids.find(std::string{name});
it != m_def.m_event_ids.end()) {
return it->second;
}
const auto id = static_cast<EventId>(m_def.m_event_names.size());
m_def.m_event_names.emplace_back(name);
m_def.m_event_ids.emplace(std::string{name}, id);
return id;
}
Builder& Builder::initial(StateRef child)
{
const auto parent = m_def.m_states[child.id()].parent;
m_def.m_states[parent].initial = child.id();
return *this;
}
Builder& Builder::parallel(StateRef composite)
{
m_def.m_states[composite.id()].parallel = true;
return *this;
}
Builder& Builder::on_entry(StateRef state, Action action)
{
m_def.m_states[state.id()].entry = std::move(action);
return *this;
}
Builder& Builder::on_entry(StateRef state, SyncAction action)
{
return on_entry(state, wrap_sync(std::move(action)));
}
Builder& Builder::on_exit(StateRef state, Action action)
{
m_def.m_states[state.id()].exit = std::move(action);
return *this;
}
Builder& Builder::on_exit(StateRef state, SyncAction action)
{
return on_exit(state, wrap_sync(std::move(action)));
}
Builder& Builder::history(StateRef composite, History kind)
{
m_def.m_states[composite.id()].history = kind;
return *this;
}
Builder& Builder::defer(StateRef state, EventId id)
{
m_def.m_states[state.id()].deferred.push_back(id);
return *this;
}
Builder& Builder::timeout(StateRef state,
std::chrono::milliseconds after,
EventId fires)
{
m_def.m_states[state.id()].timeout = MachineDef::Timeout{after, fires};
return *this;
}
TransitionBuilder Builder::transition(StateRef from, EventId on,
StateRef to)
{
MachineDef::TransitionDef t;
t.from = from.id();
t.on = on;
t.to = to.id();
t.internal = false;
m_def.m_transitions.push_back(std::move(t));
return TransitionBuilder{*this, m_def.m_transitions.size() - 1};
}
TransitionBuilder Builder::internal(StateRef in, EventId on)
{
MachineDef::TransitionDef t;
t.from = in.id();
t.on = on;
t.to = kInvalidState;
t.internal = true;
m_def.m_transitions.push_back(std::move(t));
return TransitionBuilder{*this, m_def.m_transitions.size() - 1};
}
TransitionBuilder& TransitionBuilder::guard(Guard g)
{
m_builder->m_def.m_transitions[m_index].guard = std::move(g);
return *this;
}
TransitionBuilder& TransitionBuilder::action(Action a)
{
m_builder->m_def.m_transitions[m_index].action = std::move(a);
return *this;
}
TransitionBuilder& TransitionBuilder::action(SyncAction a)
{
return action(wrap_sync(std::move(a)));
}
std::expected<std::shared_ptr<const MachineDef>, DefError> Builder::build()
{
if (m_consumed) {
return std::unexpected{DefError{"Builder::build() called twice"}};
}
auto& def = m_def;
// Every composite (state with children) that is entered must know
// where to go: an initial child — parallel composites enter all
// children instead. Default a single-child composite's initial.
for (StateId id = 0; id < def.m_states.size(); ++id) {
auto& node = def.m_states[id];
if (node.children.empty()) {
if (node.parallel) {
return std::unexpected{DefError{
std::format("parallel state '{}' has no child regions",
node.name)}};
}
if (id == kRootState) {
return std::unexpected{DefError{"machine has no states"}};
}
continue;
}
if (node.parallel) {
continue;
}
if (node.initial == kInvalidState) {
if (node.children.size() == 1) {
node.initial = node.children.front();
} else if (id == kRootState) {
// Convention: the first declared top-level state.
node.initial = node.children.front();
} else {
return std::unexpected{DefError{std::format(
"composite state '{}' needs initial()", node.name)}};
}
}
if (!def.is_ancestor_or_self(id, node.initial) ||
node.initial == id) {
return std::unexpected{DefError{std::format(
"initial of '{}' is not a descendant", node.name)}};
}
}
// Transition sanity.
for (const auto& t : def.m_transitions) {
if (t.from == kInvalidState || t.from >= def.m_states.size()) {
return std::unexpected{
DefError{"transition from unknown state"}};
}
if (!t.internal &&
(t.to == kInvalidState || t.to >= def.m_states.size())) {
return std::unexpected{DefError{"transition to unknown state"}};
}
if (t.on == kInvalidEvent || t.on >= def.m_event_names.size()) {
return std::unexpected{DefError{"transition on unknown event"}};
}
}
// Index transitions by source state, in definition order.
def.m_transitions_by_state.assign(def.m_states.size(), {});
for (std::size_t i = 0; i < def.m_transitions.size(); ++i) {
def.m_transitions_by_state[def.m_transitions[i].from].push_back(i);
}
m_consumed = true;
auto out = std::make_shared<MachineDef>(std::move(m_def));
Void::Log::debug("Fsm",
"built definition: {} states, {} events, "
"{} transitions",
out->m_states.size(), out->m_event_names.size(),
out->m_transitions.size());
return out;
}
} // namespace Void::Fsm
+948
View File
@@ -0,0 +1,948 @@
#include <Void/Fsm/Machine.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <cassert>
namespace Void::Fsm
{
// ── Envelope ──────────────────────────────────────────────────────────
// One queued unit of work. Allocated by producers, freed by the
// consumer (or by the destructor for never-processed envelopes).
struct Machine::Envelope {
enum class Kind : std::uint8_t {
Event,
Swap,
Serialize,
StopMarker
};
Kind kind{Kind::Event};
Event event{};
// completion plumbing (all optional)
std::optional<SendResult>* result_slot{nullptr};
std::coroutine_handle<> continuation{};
Async::Executor* resume_on{nullptr};
std::binary_semaphore* done{nullptr};
// control payloads
std::shared_ptr<const MachineDef> new_def{};
Json::Value* out_json{nullptr};
void complete(SendResult result)
{
if (result_slot != nullptr) {
*result_slot = result;
}
if (done != nullptr) {
done->release();
}
if (continuation) {
auto h = continuation;
continuation = {};
if (resume_on != nullptr) {
resume_on->post(h);
} else {
h.resume();
}
}
}
};
// ── construction / lifecycle ──────────────────────────────────────────
Machine::Machine(std::shared_ptr<const MachineDef> def, Options options)
: m_def(std::move(def)), m_options(options)
{
}
Machine::~Machine()
{
stop();
// Free anything still queued (posted before stop or never run).
while (auto env = m_queue.try_pop()) {
(*env)->complete(SendResult::Dropped);
delete *env;
}
for (auto* env : m_deferred) {
delete env;
}
m_deferred.clear();
}
void Machine::start()
{
if (m_accepting.load(std::memory_order_acquire)) {
return;
}
m_stop.store(false, std::memory_order_release);
m_accepting.store(true, std::memory_order_release);
if (m_options.own_worker) {
// start() returns only once the initial configuration is
// entered (entry actions included) — observers immediately
// see a coherent snapshot.
std::binary_semaphore ready{0};
m_worker = std::thread([this, &ready] {
enter_initial_configuration();
ready.release();
consumer_loop();
});
ready.acquire();
} else {
enter_initial_configuration();
}
}
void Machine::stop()
{
if (!m_accepting.exchange(false, std::memory_order_acq_rel)) {
// Never started or already stopped; still join a worker that
// may be winding down.
if (m_worker.joinable()) {
m_worker.join();
}
return;
}
m_stop.store(true, std::memory_order_release);
wake_consumer();
if (m_worker.joinable()) {
m_worker.join();
} else {
// Embedder-driven: process the backlog on this (consumer)
// thread before declaring the machine stopped.
drain_once();
}
StateSnapshot snap = m_snapshot;
snap.running = false;
m_seq.fetch_add(1, std::memory_order_acq_rel);
m_snapshot = snap;
m_seq.fetch_add(1, std::memory_order_release);
}
bool Machine::running() const noexcept { return current().running; }
// ── submission ────────────────────────────────────────────────────────
bool Machine::post(Event event)
{
if (!m_accepting.load(std::memory_order_acquire)) {
return false;
}
auto* env = new Envelope{};
env->event = std::move(event);
m_queue.push(env);
wake_consumer();
return true;
}
void Machine::SendAwaitable::await_suspend(std::coroutine_handle<> h)
{
if (!m_machine->m_accepting.load(std::memory_order_acquire)) {
m_result = SendResult::Dropped;
h.resume();
return;
}
auto* env = new Envelope{};
env->event = std::move(m_event);
env->result_slot = &m_result;
env->continuation = h;
env->resume_on = m_resume_on;
m_machine->m_queue.push(env);
m_machine->wake_consumer();
}
SendResult Machine::send_wait(Event event)
{
if (!m_accepting.load(std::memory_order_acquire)) {
return SendResult::Dropped;
}
std::optional<SendResult> result;
std::binary_semaphore done{0};
auto* env = new Envelope{};
env->event = std::move(event);
env->result_slot = &result;
env->done = &done;
m_queue.push(env);
wake_consumer();
done.acquire();
return result.value_or(SendResult::Dropped);
}
// ── observation ───────────────────────────────────────────────────────
StateSnapshot Machine::current() const noexcept
{
// Seqlock read: retry while a write is in flight or raced us.
for (;;) {
const auto before = m_seq.load(std::memory_order_acquire);
if ((before & 1U) != 0U) {
continue;
}
StateSnapshot snap = m_snapshot;
std::atomic_thread_fence(std::memory_order_acquire);
if (m_seq.load(std::memory_order_relaxed) == before) {
return snap;
}
}
}
bool Machine::is_in(StateId state) const
{
const auto snap = current();
if (snap.contains(state)) {
return true;
}
const auto def = definition();
for (std::uint32_t i = 0; i < snap.leaf_count; ++i) {
if (def->is_ancestor_or_self(state, snap.leaves[i])) {
return true;
}
}
return false;
}
bool Machine::is_in(std::string_view state) const
{
const auto def = definition();
const auto id = def->state_id(state);
return id.has_value() && is_in(*id);
}
// ── hot swap / persistence ────────────────────────────────────────────
void Machine::swap_definition(std::shared_ptr<const MachineDef> def)
{
if (!m_accepting.load(std::memory_order_acquire)) {
// Not running: take effect immediately for the next start().
m_def.store(std::move(def), std::memory_order_release);
return;
}
auto* env = new Envelope{};
env->kind = Envelope::Kind::Swap;
env->new_def = std::move(def);
m_queue.push(env);
wake_consumer();
}
Json::Value Machine::serialize_state()
{
if (!m_accepting.load(std::memory_order_acquire) ||
!m_options.own_worker) {
// Quiescent machine, or embedder-driven: the caller is (or
// stands in for) the consumer — read directly. Queueing here
// would deadlock with nobody to drain.
Json::Value out;
Envelope env;
env.kind = Envelope::Kind::Serialize;
env.out_json = &out;
(void)handle_envelope(env);
return out;
}
Json::Value out;
std::binary_semaphore done{0};
auto* env = new Envelope{};
env->kind = Envelope::Kind::Serialize;
env->out_json = &out;
env->done = &done;
m_queue.push(env);
wake_consumer();
done.acquire();
return out;
}
std::expected<void, FsmError>
Machine::restore_state(const Json::Value& state)
{
if (m_accepting.load(std::memory_order_acquire)) {
return std::unexpected{
FsmError{"restore_state requires a stopped machine"}};
}
if (!state.is_object() || state.find("leaves") == nullptr) {
return std::unexpected{FsmError{"malformed machine state json"}};
}
m_pending_restore = state;
return {};
}
// ── consumer internals ────────────────────────────────────────────────
void Machine::wake_consumer() noexcept
{
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
m_wakeup.release();
}
}
void Machine::consumer_loop()
{
for (;;) {
drain_once();
if (m_stop.load(std::memory_order_acquire) && m_queue.empty()) {
return;
}
m_sleeping.store(true, std::memory_order_release);
if (!m_queue.empty() || m_stop.load(std::memory_order_acquire)) {
m_sleeping.store(false, std::memory_order_release);
continue;
}
if (const auto deadline = next_deadline(); deadline.has_value()) {
(void)m_wakeup.try_acquire_until(*deadline);
} else {
m_wakeup.acquire();
}
m_sleeping.store(false, std::memory_order_release);
}
}
std::size_t Machine::run_pending() { return drain_once(); }
void Machine::run_until(const std::function<bool()>& until)
{
while (!until()) {
if (drain_once() == 0) {
fire_due_timers();
std::this_thread::yield();
}
}
}
std::size_t Machine::drain_once()
{
std::size_t handled = 0;
fire_due_timers();
if (m_deferred_dirty) {
reinject_deferred();
}
while (auto env = m_queue.try_pop()) {
if (handle_envelope(**env)) {
delete *env;
}
++handled;
fire_due_timers();
if (m_deferred_dirty) {
reinject_deferred();
}
}
return handled;
}
// Returns true if the envelope should be freed by the caller (false:
// ownership moved to the deferred stash).
bool Machine::handle_envelope(Envelope& env)
{
switch (env.kind) {
case Envelope::Kind::Swap:
apply_swap(std::move(env.new_def));
return true;
case Envelope::Kind::Serialize:
{
auto obj = Json::object();
auto& o = obj.as_object();
o.emplace_back("__fsm", Json::Value{1});
auto leaves = Json::array();
for (const auto& name : active_leaf_names()) {
leaves.as_array().emplace_back(name);
}
o.emplace_back("leaves", std::move(leaves));
auto hist = Json::object();
if (m_active_def) {
for (const auto& [state, record] : m_history) {
auto arr = Json::array();
for (const auto leaf : record.leaves) {
arr.as_array().emplace_back(
m_active_def->state(leaf).name);
}
hist.as_object().emplace_back(
m_active_def->state(state).name,
std::move(arr));
}
}
o.emplace_back("history", std::move(hist));
o.emplace_back("step",
Json::Value{static_cast<double>(m_step)});
if (env.out_json != nullptr) {
*env.out_json = std::move(obj);
}
env.complete(SendResult::Handled);
return true;
}
case Envelope::Kind::StopMarker:
return true;
case Envelope::Kind::Event:
break;
}
const auto result = dispatch_event(env.event);
env.complete(result);
if (result == SendResult::Deferred) {
m_deferred.push_back(&env);
return false;
}
return true;
}
SendResult Machine::dispatch_event(const Event& event)
{
const auto& def = *m_active_def;
bool handled = false;
bool deferrable = false;
// Copy: transitions mutate m_leaves while we iterate regions.
const auto leaves = m_leaves;
for (const StateId leaf : leaves) {
if (leaf >= m_active.size() || !m_active[leaf]) {
continue; // region was exited by an earlier transition
}
const MachineDef::TransitionDef* chosen = nullptr;
StateId source = leaf;
for (StateId cur = leaf; cur != kInvalidState && chosen == nullptr;
cur = def.state(cur).parent) {
for (const auto index : def.transitions_from(cur)) {
const auto& t = def.transition(index);
if (t.on != event.id) {
continue;
}
if (t.guard && !t.guard(*this, event)) {
continue;
}
chosen = &t;
source = cur;
break;
}
if (chosen == nullptr) {
const auto& node = def.state(cur);
if (std::find(node.deferred.begin(),
node.deferred.end(),
event.id) != node.deferred.end()) {
deferrable = true;
}
}
}
if (chosen != nullptr) {
perform_transition(*chosen, leaf, event);
handled = true;
}
}
if (handled) {
++m_step;
m_deferred_dirty = true;
publish_snapshot();
return SendResult::Handled;
}
if (deferrable) {
return SendResult::Deferred;
}
return SendResult::Unhandled;
}
void Machine::perform_transition(const MachineDef::TransitionDef& t,
StateId /*source_leaf*/,
const Event& event)
{
const auto& def = *m_active_def;
if (t.internal) {
run_action(t.action, event);
return;
}
StateId boundary = def.lca(t.from, t.to);
if (boundary == t.from || boundary == t.to) {
// Self-transitions and ancestor/descendant targets exit (at
// least) the `from`/`to` state itself.
boundary = def.state(boundary).parent;
if (boundary == kInvalidState) {
boundary = kRootState;
}
}
// The child of `boundary` containing the transition source: the
// whole active subtree under it exits.
StateId branch = t.from;
while (def.state(branch).parent != boundary) {
branch = def.state(branch).parent;
}
// Snapshot history for every composite about to be exited — the
// record must reflect the configuration at the moment of exit,
// not accumulate across earlier transitions.
for (StateId s = 0; s < m_active.size(); ++s) {
if (!m_active[s] || !def.is_ancestor_or_self(branch, s)) {
continue;
}
const auto& node = def.state(s);
if (node.history == History::None) {
continue;
}
HistoryRecord record;
if (node.history == History::Shallow) {
for (const auto child : node.children) {
if (m_active[child]) {
record.leaves.push_back(child);
break;
}
}
} else { // Deep
for (const auto leaf : m_leaves) {
if (m_active[leaf] && def.is_ancestor_or_self(s, leaf)) {
record.leaves.push_back(leaf);
}
}
}
if (!record.leaves.empty()) {
m_history[s] = std::move(record);
}
}
// Exit phase — innermost first, per active leaf chain.
const auto leaves = m_leaves;
for (const StateId leaf : leaves) {
if (leaf >= m_active.size() || !m_active[leaf]) {
continue;
}
if (!def.is_ancestor_or_self(branch, leaf)) {
continue;
}
exit_to_lca(leaf, boundary, event);
}
run_action(t.action, event);
enter_target(boundary, t.to, event);
}
void Machine::exit_to_lca(StateId leaf, StateId lca, const Event& event)
{
for (StateId cur = leaf; cur != lca && cur != kInvalidState;
cur = m_active_def->state(cur).parent) {
if (m_active[cur]) {
exit_single(cur, event);
}
}
}
void Machine::exit_single(StateId state, const Event& event)
{
const auto& node = m_active_def->state(state);
run_action(node.exit, event);
m_active[state] = false;
++m_activation[state]; // invalidates armed timers
std::erase(m_leaves, state);
}
void Machine::enter_target(StateId lca, StateId target, const Event& event)
{
const auto& def = *m_active_def;
// Path lca(exclusive) → target, outermost first.
std::vector<StateId> path;
for (StateId cur = target; cur != lca && cur != kInvalidState;
cur = def.state(cur).parent) {
path.push_back(cur);
}
for (auto it = path.rbegin(); it != path.rend(); ++it) {
if (!m_active[*it]) {
enter_single(*it, event);
}
}
descend_into(target, event);
}
void Machine::descend_into(StateId state, const Event& event)
{
const auto& def = *m_active_def;
const auto& node = def.state(state);
if (node.children.empty()) {
if (std::find(m_leaves.begin(), m_leaves.end(), state) ==
m_leaves.end()) {
m_leaves.push_back(state);
}
return;
}
if (node.parallel) {
for (const auto child : node.children) {
enter_single(child, event);
descend_into(child, event);
}
return;
}
if (node.history != History::None) {
if (const auto it = m_history.find(state);
it != m_history.end() && !it->second.leaves.empty()) {
// Keep the record — UML history persists; the next exit
// of this composite overwrites it anyway.
const auto record = it->second;
if (node.history == History::Shallow) {
const auto child = record.leaves.front();
enter_single(child, event);
descend_into(child, event);
} else { // Deep: re-activate each recorded leaf chain
for (const auto leaf : record.leaves) {
std::vector<StateId> path;
for (StateId cur = leaf;
cur != state && cur != kInvalidState;
cur = def.state(cur).parent) {
path.push_back(cur);
}
for (auto it2 = path.rbegin(); it2 != path.rend();
++it2) {
if (!m_active[*it2]) {
enter_single(*it2, event);
}
}
if (std::find(m_leaves.begin(), m_leaves.end(), leaf) ==
m_leaves.end()) {
m_leaves.push_back(leaf);
}
}
}
return;
}
}
const auto child = node.initial;
enter_single(child, event);
descend_into(child, event);
}
void Machine::enter_single(StateId state, const Event& event)
{
const auto& node = m_active_def->state(state);
m_active[state] = true;
++m_activation[state];
if (node.timeout.has_value()) {
m_timers.push_back(TimerArm{
state, std::chrono::steady_clock::now() + node.timeout->after,
node.timeout->fires, m_activation[state]});
}
run_action(node.entry, event);
}
void Machine::run_action(const Action& action, const Event& event)
{
if (!action) {
return;
}
// Drive the coroutine to completion on this consumer thread; the
// run-to-completion step does not finish until the action does.
// External resumptions arrive through m_executor.post (thread-
// safe), so awaiting cross-thread work cannot deadlock — it just
// stalls this machine (inherent to RTC semantics).
bool finished = false;
Async::spawn(m_executor,
[](const Action& a, Machine& m, const Event& e,
bool& done) -> Coro::Task<void> {
co_await a(m, e);
done = true;
}(action, *this, event, finished));
while (!finished) {
if (!m_executor.run_one()) {
std::this_thread::yield();
}
}
}
void Machine::enter_initial_configuration()
{
m_active_def = m_def.load(std::memory_order_acquire);
m_active.assign(m_active_def->state_count(), false);
m_activation.assign(m_active_def->state_count(), 0);
m_leaves.clear();
m_timers.clear();
m_history.clear();
m_active[kRootState] = true;
if (m_pending_restore.has_value()) {
const auto& def = *m_active_def;
const auto& state = *m_pending_restore;
// History first (so future re-entries see it).
if (const auto* hist = state.find("history");
hist != nullptr && hist->is_object()) {
for (const auto& [name, arr] : hist->as_object()) {
const auto id = def.state_id(name);
if (!id.has_value() || !arr.is_array()) {
continue;
}
HistoryRecord record;
for (const auto& leaf_name : arr.as_array()) {
if (const auto leaf =
def.state_id(leaf_name.as_string());
leaf.has_value()) {
record.leaves.push_back(*leaf);
}
}
if (!record.leaves.empty()) {
m_history.emplace(*id, std::move(record));
}
}
}
// Activate recorded leaf chains silently (no entry actions —
// the configuration is being *restored*, not entered).
bool any = false;
if (const auto* leaves = state.find("leaves");
leaves != nullptr && leaves->is_array()) {
for (const auto& leaf_name : leaves->as_array()) {
const auto id = def.state_id(leaf_name.as_string());
if (!id.has_value()) {
Void::Log::warn("Fsm",
"restore: unknown state '{}' skipped",
leaf_name.as_string());
continue;
}
for (StateId cur = *id; cur != kInvalidState;
cur = def.state(cur).parent) {
m_active[cur] = true;
}
m_leaves.push_back(*id);
any = true;
}
}
m_pending_restore.reset();
if (any) {
// Arm timers for restored states.
for (const auto leaf : m_leaves) {
for (StateId cur = leaf; cur != kInvalidState;
cur = def.state(cur).parent) {
const auto& node = def.state(cur);
if (node.timeout.has_value()) {
++m_activation[cur];
m_timers.push_back(TimerArm{
cur,
std::chrono::steady_clock::now() +
node.timeout->after,
node.timeout->fires, m_activation[cur]});
}
}
}
publish_snapshot();
return;
}
Void::Log::warn("Fsm", "restore matched no states; entering "
"initial configuration");
}
descend_into(kRootState, Event{});
++m_step;
publish_snapshot();
}
void Machine::publish_snapshot()
{
StateSnapshot snap;
snap.leaf_count = 0;
for (const auto leaf : m_leaves) {
if (snap.leaf_count < StateSnapshot::kMaxLeaves) {
snap.leaves[snap.leaf_count++] = leaf;
}
}
snap.step = m_step;
snap.running = m_accepting.load(std::memory_order_acquire);
m_seq.fetch_add(1, std::memory_order_acq_rel); // odd: write begins
m_snapshot = snap;
m_seq.fetch_add(1, std::memory_order_release); // even: write ends
}
void Machine::rearm_timers()
{
// Prune stale arms (state exited or re-activated since).
std::erase_if(m_timers, [this](const TimerArm& arm) {
return arm.state >= m_active.size() || !m_active[arm.state] ||
m_activation[arm.state] != arm.generation;
});
}
void Machine::fire_due_timers()
{
if (m_timers.empty() || !m_active_def) {
return;
}
const auto now = std::chrono::steady_clock::now();
// Collect due, valid arms first — dispatch mutates m_timers.
std::vector<EventId> due;
std::erase_if(m_timers, [&](const TimerArm& arm) {
const bool stale = arm.state >= m_active.size() ||
!m_active[arm.state] ||
m_activation[arm.state] != arm.generation;
if (stale) {
return true;
}
if (arm.deadline <= now) {
due.push_back(arm.fires);
return true;
}
return false;
});
for (const auto id : due) {
(void)dispatch_event(Event{id, {}});
}
}
std::optional<std::chrono::steady_clock::time_point>
Machine::next_deadline() const
{
std::optional<std::chrono::steady_clock::time_point> next;
for (const auto& arm : m_timers) {
if (arm.state < m_active.size() && m_active[arm.state] &&
m_activation[arm.state] == arm.generation) {
if (!next.has_value() || arm.deadline < *next) {
next = arm.deadline;
}
}
}
return next;
}
void Machine::reinject_deferred()
{
m_deferred_dirty = false;
if (m_deferred.empty()) {
return;
}
// Completion already ran when the event was first deferred; these
// envelopes only carry the event now. Process in FIFO order ahead
// of the queue; still-deferred ones go back to the stash.
auto pending = std::move(m_deferred);
m_deferred.clear();
for (auto* env : pending) {
const auto result = dispatch_event(env->event);
if (result == SendResult::Deferred) {
m_deferred.push_back(env);
} else {
delete env;
}
}
}
std::vector<std::string> Machine::active_leaf_names() const
{
std::vector<std::string> names;
if (!m_active_def) {
return names;
}
names.reserve(m_leaves.size());
for (const auto leaf : m_leaves) {
names.push_back(m_active_def->state(leaf).name);
}
return names;
}
void Machine::apply_swap(std::shared_ptr<const MachineDef> next)
{
if (!next) {
return;
}
const auto old_def = m_active_def;
const auto old_leaves = active_leaf_names();
// Remap history records by name before switching defs.
std::vector<std::pair<std::string, std::vector<std::string>>>
old_history;
if (old_def) {
for (const auto& [state, record] : m_history) {
std::vector<std::string> leaves;
for (const auto leaf : record.leaves) {
leaves.push_back(old_def->state(leaf).name);
}
old_history.emplace_back(old_def->state(state).name,
std::move(leaves));
}
}
m_def.store(next, std::memory_order_release);
m_active_def = std::move(next);
m_active.assign(m_active_def->state_count(), false);
m_activation.assign(m_active_def->state_count(), 0);
m_leaves.clear();
m_timers.clear();
m_history.clear();
m_active[kRootState] = true;
for (const auto& [name, leaves] : old_history) {
const auto id = m_active_def->state_id(name);
if (!id.has_value()) {
continue;
}
HistoryRecord record;
for (const auto& leaf_name : leaves) {
if (const auto leaf = m_active_def->state_id(leaf_name);
leaf.has_value()) {
record.leaves.push_back(*leaf);
}
}
if (!record.leaves.empty()) {
m_history.emplace(*id, std::move(record));
}
}
bool all_mapped = !old_leaves.empty();
for (const auto& name : old_leaves) {
const auto id = m_active_def->state_id(name);
if (!id.has_value()) {
all_mapped = false;
break;
}
}
if (all_mapped) {
// Seamless adoption: same state names — activate the mapped
// chains without re-running entry actions.
const auto& def = *m_active_def;
for (const auto& name : old_leaves) {
const auto id = *def.state_id(name);
for (StateId cur = id; cur != kInvalidState;
cur = def.state(cur).parent) {
m_active[cur] = true;
}
// The state may have grown children in the new def.
if (def.state(id).children.empty()) {
m_leaves.push_back(id);
} else {
descend_into(id, Event{});
}
// Re-arm timers along the chain.
for (StateId cur = id; cur != kInvalidState;
cur = def.state(cur).parent) {
const auto& node = def.state(cur);
if (node.timeout.has_value() && m_active[cur] &&
m_activation[cur] == 0) {
++m_activation[cur];
m_timers.push_back(
TimerArm{cur,
std::chrono::steady_clock::now() +
node.timeout->after,
node.timeout->fires, m_activation[cur]});
}
}
}
Void::Log::info("Fsm",
"definition swapped seamlessly "
"({} active leaves kept)",
m_leaves.size());
} else {
Void::Log::warn("Fsm", "definition swap changed the active "
"state set; entering initial "
"configuration");
descend_into(kRootState, Event{});
}
++m_step;
m_deferred_dirty = true; // new def may consume stashed events
publish_snapshot();
}
} // namespace Void::Fsm
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Fsm
INTERNAL_DEPS Functional Data
)
+247
View File
@@ -0,0 +1,247 @@
#include <Void/Fsm/Definition.hpp>
#include <Void/Fsm/Machine.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <vector>
using namespace Void::Fsm;
namespace
{
// Embedder-driven machine (no worker thread): post + run_pending make
// the tests fully deterministic.
struct Bench {
std::shared_ptr<const MachineDef> def;
std::unique_ptr<Machine> machine;
std::vector<std::string> log;
explicit Bench(Builder& b)
{
auto built = b.build();
Void::Testing::expect(built.has_value());
def = *built;
machine = std::make_unique<Machine>(
def, MachineOptions{.own_worker = false});
}
SendResult step(EventId ev)
{
machine->post(Event{ev, {}});
machine->run_pending();
return SendResult::Handled; // result checked via send paths
}
};
} // namespace
Void::Testing::Test basic_initial_state_entered_on_start()
{
Builder b;
auto idle = b.state("idle");
auto run = b.state("running");
b.initial(idle);
(void)run;
Bench bench{b};
bench.machine->start();
Void::Testing::expect(bench.machine->is_in("idle"));
Void::Testing::expect(!bench.machine->is_in("running"));
Void::Testing::expect(bench.machine->running());
}
Void::Testing::Test basic_transition_changes_state()
{
Builder b;
auto idle = b.state("idle");
auto run = b.state("running");
b.initial(idle);
const auto go = b.event("go");
b.transition(idle, go, run);
Bench bench{b};
bench.machine->start();
bench.machine->post(Event{go, {}});
bench.machine->run_pending();
Void::Testing::expect(bench.machine->is_in("running"));
Void::Testing::expect(!bench.machine->is_in("idle"));
}
Void::Testing::Test basic_entry_exit_and_action_ordering()
{
std::vector<std::string> log;
Builder b;
auto a = b.state("a");
auto c = b.state("c");
b.initial(a);
const auto go = b.event("go");
b.on_entry(a, SyncAction{[&](Machine&, const Event&) {
log.push_back("enter a");
}});
b.on_exit(a, SyncAction{[&](Machine&, const Event&) {
log.push_back("exit a");
}});
b.on_entry(c, SyncAction{[&](Machine&, const Event&) {
log.push_back("enter c");
}});
b.transition(a, go, c).action(SyncAction{
[&](Machine&, const Event&) { log.push_back("action"); }});
Bench bench{b};
bench.machine->start();
bench.machine->post(Event{go, {}});
bench.machine->run_pending();
const std::vector<std::string> expected{"enter a", "exit a", "action",
"enter c"};
Void::Testing::expect(log == expected);
}
Void::Testing::Test basic_guard_blocks_and_allows()
{
Builder b;
auto a = b.state("a");
auto c = b.state("c");
b.initial(a);
const auto go = b.event("go");
bool open = false;
b.transition(a, go, c).guard(
[&](const Machine&, const Event&) { return open; });
Bench bench{b};
bench.machine->start();
bench.machine->post(Event{go, {}});
bench.machine->run_pending();
Void::Testing::expect(bench.machine->is_in("a"));
open = true;
bench.machine->post(Event{go, {}});
bench.machine->run_pending();
Void::Testing::expect(bench.machine->is_in("c"));
}
Void::Testing::Test basic_internal_transition_no_exit_entry()
{
std::vector<std::string> log;
Builder b;
auto a = b.state("a");
b.initial(a);
const auto tick = b.event("tick");
b.on_entry(a, SyncAction{[&](Machine&, const Event&) {
log.push_back("enter");
}});
b.on_exit(a, SyncAction{[&](Machine&, const Event&) {
log.push_back("exit");
}});
b.internal(a, tick).action(SyncAction{
[&](Machine&, const Event&) { log.push_back("internal"); }});
Bench bench{b};
bench.machine->start();
bench.machine->post(Event{tick, {}});
bench.machine->run_pending();
const std::vector<std::string> expected{"enter", "internal"};
Void::Testing::expect(log == expected);
Void::Testing::expect(bench.machine->is_in("a"));
}
Void::Testing::Test basic_self_transition_exits_and_reenters()
{
std::vector<std::string> log;
Builder b;
auto a = b.state("a");
b.initial(a);
const auto reset = b.event("reset");
b.on_entry(a, SyncAction{[&](Machine&, const Event&) {
log.push_back("enter");
}});
b.on_exit(a, SyncAction{[&](Machine&, const Event&) {
log.push_back("exit");
}});
b.transition(a, reset, a);
Bench bench{b};
bench.machine->start();
bench.machine->post(Event{reset, {}});
bench.machine->run_pending();
const std::vector<std::string> expected{"enter", "exit", "enter"};
Void::Testing::expect(log == expected);
}
Void::Testing::Test basic_payload_reaches_action()
{
int received = 0;
Builder b;
auto a = b.state("a");
auto c = b.state("c");
b.initial(a);
const auto go = b.event("go");
b.transition(a, go, c).action(
SyncAction{[&](Machine&, const Event& e) {
received = std::any_cast<int>(e.payload);
}});
Bench bench{b};
bench.machine->start();
bench.machine->post(Event{go, 42});
bench.machine->run_pending();
Void::Testing::expect_eq(received, 42);
}
Void::Testing::Test basic_unhandled_event_keeps_state()
{
Builder b;
auto a = b.state("a");
b.initial(a);
const auto noop = b.event("noop");
(void)noop;
Bench bench{b};
bench.machine->start();
bench.machine->post(Event{noop, {}});
bench.machine->run_pending();
Void::Testing::expect(bench.machine->is_in("a"));
}
Void::Testing::Test basic_post_rejected_before_start_and_after_stop()
{
Builder b;
auto a = b.state("a");
b.initial(a);
const auto go = b.event("go");
Bench bench{b};
Void::Testing::expect(!bench.machine->post(Event{go, {}}));
bench.machine->start();
Void::Testing::expect(bench.machine->post(Event{go, {}}));
bench.machine->run_pending();
bench.machine->stop();
Void::Testing::expect(!bench.machine->post(Event{go, {}}));
Void::Testing::expect(!bench.machine->running());
}
Void::Testing::Test builder_rejects_composite_without_initial()
{
Builder b;
auto parent = b.state("parent");
(void)b.state("c1", parent);
(void)b.state("c2", parent);
b.initial(parent); // parent initial of root, but no initial child
auto built = b.build();
Void::Testing::expect(!built.has_value());
}
Void::Testing::Test builder_defaults_first_top_level_as_initial()
{
Builder b;
(void)b.state("first");
(void)b.state("second");
Bench bench{b};
bench.machine->start();
Void::Testing::expect(bench.machine->is_in("first"));
}
+221
View File
@@ -0,0 +1,221 @@
#include <Void/Fsm/Definition.hpp>
#include <Void/Fsm/Machine.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <thread>
#include <vector>
using namespace Void::Fsm;
#ifdef VOID_HAS_ENUM_REFLECTION
namespace
{
enum class Phase { Ping, Pong };
enum class Signal { Flip };
} // namespace
Void::Testing::Test enum_reflection_builds_states_and_events()
{
Builder b;
b.states_from_enum<Phase>();
b.initial(b.state_of(Phase::Ping));
const auto flip = b.event(Signal::Flip);
b.transition(b.state_of(Phase::Ping), flip, b.state_of(Phase::Pong));
b.transition(b.state_of(Phase::Pong), flip, b.state_of(Phase::Ping));
auto def = b.build();
Void::Testing::expect(def.has_value());
Void::Testing::expect((*def)->state_id("Ping").has_value());
Void::Testing::expect((*def)->event_id("Flip").has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
Void::Testing::expect(m.is_in("Ping"));
Void::Testing::expect(m.post(Signal::Flip));
m.run_pending();
Void::Testing::expect(m.is_in("Pong"));
// Serialized state uses enumerator names — stable across reloads.
const auto json = m.serialize_state();
Void::Testing::expect_eq(json["leaves"][0].as_string(),
std::string{"Pong"});
}
#endif // VOID_HAS_ENUM_REFLECTION
// @tag stress, concurrency
Void::Testing::Test concurrent_posts_all_processed_in_producer_order()
{
constexpr int producers = 8;
constexpr int per_producer = 10'000;
// counter state with an internal self-loop that consumes "bump"
// events carrying {producer, seq} payloads.
struct Payload {
int producer;
int seq;
};
std::vector<int> next_seq(producers, 0);
std::atomic<long long> handled{0};
bool order_ok = true;
Builder b;
auto counting = b.state("counting");
b.initial(counting);
const auto bump = b.event("bump");
b.internal(counting, bump)
.action(SyncAction{[&](Machine&, const Event& e) {
const auto p = std::any_cast<Payload>(e.payload);
// Per-producer FIFO must hold (single consumer).
if (next_seq[static_cast<std::size_t>(p.producer)] != p.seq) {
order_ok = false;
}
++next_seq[static_cast<std::size_t>(p.producer)];
++handled;
}});
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def}; // own worker
m.start();
std::atomic<bool> go{false};
std::vector<std::thread> threads;
threads.reserve(producers);
for (int p = 0; p < producers; ++p) {
threads.emplace_back([&m, &go, bump, p] {
go.wait(false);
for (int i = 0; i < per_producer; ++i) {
while (!m.post(Event{bump, Payload{p, i}})) {
std::this_thread::yield();
}
}
});
}
go = true;
go.notify_all();
for (auto& t : threads) {
t.join();
}
// Everything posted before this send_wait is processed before it.
(void)m.send_wait(Event{bump, Payload{0, per_producer}});
++next_seq[0]; // account for the flush event
m.stop();
Void::Testing::expect_eq(
handled.load(),
static_cast<long long>(producers) * per_producer + 1);
Void::Testing::expect(order_ok);
}
// @tag stress, concurrency
Void::Testing::Test snapshot_reads_never_tear_under_load()
{
Builder b;
auto ping = b.state("ping");
auto pong = b.state("pong");
b.initial(ping);
const auto flip = b.event("flip");
b.transition(ping, flip, pong);
b.transition(pong, flip, ping);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def};
m.start();
std::atomic<bool> stop{false};
std::atomic<long long> reads{0};
bool sane = true;
std::vector<std::thread> readers;
readers.reserve(4);
for (int r = 0; r < 4; ++r) {
readers.emplace_back([&] {
while (!stop.load(std::memory_order_relaxed)) {
const auto snap = m.current();
// Exactly one leaf, and it is one of the two states.
if (snap.leaf_count != 1) {
sane = false;
}
++reads;
}
});
}
for (int i = 0; i < 20'000; ++i) {
m.post(Event{flip, {}});
}
(void)m.send_wait(Event{flip, {}});
stop = true;
for (auto& t : readers) {
t.join();
}
m.stop();
Void::Testing::expect(sane);
Void::Testing::expect(reads.load() > 0);
}
// @tag stress, concurrency
Void::Testing::Test hot_swap_under_sustained_load()
{
auto make = [](bool variant) {
Builder b;
auto ping = b.state("ping");
auto pong = b.state("pong");
b.initial(ping);
const auto flip = b.event("flip");
b.transition(ping, flip, pong);
b.transition(pong, flip, ping);
if (variant) {
// identical topology, extra no-op event
(void)b.event("extra");
}
auto def = b.build();
Void::Testing::expect(def.has_value());
return *def;
};
Machine m{make(false)};
m.start();
std::atomic<bool> stop{false};
std::vector<std::thread> producers;
producers.reserve(4);
const auto flip = *m.definition()->event_id("flip");
for (int p = 0; p < 4; ++p) {
producers.emplace_back([&m, &stop, flip] {
while (!stop.load(std::memory_order_relaxed)) {
(void)m.post(Event{flip, {}});
// Pace producers so the backlog stays bounded — the test
// exercises swap-under-load, not queue growth.
std::this_thread::yield();
}
});
}
for (int i = 0; i < 50; ++i) {
m.swap_definition(make(i % 2 == 1));
std::this_thread::sleep_for(std::chrono::microseconds{200});
}
stop = true;
for (auto& t : producers) {
t.join();
}
(void)m.send_wait(Event{flip, {}});
// Machine is still coherent: exactly one of the two states active.
const bool in_ping = m.is_in("ping");
const bool in_pong = m.is_in("pong");
Void::Testing::expect(in_ping != in_pong);
m.stop();
}
+336
View File
@@ -0,0 +1,336 @@
#include <Void/Fsm/Definition.hpp>
#include <Void/Fsm/Machine.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <string>
#include <thread>
#include <vector>
using namespace Void::Fsm;
// ── deferred events ───────────────────────────────────────────────────────────
Void::Testing::Test defer_stashes_until_state_change()
{
int handled = 0;
Builder b;
auto busy = b.state("busy");
auto idle = b.state("idle");
b.initial(busy);
const auto job = b.event("job");
const auto done = b.event("done");
b.defer(busy, job);
b.transition(busy, done, idle);
b.internal(idle, job).action(
SyncAction{[&](Machine&, const Event&) { ++handled; }});
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{job, {}}); // deferred in busy
m.post(Event{job, {}}); // deferred in busy
m.run_pending();
Void::Testing::expect_eq(handled, 0);
m.post(Event{done, {}}); // busy -> idle, deferred jobs re-inject
m.run_pending();
Void::Testing::expect_eq(handled, 2);
}
Void::Testing::Test defer_keeps_fifo_order()
{
std::vector<int> seen;
Builder b;
auto busy = b.state("busy");
auto idle = b.state("idle");
b.initial(busy);
const auto job = b.event("job");
const auto done = b.event("done");
b.defer(busy, job);
b.transition(busy, done, idle);
b.internal(idle, job).action(
SyncAction{[&](Machine&, const Event& e) {
seen.push_back(std::any_cast<int>(e.payload));
}});
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{job, 1});
m.post(Event{job, 2});
m.post(Event{job, 3});
m.post(Event{done, {}});
m.run_pending();
const std::vector<int> expected{1, 2, 3};
Void::Testing::expect(seen == expected);
}
// ── orthogonal regions ────────────────────────────────────────────────────────
Void::Testing::Test parallel_enters_all_regions()
{
Builder b;
auto sys = b.state("sys");
auto net = b.state("net", sys);
auto net_d = b.state("net_down", net);
auto net_u = b.state("net_up", net);
auto disk = b.state("disk", sys);
auto d_ok = b.state("disk_ok", disk);
auto d_bad = b.state("disk_bad", disk);
b.initial(sys);
b.parallel(sys);
b.initial(net_d);
b.initial(d_ok);
(void)net_u;
(void)d_bad;
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
Void::Testing::expect(m.is_in("net_down"));
Void::Testing::expect(m.is_in("disk_ok"));
Void::Testing::expect_eq(m.current().leaf_count, std::uint32_t{2});
}
Void::Testing::Test parallel_regions_react_independently()
{
Builder b;
auto sys = b.state("sys");
auto net = b.state("net", sys);
auto net_d = b.state("net_down", net);
auto net_u = b.state("net_up", net);
auto disk = b.state("disk", sys);
auto d_ok = b.state("disk_ok", disk);
auto d_bad = b.state("disk_bad", disk);
b.initial(sys);
b.parallel(sys);
b.initial(net_d);
b.initial(d_ok);
const auto net_event = b.event("net_restored");
const auto disk_event = b.event("disk_failed");
b.transition(net_d, net_event, net_u);
b.transition(d_ok, disk_event, d_bad);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{net_event, {}});
m.run_pending();
Void::Testing::expect(m.is_in("net_up"));
Void::Testing::expect(m.is_in("disk_ok")); // untouched
m.post(Event{disk_event, {}});
m.run_pending();
Void::Testing::expect(m.is_in("net_up"));
Void::Testing::expect(m.is_in("disk_bad"));
}
Void::Testing::Test parallel_one_event_can_fire_in_both_regions()
{
Builder b;
auto sys = b.state("sys");
auto r1 = b.state("r1", sys);
auto a1 = b.state("a1", r1);
auto b1 = b.state("b1", r1);
auto r2 = b.state("r2", sys);
auto a2 = b.state("a2", r2);
auto b2 = b.state("b2", r2);
b.initial(sys);
b.parallel(sys);
b.initial(a1);
b.initial(a2);
const auto flip = b.event("flip");
b.transition(a1, flip, b1);
b.transition(a2, flip, b2);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{flip, {}});
m.run_pending();
Void::Testing::expect(m.is_in("b1"));
Void::Testing::expect(m.is_in("b2"));
}
// ── timers ────────────────────────────────────────────────────────────────────
Void::Testing::Test timeout_fires_after_duration()
{
Builder b;
auto waiting = b.state("waiting");
auto expired = b.state("expired");
b.initial(waiting);
const auto timeout_ev = b.event("timed_out");
b.timeout(waiting, std::chrono::milliseconds{20}, timeout_ev);
b.transition(waiting, timeout_ev, expired);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.run_pending();
Void::Testing::expect(m.is_in("waiting")); // not yet
std::this_thread::sleep_for(std::chrono::milliseconds{30});
m.run_pending();
Void::Testing::expect(m.is_in("expired"));
}
Void::Testing::Test timeout_cancelled_by_leaving_state()
{
Builder b;
auto waiting = b.state("waiting");
auto active = b.state("active");
auto expired = b.state("expired");
b.initial(waiting);
const auto timeout_ev = b.event("timed_out");
const auto go = b.event("go");
b.timeout(waiting, std::chrono::milliseconds{20}, timeout_ev);
b.transition(waiting, timeout_ev, expired);
b.transition(waiting, go, active);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{go, {}});
m.run_pending();
std::this_thread::sleep_for(std::chrono::milliseconds{30});
m.run_pending();
Void::Testing::expect(m.is_in("active")); // timer was disarmed
}
// @tag integration
Void::Testing::Test timeout_with_own_worker_thread()
{
Builder b;
auto waiting = b.state("waiting");
auto expired = b.state("expired");
b.initial(waiting);
const auto timeout_ev = b.event("timed_out");
b.timeout(waiting, std::chrono::milliseconds{15}, timeout_ev);
b.transition(waiting, timeout_ev, expired);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def}; // own worker
m.start();
for (int i = 0; i < 200 && !m.is_in("expired"); ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
Void::Testing::expect(m.is_in("expired"));
m.stop();
}
// ── coroutine actions / awaitable send ────────────────────────────────────────
Void::Testing::Test coro_action_completes_within_step()
{
std::vector<std::string> log;
Builder b;
auto a = b.state("a");
auto c = b.state("c");
b.initial(a);
const auto go = b.event("go");
b.transition(a, go, c).action(
Action{[&](Machine&, const Event&) -> Void::Coro::Task<void> {
log.push_back("action begin");
auto inner = []() -> Void::Coro::Task<int> { co_return 7; };
const int v = co_await inner();
log.push_back("inner " + std::to_string(v));
log.push_back("action end");
}});
b.on_entry(c, SyncAction{[&](Machine&, const Event&) {
log.push_back("enter c");
}});
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{go, {}});
m.run_pending();
const std::vector<std::string> expected{
"action begin", "inner 7", "action end", "enter c"};
Void::Testing::expect(log == expected);
}
// @tag integration
Void::Testing::Test send_wait_returns_step_result()
{
Builder b;
auto a = b.state("a");
auto c = b.state("c");
b.initial(a);
const auto go = b.event("go");
const auto noop = b.event("noop");
b.transition(a, go, c);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def}; // worker drives; send_wait blocks the caller
m.start();
Void::Testing::expect(m.send_wait(Event{go, {}}) ==
SendResult::Handled);
Void::Testing::expect(m.is_in("c"));
Void::Testing::expect(m.send_wait(Event{noop, {}}) ==
SendResult::Unhandled);
m.stop();
Void::Testing::expect(m.send_wait(Event{go, {}}) ==
SendResult::Dropped);
}
// @tag integration
Void::Testing::Test co_await_send_resolves_with_result()
{
Builder b;
auto a = b.state("a");
auto c = b.state("c");
b.initial(a);
const auto go = b.event("go");
b.transition(a, go, c);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def};
m.start();
std::optional<SendResult> result;
Void::Async::ManualExecutor ex;
Void::Async::spawn(
ex,
[](Machine& machine, Void::Async::Executor& resume_on,
std::optional<SendResult>& out) -> Void::Coro::Task<void> {
out = co_await machine.send(
Event{*machine.definition()->event_id("go"), {}},
&resume_on);
}(m, ex, result));
// Drain until the awaitable resumes us back on `ex` with the result.
for (int i = 0; i < 500 && !result.has_value(); ++i) {
if (ex.drain() == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
Void::Testing::expect(result.has_value());
Void::Testing::expect(*result == SendResult::Handled);
Void::Testing::expect(m.is_in("c"));
m.stop();
}
+239
View File
@@ -0,0 +1,239 @@
#include <Void/Fsm/Definition.hpp>
#include <Void/Fsm/Machine.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <memory>
#include <string>
#include <vector>
using namespace Void::Fsm;
namespace
{
struct Trace {
std::vector<std::string> log;
SyncAction enter(std::string name)
{
return [this, name](Machine&, const Event&) {
log.push_back("+" + name);
};
}
SyncAction exit(std::string name)
{
return [this, name](Machine&, const Event&) {
log.push_back("-" + name);
};
}
};
} // namespace
Void::Testing::Test hierarchy_descends_into_nested_initial()
{
Trace t;
Builder b;
auto outer = b.state("outer");
auto inner = b.state("inner", outer);
auto deep = b.state("deep", inner);
b.initial(outer);
b.initial(inner);
b.initial(deep);
b.on_entry(outer, t.enter("outer"));
b.on_entry(inner, t.enter("inner"));
b.on_entry(deep, t.enter("deep"));
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
const std::vector<std::string> expected{"+outer", "+inner", "+deep"};
Void::Testing::expect(t.log == expected);
Void::Testing::expect(m.is_in("outer"));
Void::Testing::expect(m.is_in("inner"));
Void::Testing::expect(m.is_in("deep"));
}
Void::Testing::Test hierarchy_lca_exit_entry_order()
{
Trace t;
Builder b;
auto top = b.state("top");
auto a = b.state("a", top);
auto a1 = b.state("a1", a);
auto c = b.state("c", top);
auto c1 = b.state("c1", c);
b.initial(top);
b.initial(a);
b.initial(a1);
b.initial(c1);
const auto hop = b.event("hop");
b.on_exit(a1, t.exit("a1"));
b.on_exit(a, t.exit("a"));
b.on_exit(top, t.exit("top"));
b.on_entry(c, t.enter("c"));
b.on_entry(c1, t.enter("c1"));
b.transition(a1, hop, c1);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
t.log.clear();
m.post(Event{hop, {}});
m.run_pending();
// LCA(a1, c1) = top: exit a1, a (innermost first; top stays),
// then enter c, c1 (outermost first).
const std::vector<std::string> expected{"-a1", "-a", "+c", "+c1"};
Void::Testing::expect(t.log == expected);
Void::Testing::expect(m.is_in("top"));
Void::Testing::expect(m.is_in("c1"));
}
Void::Testing::Test hierarchy_inner_transition_wins_over_outer()
{
Builder b;
auto outer = b.state("outer");
auto in1 = b.state("in1", outer);
auto in2 = b.state("in2", outer);
auto away = b.state("away");
b.initial(outer);
b.initial(in1);
const auto go = b.event("go");
b.transition(outer, go, away); // outer handler
b.transition(in1, go, in2); // inner handler must win
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{go, {}});
m.run_pending();
Void::Testing::expect(m.is_in("in2"));
Void::Testing::expect(!m.is_in("away"));
}
Void::Testing::Test hierarchy_outer_handles_when_inner_does_not()
{
Builder b;
auto outer = b.state("outer");
auto in1 = b.state("in1", outer);
auto away = b.state("away");
b.initial(outer);
b.initial(in1);
const auto leave = b.event("leave");
b.transition(outer, leave, away);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{leave, {}});
m.run_pending();
Void::Testing::expect(m.is_in("away"));
Void::Testing::expect(!m.is_in("outer"));
}
Void::Testing::Test hierarchy_shallow_history_restores_child()
{
Builder b;
auto work = b.state("work");
auto w1 = b.state("w1", work);
auto w2 = b.state("w2", work);
auto pause = b.state("pause");
b.initial(work);
b.initial(w1);
b.history(work, History::Shallow);
const auto next = b.event("next");
const auto stop_ = b.event("stop");
const auto resume = b.event("resume");
b.transition(w1, next, w2);
b.transition(work, stop_, pause);
b.transition(pause, resume, work);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{next, {}}); // w1 -> w2
m.post(Event{stop_, {}}); // -> pause (records w2)
m.run_pending();
Void::Testing::expect(m.is_in("pause"));
m.post(Event{resume, {}}); // -> work, history -> w2
m.run_pending();
Void::Testing::expect(m.is_in("w2"));
Void::Testing::expect(!m.is_in("w1"));
}
Void::Testing::Test hierarchy_deep_history_restores_leaves()
{
Builder b;
auto work = b.state("work");
auto sub = b.state("sub", work);
auto s1 = b.state("s1", sub);
auto s2 = b.state("s2", sub);
auto pause = b.state("pause");
b.initial(work);
b.initial(sub);
b.initial(s1);
b.history(work, History::Deep);
const auto next = b.event("next");
const auto stop_ = b.event("stop");
const auto resume = b.event("resume");
b.transition(s1, next, s2);
b.transition(work, stop_, pause);
b.transition(pause, resume, work);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{next, {}});
m.post(Event{stop_, {}});
m.run_pending();
Void::Testing::expect(m.is_in("pause"));
m.post(Event{resume, {}});
m.run_pending();
// Deep history re-activates the full chain down to s2 (shallow would
// have restored sub and then default-descended back into s1).
Void::Testing::expect(m.is_in("s2"));
Void::Testing::expect(!m.is_in("s1"));
}
Void::Testing::Test hierarchy_no_history_reenters_initial()
{
Builder b;
auto work = b.state("work");
auto w1 = b.state("w1", work);
auto w2 = b.state("w2", work);
auto pause = b.state("pause");
b.initial(work);
b.initial(w1);
const auto next = b.event("next");
const auto stop_ = b.event("stop");
const auto resume = b.event("resume");
b.transition(w1, next, w2);
b.transition(work, stop_, pause);
b.transition(pause, resume, work);
auto def = b.build();
Void::Testing::expect(def.has_value());
Machine m{*def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{next, {}});
m.post(Event{stop_, {}});
m.post(Event{resume, {}});
m.run_pending();
Void::Testing::expect(m.is_in("w1")); // back to initial, not w2
}
+186
View File
@@ -0,0 +1,186 @@
#include <Void/Fsm/Definition.hpp>
#include <Void/Fsm/Machine.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <memory>
#include <string>
using namespace Void::Fsm;
namespace
{
// work{ sub{ s1, s2 } }, pause — with deep history on work.
std::shared_ptr<const MachineDef> make_def()
{
Builder b;
auto work = b.state("work");
auto sub = b.state("sub", work);
auto s1 = b.state("s1", sub);
auto s2 = b.state("s2", sub);
auto pause = b.state("pause");
b.initial(work);
b.initial(sub);
b.initial(s1);
b.history(work, History::Deep);
b.transition(s1, b.event("next"), s2);
b.transition(work, b.event("stop"), pause);
b.transition(pause, b.event("resume"), work);
auto def = b.build();
Void::Testing::expect(def.has_value());
return *def;
}
} // namespace
Void::Testing::Test serialize_captures_leaves_by_name()
{
auto def = make_def();
Machine m{def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{*def->event_id("next"), {}});
m.run_pending();
const auto json = m.serialize_state();
Void::Testing::expect(json.is_object());
const auto& leaves = json["leaves"].as_array();
Void::Testing::expect_eq(leaves.size(), std::size_t{1});
Void::Testing::expect_eq(leaves[0].as_string(), std::string{"s2"});
}
Void::Testing::Test serialize_restore_round_trip()
{
auto def = make_def();
Void::Json::Value saved;
{
Machine m{def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{*def->event_id("next"), {}}); // s1 -> s2
m.run_pending();
saved = m.serialize_state();
m.stop();
}
Machine restored{def, MachineOptions{.own_worker = false}};
Void::Testing::expect(restored.restore_state(saved).has_value());
restored.start();
Void::Testing::expect(restored.is_in("s2"));
Void::Testing::expect(restored.is_in("work"));
Void::Testing::expect(!restored.is_in("s1"));
// The restored machine behaves identically: stop/resume goes back
// to s2 via deep history captured in the serialized state.
restored.post(Event{*def->event_id("stop"), {}});
restored.post(Event{*def->event_id("resume"), {}});
restored.run_pending();
Void::Testing::expect(restored.is_in("s2"));
}
Void::Testing::Test serialize_preserves_history_records()
{
auto def = make_def();
Void::Json::Value saved;
{
Machine m{def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{*def->event_id("next"), {}}); // -> s2
m.post(Event{*def->event_id("stop"), {}}); // -> pause, hist {s2}
m.run_pending();
saved = m.serialize_state();
m.stop();
}
Machine restored{def, MachineOptions{.own_worker = false}};
Void::Testing::expect(restored.restore_state(saved).has_value());
restored.start();
Void::Testing::expect(restored.is_in("pause"));
restored.post(Event{*def->event_id("resume"), {}});
restored.run_pending();
Void::Testing::expect(restored.is_in("s2")); // history survived
}
Void::Testing::Test restore_rejects_running_machine_and_garbage()
{
auto def = make_def();
Machine m{def, MachineOptions{.own_worker = false}};
Void::Testing::expect(
!m.restore_state(Void::Json::Value{42}).has_value());
m.start();
const auto state = m.serialize_state();
Void::Testing::expect(!m.restore_state(state).has_value());
}
Void::Testing::Test restore_with_unknown_states_falls_back_to_initial()
{
auto def = make_def();
auto bogus = Void::Json::parse(
R"({"__fsm":1,"leaves":["no_such_state"],"history":{}})");
Void::Testing::expect(bogus.has_value());
Machine m{def, MachineOptions{.own_worker = false}};
Void::Testing::expect(m.restore_state(*bogus).has_value());
m.start();
Void::Testing::expect(m.is_in("s1")); // initial configuration
}
// ── hot definition swap ───────────────────────────────────────────────────────
Void::Testing::Test swap_same_names_keeps_configuration()
{
auto def = make_def();
Machine m{def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{*def->event_id("next"), {}}); // -> s2
m.run_pending();
int entries = 0;
// New definition: same state names, one extra transition + an entry
// probe that must NOT run during a seamless swap.
Builder b;
auto work = b.state("work");
auto sub = b.state("sub", work);
auto s1 = b.state("s1", sub);
auto s2 = b.state("s2", sub);
auto pause = b.state("pause");
b.initial(work);
b.initial(sub);
b.initial(s1);
b.on_entry(s2, SyncAction{[&](Machine&, const Event&) {
++entries;
}});
b.transition(s2, b.event("back"), s1); // new behavior
b.transition(work, b.event("stop"), pause);
auto next_def = b.build();
Void::Testing::expect(next_def.has_value());
m.swap_definition(*next_def);
m.run_pending();
Void::Testing::expect(m.is_in("s2")); // configuration survived
Void::Testing::expect_eq(entries, 0); // no re-entry side effects
// New transition is live.
m.post(Event{*(*next_def)->event_id("back"), {}});
m.run_pending();
Void::Testing::expect(m.is_in("s1"));
}
Void::Testing::Test swap_with_missing_states_reenters_initial()
{
auto def = make_def();
Machine m{def, MachineOptions{.own_worker = false}};
m.start();
m.post(Event{*def->event_id("next"), {}}); // -> s2
m.run_pending();
Builder b;
(void)b.state("fresh_a");
(void)b.state("fresh_b");
auto next_def = b.build();
Void::Testing::expect(next_def.has_value());
m.swap_definition(*next_def);
m.run_pending();
Void::Testing::expect(m.is_in("fresh_a"));
}