FSM (3): direct control — fluent events, free jumps, lifecycle, mutation

Adds imperative ergonomics for driving and reshaping a machine. The engine
isn't preemptible mid-state (coroutines aren't interruptible), so external
controls apply at transition boundaries and mutation is Idle-only — both
documented.

- Fluent events: send(e1, e2, …) variadic post.
- Free runtime jumps: in-state goto_state<S>() reaches any registered state
  with no declared transition ("each state can be moved to another state");
  external jump<S>() requests a redirect applied by drive() at the next
  boundary (race-safe via an atomic, non-preemptive).
- Lifecycle: reset() returns a finished/idle machine to Idle (drops the
  owned ctx, clears outcome/current/jump); restart() / restart_at<S>()
  re-run; pause() / resume() (ExecutionContext gains a paused flag — the
  worker stops draining and pump() no-ops while paused; posted events
  buffer until resume()).
- Runtime mutation (Idle only): remove<S>() (re-packs indices,
  fixes the initial), set_initial<S>(), replace<S, T>().

8 new tests (Direct): send batch, goto_state skip, boundary jump (embedder
mode), restart / restart_at, remove + set_initial, replace, pause holds
events until resume. 995 green, ASan+UBSan clean, 0 flaky in 15 runs,
-Werror clean. Completes the FSM refactor plan (1-3).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 15:44:19 +03:00
1 parent b34226369a
commit 7c7c590d79
5 files changed
+457 -3

No files matched your search

+3
View File
@@ -149,12 +149,15 @@ Other key points:
`Void::Fsm::Machine<ResultT>` — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task<Step> run()` returning `next<S>()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves. `Void::Fsm::Machine<ResultT>` — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task<Step> run()` returning `next<S>()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves.
Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp` (the `Machine<Derived, ResultT>` template + `States<>`, nested `State`/`Reactive`/`Continue` bases, lifecycle, events, nesting, persistence); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable<Derived,…>` templates, aliased by `Machine::Reactive`); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Continuation.hpp` (`Detail::Continuation<State,R>` = `Continue<R>`, with a `void` specialization); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase`); `Detail/TypeName.hpp` (`type_name<T>()`).
- **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests). - **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests).
- **Events**: `co_await await_event<E>()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post<E>(e)` is lock-free from any thread. - **Events**: `co_await await_event<E>()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post<E>(e)` is lock-free from any thread.
- **Nesting**: `co_await run_child<Sub>(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected<R, FsmError>`) — the imperative form, branch on it yourself. - **Nesting**: `co_await run_child<Sub>(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected<R, FsmError>`) — the imperative form, branch on it yourself.
- **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (a `static_assert` enforces it) and be in `States<>`. A `Continue` handler may itself return another `startMachine` (chaining) or any normal `Step`. Mechanics: a `Step::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's `resume()` (overridden by `Continue<R>`) dispatches — a plain state entered with a pending result just `run()`s. - **Sub-machine continuations (declarative)**: `co_return startMachine<Sub, Next>(args...)` launches `Sub` (constructed from `args`, on the shared executor/events/services), then enters `Next` and the engine **finds on its own which method to call** — `Next` derives `Continue<Sub::result_type>` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue<void>` takes a nullary `on_success()`). `Next` must derive `Continue<R>` (a `static_assert` enforces it) and be in `States<>`. A `Continue` handler may itself return another `startMachine` (chaining) or any normal `Step`. Mechanics: a `Step::Kind::Launch` carries the target + a type-erased launcher; `drive()` runs it, stashes the `LaunchResult`, and the entered state's `resume()` (overridden by `Continue<R>`) dispatches — a plain state entered with a pending result just `run()`s.
- **Composite sub-states (hierarchy)**: `co_await run_region<Sub>()` is `run_child` with introspection — the calling state's `on_enter`/`on_exit` wrap the child region, and the parent's `state_path()` reports the parent→child chain (`{Composite, …child leaf}`) while it runs. Map the child's `Outcome` to a sibling transition (`r ? next<Done>() : next<Recover>()`). Parent-level multi-event handling via `co_await await_any<E1, E2, …>()` → `std::variant<Es...>` (e.g. a region waits for `Tick` or `Cancel` at one level). Coroutines aren't preemptible mid-flight, so child cancellation is **cooperative**: the region awaits a shared `Cancel` event (events route to the deepest awaiter) and returns a failing `Outcome` the parent maps — no frame is abandoned. - **Composite sub-states (hierarchy)**: `co_await run_region<Sub>()` is `run_child` with introspection — the calling state's `on_enter`/`on_exit` wrap the child region, and the parent's `state_path()` reports the parent→child chain (`{Composite, …child leaf}`) while it runs. Map the child's `Outcome` to a sibling transition (`r ? next<Done>() : next<Recover>()`). Parent-level multi-event handling via `co_await await_any<E1, E2, …>()` → `std::variant<Es...>` (e.g. a region waits for `Tick` or `Cancel` at one level). Coroutines aren't preemptible mid-flight, so child cancellation is **cooperative**: the region awaits a shared `Cancel` event (events route to the deepest awaiter) and returns a failing `Outcome` the parent maps — no frame is abandoned.
- **Dynamic**: `add<S>()` / `add_if<S>(cond)`; `next<unregistered>` fails; `has_state<S>()` lets a state branch. - **Dynamic**: `add<S>()` / `add_if<S>(cond)`; `next<unregistered>` fails; `has_state<S>()` lets a state branch.
- **Direct control**: fluent `send(e1, e2, …)` (variadic `post`); free in-state jumps via `goto_state<S>()` (any registered state, no declared transition); external `jump<S>()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at<S>()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove<S>()` / `set_initial<S>()` / `replace<S, T>()`.
- **Services**: `set_services(registry)`; `state.service<I>()` resolves through the injected context. - **Services**: `set_services(registry)`; `state.service<I>()` resolves through the injected context.
- **Observation**: `current_state()` is a lock-free atomic-index read of an immutable name table (P2996 `identifier_of`, fallback to indexed names). `state_path()` is the same but appends an active `run_region` child's path — consumer-consistent (read it from within the machine or once settled; deterministic in `pump()` mode). - **Observation**: `current_state()` is a lock-free atomic-index read of an immutable name table (P2996 `identifier_of`, fallback to indexed names). `state_path()` is the same but appends an active `run_region` child's path — consumer-consistent (read it from within the machine or once settled; deterministic in `pump()` mode).
- **Introspection**: `describe()` lists registered states (name, reactive?, initial?) plus the transitions declared by reactive states (event/target names, guard-present); imperative `run()`-chosen edges aren't statically knowable so those states are edgeless nodes. `to_mermaid()` renders a `stateDiagram-v2` string. - **Introspection**: `describe()` lists registered states (name, reactive?, initial?) plus the transitions declared by reactive states (event/target names, guard-present); imperative `run()`-chosen edges aren't statically knowable so those states are edgeless nodes. `to_mermaid()` renders a `stateDiagram-v2` string.
+9
View File
@@ -132,8 +132,16 @@ namespace Void::Fsm::Detail
/// Embedder-driven step: deliver queued events + run ready /// Embedder-driven step: deliver queued events + run ready
/// coroutines. Returns work done count. Single consumer only. /// coroutines. Returns work done count. Single consumer only.
/// A no-op (returns 0) while paused.
std::size_t pump(); std::size_t pump();
/// Pause / resume event processing. While paused the worker stops
/// draining (and pump() is a no-op); posted events buffer.
void set_paused(bool paused);
/// Wake the consumer (e.g. to re-check an external jump request).
void nudge() { wake(); }
private: private:
void deliver(EventEnvelope& env); void deliver(EventEnvelope& env);
@@ -180,6 +188,7 @@ namespace Void::Fsm::Detail
std::counting_semaphore<> m_wakeup{0}; std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false}; std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_done{false}; std::atomic<bool> m_done{false};
std::atomic<bool> m_paused{false};
std::atomic<bool> m_worker_started{false}; std::atomic<bool> m_worker_started{false};
std::once_flag m_worker_once; std::once_flag m_worker_once;
std::thread m_worker; std::thread m_worker;
+148
View File
@@ -136,6 +136,16 @@ namespace Void::Fsm
return Step::transition(typeid(S)); return Step::transition(typeid(S));
} }
/// Free jump to any registered state — no declared
/// transition required ("each state can be moved to
/// another state"). Like next_dynamic, skips the
/// States<...> compile-time check; runtime-fails only if S
/// was never registered.
template <typename S> [[nodiscard]] Step goto_state() const
{
return Step::transition(typeid(S));
}
/// Route to a fallback state if `step` is a failure, /// Route to a fallback state if `step` is a failure,
/// otherwise pass it through — for error policies: /// otherwise pass it through — for error policies:
/// co_return next_or<Recovery>(co_await try_work()); /// co_return next_or<Recovery>(co_await try_work());
@@ -433,6 +443,62 @@ namespace Void::Fsm
return m_factories.contains(std::type_index{typeid(S)}); return m_factories.contains(std::type_index{typeid(S)});
} }
/// Make `S` the initial state (registers it if needed). Idle-only.
template <typename S> void set_initial()
{
if (m_status.load() != Status::Idle) {
return;
}
add<S>();
m_initial = &typeid(S);
}
/// Unregister a state. Idle-only (running indices are fixed). If it
/// was the initial state, the initial falls back to the first
/// remaining state (or none).
template <typename S> void remove()
{
if (m_status.load() != Status::Idle) {
return;
}
const std::type_index key{typeid(S)};
const auto idxIt = m_index.find(key);
if (idxIt == m_index.end()) {
return;
}
const int idx = idxIt->second;
m_name_to_type.erase(m_names[static_cast<std::size_t>(idx)]);
m_names.erase(m_names.begin() + idx);
m_factories.erase(key);
m_index.erase(idxIt);
// Re-pack the indices of states that followed S.
for (auto& [k, v] : m_index) {
if (v > idx) {
--v;
}
}
if (m_initial == &typeid(S)) {
m_initial = m_names.empty()
? nullptr
: m_name_to_type.at(m_names.front());
}
}
/// Swap state `S` for `T`, preserving the initial pointer if S was
/// it. Idle-only.
template <typename S, typename T> void replace()
{
if (m_status.load() != Status::Idle) {
return;
}
const bool was_initial = (m_initial == &typeid(S));
remove<S>();
add<T>();
if (was_initial) {
m_initial = &typeid(T);
}
}
// ── service context ─────────────────────────────────────────── // ── service context ───────────────────────────────────────────
void set_services(Service::ServiceRegistry& registry) noexcept void set_services(Service::ServiceRegistry& registry) noexcept
{ {
@@ -525,6 +591,58 @@ namespace Void::Fsm
} }
} }
/// Return a finished (or idle) machine to Idle so it can run
/// again: drops the owned execution context, clears the
/// outcome/current-state/jump. No-op while Running.
void reset()
{
if (m_status.load() == Status::Running) {
return;
}
if (m_owns_ctx && m_ctx) {
m_ctx->stop();
}
m_ctx.reset();
m_owns_ctx = false;
m_current.store(-1, std::memory_order_release);
m_outcome.reset();
m_pending_result.reset();
m_jump.store(nullptr, std::memory_order_release);
m_step = 0;
m_status.store(Status::Idle, std::memory_order_release);
}
/// reset() then start() from the initial state.
void restart()
{
reset();
start();
}
/// reset(), make `S` the initial state, then start().
template <typename S> void restart_at()
{
reset();
m_initial = &typeid(S);
start();
}
/// Pause / resume event processing (best-effort: a state already
/// running finishes; further progress waits). Events posted while
/// paused buffer until resume().
void pause()
{
if (m_ctx) {
m_ctx->set_paused(true);
}
}
void resume()
{
if (m_ctx) {
m_ctx->set_paused(false);
}
}
// ── events ──────────────────────────────────────────────────── // ── events ────────────────────────────────────────────────────
template <typename E> void post(E event) template <typename E> void post(E event)
{ {
@@ -535,6 +653,25 @@ namespace Void::Fsm
std::any{std::move(event)}}); std::any{std::move(event)}});
} }
/// Fluent post: send one or several events in one call.
/// fsm.send(Go{5}); fsm.send(Go{5}, Stop{});
template <typename... Es> void send(Es&&... events)
{
(post(std::forward<Es>(events)), ...);
}
/// Request a jump to any registered state `S` from outside the
/// machine. Race-safe; applied at the next transition boundary
/// (a running state isn't preempted — coroutines aren't
/// interruptible mid-flight).
template <typename S> void jump()
{
m_jump.store(&typeid(S), std::memory_order_release);
if (m_ctx) {
m_ctx->nudge();
}
}
template <typename E> [[nodiscard]] auto await_event() template <typename E> [[nodiscard]] auto await_event()
{ {
return Detail::make_event_awaiter( return Detail::make_event_awaiter(
@@ -912,6 +1049,13 @@ namespace Void::Fsm
co_return std::unexpected{FsmError{"no initial state"}}; co_return std::unexpected{FsmError{"no initial state"}};
} }
for (;;) { for (;;) {
// Apply an external jump<S>() at this transition boundary.
if (const auto* j =
m_jump.exchange(nullptr, std::memory_order_acq_rel);
j != nullptr) {
cur = j;
m_pending_result.reset();
}
const auto it = m_factories.find(std::type_index{*cur}); const auto it = m_factories.find(std::type_index{*cur});
if (it == m_factories.end()) { if (it == m_factories.end()) {
co_return std::unexpected{ co_return std::unexpected{
@@ -1005,6 +1149,10 @@ namespace Void::Fsm
// Set by a Launch step's sub-machine result; consumed by the next // Set by a Launch step's sub-machine result; consumed by the next
// state's resume() (a Continue<R> dispatch). // state's resume() (a Continue<R> dispatch).
std::optional<LaunchResult> m_pending_result; std::optional<LaunchResult> m_pending_result;
// External jump request (jump<S>()); applied by drive() at the
// next transition boundary.
std::atomic<const std::type_info*> m_jump{nullptr};
}; };
} // namespace Void::Fsm } // namespace Void::Fsm
+19 -3
View File
@@ -136,8 +136,17 @@ namespace Void::Fsm::Detail
m_buffers[std::type_index{*env.type}].push_back(std::move(env.value)); m_buffers[std::type_index{*env.type}].push_back(std::move(env.value));
} }
void ExecutionContext::set_paused(bool paused)
{
m_paused.store(paused, std::memory_order_release);
wake();
}
std::size_t ExecutionContext::pump() std::size_t ExecutionContext::pump()
{ {
if (m_paused.load(std::memory_order_acquire)) {
return 0;
}
std::size_t work = 0; std::size_t work = 0;
fire_due_timers(); fire_due_timers();
while (auto env = m_queue.try_pop()) { while (auto env = m_queue.try_pop()) {
@@ -192,17 +201,24 @@ namespace Void::Fsm::Detail
void ExecutionContext::run_loop() void ExecutionContext::run_loop()
{ {
for (;;) { for (;;) {
const bool paused = m_paused.load(std::memory_order_acquire);
if (!paused) {
pump(); pump();
}
if (m_done.load(std::memory_order_acquire)) { if (m_done.load(std::memory_order_acquire)) {
return; return;
} }
m_sleeping.store(true, std::memory_order_release); m_sleeping.store(true, std::memory_order_release);
if (!m_queue.empty() || m_done.load(std::memory_order_acquire)) { // Queued events only count as wakeable work when not paused.
if ((!paused && !m_queue.empty()) ||
m_done.load(std::memory_order_acquire)) {
m_sleeping.store(false, std::memory_order_release); m_sleeping.store(false, std::memory_order_release);
continue; continue;
} }
// Park until woken, or until the earliest timer is due. // Park until woken (post/resume/finish), or — when running — until
if (const auto deadline = next_deadline(); deadline.has_value()) { // the earliest timer is due. Paused: no timers, wait to resume.
if (const auto deadline = next_deadline();
!paused && deadline.has_value()) {
(void)m_wakeup.try_acquire_until(*deadline); (void)m_wakeup.try_acquire_until(*deadline);
} else { } else {
m_wakeup.acquire(); m_wakeup.acquire();
+278
View File
@@ -0,0 +1,278 @@
#include <Void/Fsm/Fsm.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <thread>
using Void::Coro::Task;
using Void::Fsm::MachineOptions;
using Void::Fsm::Step;
namespace Fsm = Void::Fsm;
using namespace std::chrono_literals;
// ── fluent events + free jumps ──────────────────────────────────────────────
namespace
{
struct Add {
int n;
};
// Sums two Add events, posted in one fluent send() call.
class Sum : public Fsm::Machine<Sum, int>
{
public:
int total = 0;
struct Take : State {
Task<Step> run() override
{
auto a = co_await await_event<Add>();
self().total += a.n;
auto b = co_await await_event<Add>();
self().total += b.n;
co_return succeed(self().total);
}
};
using States = Fsm::States<Take>;
};
} // namespace
// @tag integration
Void::Testing::Test send_posts_multiple_events()
{
Sum fsm;
fsm.start();
fsm.send(Add{3}, Add{4}); // one fluent call, two events
const auto outcome = fsm.wait();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 7);
}
namespace
{
// A and C are not connected by any declared edge; goto_state<C>() jumps
// from A to C freely.
class Hop : public Fsm::Machine<Hop, int>
{
public:
struct A : State {
Task<Step> run() override { co_return goto_state<C>(); }
};
struct B : State {
Task<Step> run() override { co_return succeed(1); }
};
struct C : State {
Task<Step> run() override { co_return succeed(3); }
};
using States = Fsm::States<A, B, C>;
};
} // namespace
// @tag integration
Void::Testing::Test goto_state_jumps_to_any_registered_state()
{
Hop fsm;
const auto outcome = fsm.run_blocking();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 3); // went A -> C, skipping B
}
namespace
{
struct Tick {
};
// Loops in Loop on each Tick; an external jump<Done>() redirects at the
// next boundary.
class Jumper : public Fsm::Machine<Jumper, int>
{
public:
struct Loop : State {
Task<Step> run() override
{
co_await await_event<Tick>();
co_return next<Loop>();
}
};
struct Done : State {
Task<Step> run() override { co_return succeed(99); }
};
using States = Fsm::States<Loop, Done>;
explicit Jumper(MachineOptions o = {})
: Fsm::Machine<Jumper, int>(o)
{
}
};
} // namespace
Void::Testing::Test jump_redirects_at_next_boundary()
{
Jumper fsm{MachineOptions{.own_worker = false}};
fsm.start();
while (fsm.pump() > 0) {
} // enter Loop, park on Tick
fsm.send(Tick{});
while (fsm.pump() > 0) {
} // Loop -> next<Loop> -> park again
fsm.jump<Jumper::Done>(); // request a jump
fsm.send(Tick{});
while (fsm.pump() > 0) {
} // Loop finishes -> boundary applies the jump -> Done
const auto outcome = fsm.wait();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 99);
}
// ── lifecycle control ───────────────────────────────────────────────────────
namespace
{
// Increments a machine-owned counter each run (data survives reset()).
class Counter : public Fsm::Machine<Counter, int>
{
public:
int runs = 0;
struct Once : State {
Task<Step> run() override
{
co_return succeed(++self().runs);
}
};
using States = Fsm::States<Once>;
};
} // namespace
// @tag integration
Void::Testing::Test restart_reruns_the_machine()
{
Counter fsm;
const auto first = fsm.run_blocking();
Void::Testing::expect_eq(*first, 1);
fsm.restart();
const auto second = fsm.wait();
Void::Testing::expect_eq(*second, 2);
}
namespace
{
class Pick : public Fsm::Machine<Pick, int>
{
public:
struct A : State {
Task<Step> run() override { co_return succeed(1); }
};
struct B : State {
Task<Step> run() override { co_return succeed(2); }
};
using States = Fsm::States<A, B>; // initial = A
};
} // namespace
// @tag integration
Void::Testing::Test restart_at_changes_initial_state()
{
Pick fsm;
const auto first = fsm.run_blocking();
Void::Testing::expect_eq(*first, 1); // A
fsm.restart_at<Pick::B>();
const auto second = fsm.wait();
Void::Testing::expect_eq(*second, 2); // B
}
// ── runtime mutation (Idle only) ────────────────────────────────────────────
namespace
{
class Mut : public Fsm::Machine<Mut, int>
{
public:
struct A : State {
Task<Step> run() override { co_return succeed(1); }
};
struct B : State {
Task<Step> run() override { co_return succeed(2); }
};
struct C : State {
Task<Step> run() override { co_return succeed(3); }
};
// Not in States<> — added via replace<>.
struct Extra : State {
Task<Step> run() override { co_return succeed(7); }
};
using States = Fsm::States<A, B, C>;
};
} // namespace
Void::Testing::Test remove_and_set_initial_before_start()
{
Mut fsm;
Void::Testing::expect(fsm.has_state<Mut::C>());
fsm.remove<Mut::C>();
Void::Testing::expect(!fsm.has_state<Mut::C>());
Void::Testing::expect_eq(fsm.describe().size(), std::size_t{2});
fsm.set_initial<Mut::B>();
const auto outcome = fsm.run_blocking();
Void::Testing::expect_eq(*outcome, 2);
}
Void::Testing::Test replace_swaps_a_state_and_keeps_initial()
{
Mut fsm;
fsm.replace<Mut::A, Mut::Extra>(); // A was initial -> Extra becomes initial
Void::Testing::expect(!fsm.has_state<Mut::A>());
Void::Testing::expect(fsm.has_state<Mut::Extra>());
const auto outcome = fsm.run_blocking();
Void::Testing::expect_eq(*outcome, 7);
}
// ── pause / resume ──────────────────────────────────────────────────────────
namespace
{
struct Go {
};
class Sleeper : public Fsm::Machine<Sleeper, int>
{
public:
struct W : State {
Task<Step> run() override
{
co_await await_event<Go>();
co_return succeed(5);
}
};
using States = Fsm::States<W>;
};
} // namespace
// @tag integration
Void::Testing::Test pause_holds_events_until_resume()
{
Sleeper fsm;
fsm.start();
fsm.pause();
fsm.post(Go{}); // buffered while paused, not delivered
std::this_thread::sleep_for(20ms);
Void::Testing::expect(!fsm.finished()); // still parked, event held
fsm.resume();
const auto outcome = fsm.wait();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 5);
}