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>
270 lines
7.4 KiB
C++
270 lines
7.4 KiB
C++
#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
|