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

222 lines
6.2 KiB
C++

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