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
+458 -4

No files matched your search

+9
View File
@@ -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<bool> m_sleeping{false};
std::atomic<bool> m_done{false};
std::atomic<bool> m_paused{false};
std::atomic<bool> m_worker_started{false};
std::once_flag m_worker_once;
std::thread m_worker;
+148
View File
@@ -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 <typename S> [[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<Recovery>(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 <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 ───────────────────────────────────────────
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 ────────────────────────────────────────────────────
template <typename E> 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 <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()
{
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<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});
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<R> dispatch).
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