From 4af3ee6d0c78e69e57b0740149034f2741a6c5b0 Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 15 Jun 2026 02:48:27 +0300 Subject: [PATCH] =?UTF-8?q?FSM=20(8):=20deferred=20events=20+=20richer=20r?= =?UTF-8?q?eactive=20DSL=20=E2=80=94=20completes=20the=20upgrade?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final phase of the FSM upgrade. Extends the reactive transition DSL: - Deferred events: on.defer() 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().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 --- CLAUDE.md | 1 + include/Void/Fsm/Detail/Reactive.hpp | 50 ++++++++++- include/Void/Fsm/Detail/Roles.hpp | 44 +++++++++- include/Void/Fsm/Machine.hpp | 9 ++ tests/standalone/Fsm/Defer.cpp | 119 +++++++++++++++++++++++++++ 5 files changed, 216 insertions(+), 7 deletions(-) create mode 100644 tests/standalone/Fsm/Defer.cpp diff --git a/CLAUDE.md b/CLAUDE.md index 3113d1f..a34b47b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -170,6 +170,7 @@ Header layout (include `` — a thin umbrella): `Machine.hpp` - **Direct control**: fluent `send(e1, e2, …)` (variadic `post`); free in-state jumps via `goto_state()` (any registered state, no declared transition); external `jump()` applied at the next transition boundary (race-safe, non-preemptive — a running state isn't interrupted); lifecycle `reset()` / `restart()` / `restart_at()` and `pause()` / `resume()` (paused = worker stops draining, posted events buffer); Idle-only mutation `remove()` / `set_initial()` / `replace()`. - **Services**: `set_services(registry)`; `state.service()` 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()` 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().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` sub-step), `next_or(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). diff --git a/include/Void/Fsm/Detail/Reactive.hpp b/include/Void/Fsm/Detail/Reactive.hpp index de63090..0d9dc90 100644 --- a/include/Void/Fsm/Detail/Reactive.hpp +++ b/include/Void/Fsm/Detail/Reactive.hpp @@ -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 struct EventEntry { const std::type_info* type{nullptr}; std::function guard; std::function(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 struct TransitionTable { std::vector> 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 deferred; + // Entry/exit actions (run by the reactive loop around the state). + std::function(Derived&)> enter_action; + std::function(Derived&)> exit_action; }; /// Fluent builder for one event row: `on.event().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 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 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(); 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 void defer() + { + m_table->deferred.push_back(&typeid(E)); + } + + /// Entry action — run when the state is entered (before it waits). + void enter(std::function fn) + { + m_table->enter_action = + [fn = std::move(fn)](Derived& d) -> Coro::Task { + fn(d); + co_return; + }; + } + /// Exit action — run when the state is left (on any transition). + void exit(std::function fn) + { + m_table->exit_action = + [fn = std::move(fn)](Derived& d) -> Coro::Task { + fn(d); + co_return; + }; + } + private: TransitionTable* m_table; diff --git a/include/Void/Fsm/Detail/Roles.hpp b/include/Void/Fsm/Detail/Roles.hpp index 0e86439..cc5fea9 100644 --- a/include/Void/Fsm/Detail/Roles.hpp +++ b/include/Void/Fsm/Detail/Roles.hpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -234,11 +235,31 @@ namespace Void::Fsm using D = MachineOf; TransitionTable 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 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 held; + auto leave = [&](Step step) -> Coro::Task { + 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 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)); + } } } } diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index 99b269c..9f28c90 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -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 void send(Es&&... events) diff --git a/tests/standalone/Fsm/Defer.cpp b/tests/standalone/Fsm/Defer.cpp new file mode 100644 index 0000000..ab53edc --- /dev/null +++ b/tests/standalone/Fsm/Defer.cpp @@ -0,0 +1,119 @@ +#include +#include +#include + +#include +#include + +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 + { + public: + + using Success = int; + std::vector 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(); + on.template event().template to(); + } + }; + struct Idle : State { + void transitions(TransitionBuilder& on) + { + on.template event() + .action([](Flow& m, const Click&) { + m.log.push_back("click"); + }) + .template to(); + } + }; + struct End : State { + Task run() { co_return succeed(1); } + }; + using States = Fsm::States; + }; +} // 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 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 + { + 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().internal( + [](Counter& m, const Tick&) { ++m.ticks; }); + on.template event().template to(); + } + }; + struct Done : State { + Task run() { co_return succeed(self().ticks); } + }; + using States = Fsm::States; + }; +} // 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 +}