Files
Library/tests/standalone/Fsm/Basic.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

248 lines
6.9 KiB
C++

#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"));
}