Files
Library/tests/standalone/Fsm/Hierarchy.cpp
T
faumarayandClaude Fable 5 697e07843c 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>
2026-06-13 00:49:45 +03:00

240 lines
6.7 KiB
C++

#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
}