FSM (8): deferred events + richer reactive DSL — completes the upgrade

Final phase of the FSM upgrade. Extends the reactive transition DSL:

- Deferred events: on.defer<E>() holds an E that arrives while in the state
  (instead of dropping it) and re-posts it to the mailbox after the next
  transition (UML deferred-event semantics). The reactive loop awaits the
  declared + deferred types, accumulates held envelopes, and re-injects them
  via Machine::repost() on exit.
- Entry/exit actions: on.enter(fn) / on.exit(fn) run when the reactive state
  is entered / left (around the wait loop).
- Internal transitions: on.event<E>().internal(fn) runs fn on E but stays in
  the state — no exit/enter, no transition (EventEntry gains an `internal`
  flag; the loop runs the action and keeps waiting).

2 new tests (Defer): a deferred Click is held in Busy and replayed in Idle
after Done (with enter/exit ordering asserted); three internal Ticks
accumulate with the state entered exactly once. 1002 tests (999 green, 3
skipped), ASan/UBSan clean, -Werror clean.

This finishes the requested FSM upgrade: one signature-inferred State,
typed Success/Failure results, multi-waiter mailbox, parallel/orthogonal
regions, history states, and the deferred/internal/entry-exit DSL.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-15 02:48:27 +03:00
1 parent 2903eca3a6
commit 4af3ee6d0c
5 files changed
+216 -7

No files matched your search

+1
View File
@@ -170,6 +170,7 @@ Header layout (include `<Void/Fsm/Fsm.hpp>` — a thin umbrella): `Machine.hpp`
- **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.
- **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).
- **Reactive DSL extras**: `on.defer<E>()` holds event `E` while in the state and re-posts it after the next transition (UML deferred events) instead of dropping it; `on.enter(fn)` / `on.exit(fn)` are entry/exit actions run by the reactive loop; `on.event<E>().internal(fn)` handles `E` (runs `fn`) **without** leaving the state (no exit/enter/transition).
- **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.
- **Error policies / middleware**: state helpers `delay(d)`, `with_retry(times, backoff, attempt)` (retries a `Coro::Task<bool>` sub-step), `next_or<Fallback>(step)` (route a failing `Step` to a fallback state). `add_interceptor({before(Transition), after(state_name)})` runs ordered hooks around each transition; `observe(fn)` is the single read-only observer.
- **Persistence**: `serialize()` → `{state name, on_serialize data}`; `restore()` on an un-started machine resumes at the named state (override `on_serialize`/`on_restore` for derived data, reflection-JSON friendly).
+47 -3
View File
@@ -26,23 +26,32 @@ namespace Void::Fsm::Detail
namespace Coro = Void::Coro;
/// One declared transition: event type, optional guard/action, the Step to
/// take, plus names for introspection.
/// take, plus names for introspection. An `internal` entry runs its action
/// and stays in the state (no exit/enter/transition).
template <typename Derived> struct EventEntry {
const std::type_info* type{nullptr};
std::function<bool(Derived&, const std::any&)> guard;
std::function<Coro::Task<void>(Derived&, const std::any&)> action;
Step step;
bool internal{false};
std::string event_name; // for introspection
std::string target_name; // for introspection
};
/// A reactive state's full transition table (events + an optional timeout).
/// A reactive state's full transition table (events + an optional timeout,
/// deferred event types, and entry/exit actions).
template <typename Derived> struct TransitionTable {
std::vector<EventEntry<Derived>> events;
bool has_timeout{false};
std::chrono::steady_clock::duration timeout_after{};
Step timeout_step;
std::string timeout_target_name;
// Event types deferred while in this state (held, re-posted on the
// next transition) instead of dropped.
std::vector<const std::type_info*> deferred;
// Entry/exit actions (run by the reactive loop around the state).
std::function<Coro::Task<void>(Derived&)> enter_action;
std::function<Coro::Task<void>(Derived&)> exit_action;
};
/// Fluent builder for one event row: `on.event<E>().guard(..).action(..)
@@ -117,9 +126,17 @@ namespace Void::Fsm::Detail
"(fail)");
}
/// Internal transition: run `fn` on the event but stay in the
/// state (no exit/enter, no transition).
void internal(std::function<void(Derived&, const E&)> fn)
{
action(std::move(fn));
commit(Step::success(std::any{}), "(internal)", true);
}
private:
void commit(Step step, std::string target)
void commit(Step step, std::string target, bool is_internal = false)
{
EventEntry<Derived> entry;
entry.type = &typeid(E);
@@ -138,6 +155,7 @@ namespace Void::Fsm::Detail
};
}
entry.step = std::move(step);
entry.internal = is_internal;
entry.event_name = type_name<E>();
entry.target_name = std::move(target);
m_table->events.push_back(std::move(entry));
@@ -220,6 +238,32 @@ namespace Void::Fsm::Detail
std::chrono::steady_clock::duration>(d)};
}
/// Defer event `E` while in this state: hold it (don't drop) and
/// re-post it after the next transition (UML deferred events).
template <typename E> void defer()
{
m_table->deferred.push_back(&typeid(E));
}
/// Entry action — run when the state is entered (before it waits).
void enter(std::function<void(Derived&)> fn)
{
m_table->enter_action =
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
fn(d);
co_return;
};
}
/// Exit action — run when the state is left (on any transition).
void exit(std::function<void(Derived&)> fn)
{
m_table->exit_action =
[fn = std::move(fn)](Derived& d) -> Coro::Task<void> {
fn(d);
co_return;
};
}
private:
TransitionTable<Derived>* m_table;
+40 -4
View File
@@ -6,6 +6,7 @@
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Step.hpp>
#include <algorithm>
#include <any>
#include <chrono>
#include <concepts>
@@ -234,11 +235,31 @@ namespace Void::Fsm
using D = MachineOf<S>;
TransitionTable<D> table;
collect_transitions(s, table);
// Await the declared event types *and* the deferred ones (so a
// deferred event wakes us to be held, not dropped).
std::vector<const std::type_info*> types;
types.reserve(table.events.size());
types.reserve(table.events.size() + table.deferred.size());
for (const auto& e : table.events) {
types.push_back(e.type);
}
for (const auto* dt : table.deferred) {
types.push_back(dt);
}
D& d = s.self();
if (table.enter_action) {
co_await table.enter_action(d);
}
// Events deferred while here, re-posted on exit.
std::vector<EventEnvelope> held;
auto leave = [&](Step step) -> Coro::Task<Step> {
if (table.exit_action) {
co_await table.exit_action(d);
}
for (auto& h : held) {
s.machine().repost(std::move(h));
}
co_return std::move(step);
};
for (;;) {
std::optional<std::chrono::steady_clock::time_point> deadline;
if (table.has_timeout) {
@@ -247,9 +268,9 @@ namespace Void::Fsm
}
auto ev = co_await s.machine().await_any_event(types, deadline);
if (!ev) {
co_return std::move(table.timeout_step);
co_return co_await leave(std::move(table.timeout_step));
}
D& d = s.self();
bool matched = false;
for (auto& e : table.events) {
if (*e.type != *ev->type) {
continue;
@@ -260,7 +281,22 @@ namespace Void::Fsm
if (e.action) {
co_await e.action(d, ev->value);
}
co_return std::move(e.step);
matched = true;
if (!e.internal) {
co_return co_await leave(std::move(e.step));
}
break; // internal: handled, stay in the state
}
if (!matched) {
// No entry took it: hold if deferred, else drop.
const bool is_deferred = std::any_of(
table.deferred.begin(), table.deferred.end(),
[&](const std::type_info* t) {
return *t == *ev->type;
});
if (is_deferred) {
held.push_back(std::move(*ev));
}
}
}
}
+9
View File
@@ -654,6 +654,15 @@ namespace Void::Fsm
std::any{std::move(event)}});
}
/// Re-post an already type-erased event (used by the reactive loop
/// to re-inject deferred events after a transition).
void repost(Detail::EventEnvelope env)
{
if (m_ctx) {
m_ctx->post(std::move(env));
}
}
/// 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)
+119
View File
@@ -0,0 +1,119 @@
#include <Void/Fsm/Fsm.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <vector>
using Void::Coro::Task;
using Void::Fsm::Step;
namespace Fsm = Void::Fsm;
// Phase-6 reactive DSL: deferred events (held + replayed after a transition),
// entry/exit actions (on.enter/on.exit), and internal transitions (handle an
// event without leaving the state).
namespace
{
struct Click {
};
struct Done {
};
// Busy defers Click (held, not dropped) and runs enter/exit actions; on
// Done it transitions to Idle, which then handles the replayed Click.
class Flow : public Fsm::Machine<Flow>
{
public:
using Success = int;
std::vector<std::string> log;
struct Busy : State {
void transitions(TransitionBuilder& on)
{
on.enter([](Flow& m) { m.log.push_back("enter"); });
on.exit([](Flow& m) { m.log.push_back("exit"); });
on.template defer<Click>();
on.template event<Done>().template to<Idle>();
}
};
struct Idle : State {
void transitions(TransitionBuilder& on)
{
on.template event<Click>()
.action([](Flow& m, const Click&) {
m.log.push_back("click");
})
.template to<End>();
}
};
struct End : State {
Task<Step> run() { co_return succeed(1); }
};
using States = Fsm::States<Busy, Idle, End>;
};
} // namespace
// @tag integration
Void::Testing::Test deferred_event_replays_after_transition()
{
Flow fsm;
fsm.start();
fsm.send(Click{}); // deferred while in Busy (not dropped)
fsm.send(Done{}); // Busy -> Idle; the held Click is replayed -> End
const auto outcome = fsm.wait();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 1);
// enter/exit actions fired around Busy; the deferred Click was handled.
const std::vector<std::string> expected{"enter", "exit", "click"};
Void::Testing::expect(fsm.log == expected);
}
// ── internal transition ─────────────────────────────────────────────────────
namespace
{
struct Tick {
};
struct Stop {
};
// Counter handles Tick internally (no exit/enter, no transition); Stop
// leaves with the accumulated count.
class Counter : public Fsm::Machine<Counter>
{
public:
using Success = int;
int ticks = 0;
int enters = 0;
struct Run : State {
void transitions(TransitionBuilder& on)
{
on.enter([](Counter& m) { ++m.enters; });
on.template event<Tick>().internal(
[](Counter& m, const Tick&) { ++m.ticks; });
on.template event<Stop>().template to<Done>();
}
};
struct Done : State {
Task<Step> run() { co_return succeed(self().ticks); }
};
using States = Fsm::States<Run, Done>;
};
} // namespace
// @tag integration
Void::Testing::Test internal_transition_stays_in_state()
{
Counter fsm;
fsm.start();
fsm.send(Tick{}, Tick{}, Tick{}); // handled internally, no re-entry
fsm.send(Stop{});
const auto outcome = fsm.wait();
Void::Testing::expect(outcome.has_value());
Void::Testing::expect_eq(*outcome, 3); // three internal ticks
Void::Testing::expect_eq(fsm.enters, 1); // entered Run exactly once
}