From 7c7c590d79624ef785a861b56cd983efab871f72 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 14 Jun 2026 15:44:19 +0300 Subject: [PATCH] =?UTF-8?q?FSM=20(3):=20direct=20control=20=E2=80=94=20flu?= =?UTF-8?q?ent=20events,=20free=20jumps,=20lifecycle,=20mutation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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() reaches any registered state with no declared transition ("each state can be moved to another state"); external jump() 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() 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() (re-packs indices, fixes the initial), set_initial(), replace(). 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 --- CLAUDE.md | 3 + include/Void/Fsm/Detail/Engine.hpp | 9 + include/Void/Fsm/Machine.hpp | 148 +++++++++++++++ src/Fsm/Engine.cpp | 24 ++- tests/standalone/Fsm/Direct.cpp | 278 +++++++++++++++++++++++++++++ 5 files changed, 458 insertions(+), 4 deletions(-) create mode 100644 tests/standalone/Fsm/Direct.cpp diff --git a/CLAUDE.md b/CLAUDE.md index ffca48b..00a0be8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -149,12 +149,15 @@ Other key points: `Void::Fsm::Machine` — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task run()` returning `next()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves. +Header layout (include `` — a thin umbrella): `Machine.hpp` (the `Machine` 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` templates, aliased by `Machine::Reactive`); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Continuation.hpp` (`Detail::Continuation` = `Continue`, 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()`). + - **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()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post(e)` is lock-free from any thread. - **Nesting**: `co_await run_child(args...)` runs a child on the *same* executor (shared events + services) and yields its `Outcome` (`std::expected`) — the imperative form, branch on it yourself. - **Sub-machine continuations (declarative)**: `co_return startMachine(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` and the engine dispatches to `on_success(R)` or `on_failure(FsmError)` by the outcome (a `Continue` takes a nullary `on_success()`). `Next` must derive `Continue` (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`) dispatches — a plain state entered with a pending result just `run()`s. - **Composite sub-states (hierarchy)**: `co_await run_region()` 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() : next()`). Parent-level multi-event handling via `co_await await_any()` → `std::variant` (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()` / `add_if(cond)`; `next` fails; `has_state()` lets a state branch. +- **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). - **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. diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp index d39fb66..2e4b465 100644 --- a/include/Void/Fsm/Detail/Engine.hpp +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -132,8 +132,16 @@ namespace Void::Fsm::Detail /// Embedder-driven step: deliver queued events + run ready /// coroutines. Returns work done count. Single consumer only. + /// A no-op (returns 0) while paused. 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: void deliver(EventEnvelope& env); @@ -180,6 +188,7 @@ namespace Void::Fsm::Detail std::counting_semaphore<> m_wakeup{0}; std::atomic m_sleeping{false}; std::atomic m_done{false}; + std::atomic m_paused{false}; std::atomic m_worker_started{false}; std::once_flag m_worker_once; std::thread m_worker; diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index cff5999..48cbf50 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -136,6 +136,16 @@ namespace Void::Fsm 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 [[nodiscard]] Step goto_state() const + { + return Step::transition(typeid(S)); + } + /// Route to a fallback state if `step` is a failure, /// otherwise pass it through — for error policies: /// co_return next_or(co_await try_work()); @@ -433,6 +443,62 @@ namespace Void::Fsm return m_factories.contains(std::type_index{typeid(S)}); } + /// Make `S` the initial state (registers it if needed). Idle-only. + template void set_initial() + { + if (m_status.load() != Status::Idle) { + return; + } + add(); + 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 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(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 void replace() + { + if (m_status.load() != Status::Idle) { + return; + } + const bool was_initial = (m_initial == &typeid(S)); + remove(); + add(); + if (was_initial) { + m_initial = &typeid(T); + } + } + // ── service context ─────────────────────────────────────────── 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 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 ──────────────────────────────────────────────────── template void post(E event) { @@ -535,6 +653,25 @@ namespace Void::Fsm 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 void send(Es&&... events) + { + (post(std::forward(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 void jump() + { + m_jump.store(&typeid(S), std::memory_order_release); + if (m_ctx) { + m_ctx->nudge(); + } + } + template [[nodiscard]] auto await_event() { return Detail::make_event_awaiter( @@ -912,6 +1049,13 @@ namespace Void::Fsm co_return std::unexpected{FsmError{"no initial state"}}; } for (;;) { + // Apply an external jump() 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}); if (it == m_factories.end()) { co_return std::unexpected{ @@ -1005,6 +1149,10 @@ namespace Void::Fsm // Set by a Launch step's sub-machine result; consumed by the next // state's resume() (a Continue dispatch). std::optional m_pending_result; + + // External jump request (jump()); applied by drive() at the + // next transition boundary. + std::atomic m_jump{nullptr}; }; } // namespace Void::Fsm diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp index 11fe93a..216c707 100644 --- a/src/Fsm/Engine.cpp +++ b/src/Fsm/Engine.cpp @@ -136,8 +136,17 @@ namespace Void::Fsm::Detail 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() { + if (m_paused.load(std::memory_order_acquire)) { + return 0; + } std::size_t work = 0; fire_due_timers(); while (auto env = m_queue.try_pop()) { @@ -192,17 +201,24 @@ namespace Void::Fsm::Detail void ExecutionContext::run_loop() { for (;;) { - pump(); + const bool paused = m_paused.load(std::memory_order_acquire); + if (!paused) { + pump(); + } if (m_done.load(std::memory_order_acquire)) { return; } 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); continue; } - // Park until woken, or until the earliest timer is due. - if (const auto deadline = next_deadline(); deadline.has_value()) { + // Park until woken (post/resume/finish), or — when running — until + // 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); } else { m_wakeup.acquire(); diff --git a/tests/standalone/Fsm/Direct.cpp b/tests/standalone/Fsm/Direct.cpp new file mode 100644 index 0000000..cf80f3a --- /dev/null +++ b/tests/standalone/Fsm/Direct.cpp @@ -0,0 +1,278 @@ +#include +#include +#include + +#include +#include + +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 + { + public: + + int total = 0; + + struct Take : State { + Task run() override + { + auto a = co_await await_event(); + self().total += a.n; + auto b = co_await await_event(); + self().total += b.n; + co_return succeed(self().total); + } + }; + using States = Fsm::States; + }; +} // 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() jumps + // from A to C freely. + class Hop : public Fsm::Machine + { + public: + + struct A : State { + Task run() override { co_return goto_state(); } + }; + struct B : State { + Task run() override { co_return succeed(1); } + }; + struct C : State { + Task run() override { co_return succeed(3); } + }; + using States = Fsm::States; + }; +} // 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() redirects at the + // next boundary. + class Jumper : public Fsm::Machine + { + public: + + struct Loop : State { + Task run() override + { + co_await await_event(); + co_return next(); + } + }; + struct Done : State { + Task run() override { co_return succeed(99); } + }; + using States = Fsm::States; + + explicit Jumper(MachineOptions o = {}) + : Fsm::Machine(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 -> park again + + fsm.jump(); // 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 + { + public: + + int runs = 0; + + struct Once : State { + Task run() override + { + co_return succeed(++self().runs); + } + }; + using States = Fsm::States; + }; +} // 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 + { + public: + + struct A : State { + Task run() override { co_return succeed(1); } + }; + struct B : State { + Task run() override { co_return succeed(2); } + }; + using States = Fsm::States; // 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(); + const auto second = fsm.wait(); + Void::Testing::expect_eq(*second, 2); // B +} + +// ── runtime mutation (Idle only) ──────────────────────────────────────────── + +namespace +{ + class Mut : public Fsm::Machine + { + public: + + struct A : State { + Task run() override { co_return succeed(1); } + }; + struct B : State { + Task run() override { co_return succeed(2); } + }; + struct C : State { + Task run() override { co_return succeed(3); } + }; + // Not in States<> — added via replace<>. + struct Extra : State { + Task run() override { co_return succeed(7); } + }; + using States = Fsm::States; + }; +} // namespace + +Void::Testing::Test remove_and_set_initial_before_start() +{ + Mut fsm; + Void::Testing::expect(fsm.has_state()); + fsm.remove(); + Void::Testing::expect(!fsm.has_state()); + Void::Testing::expect_eq(fsm.describe().size(), std::size_t{2}); + + fsm.set_initial(); + 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(); // A was initial -> Extra becomes initial + Void::Testing::expect(!fsm.has_state()); + Void::Testing::expect(fsm.has_state()); + const auto outcome = fsm.run_blocking(); + Void::Testing::expect_eq(*outcome, 7); +} + +// ── pause / resume ────────────────────────────────────────────────────────── + +namespace +{ + struct Go { + }; + + class Sleeper : public Fsm::Machine + { + public: + + struct W : State { + Task run() override + { + co_await await_event(); + co_return succeed(5); + } + }; + using States = Fsm::States; + }; +} // 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); +}