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

337 lines
10 KiB
C++

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