FSM v2 (B): timers, await_event_for, reactive/declarative states + guards

Engine: ExecutionContext gains a timer set (add_timer/cancel_timer); the
worker parks with try_acquire_until(earliest deadline) instead of a bare
acquire, and fires due timers in pump()/run_loop. The event mailbox waiter
is now multi-type (await any of N event types) and carries an optional
timeout — deliver() matches a waiting state directly (event needn't sit in
a buffer) and cancels the paired timer; the timer's fire resumes the
waiter with timed_out set. Single consumer still owns all mailbox/timer
state, so it stays lock-free for state code.

Machine:
- await_event_for<E>(duration) -> std::optional<E> (nullopt on timeout);
  await_any_event(types, deadline) for reactive states; existing
  await_event<E> rebuilt on the multi-type API.
- Reactive state base: instead of run(), a state overrides
  transitions(TransitionBuilder&) declaratively —
  on.event<E>().guard(fn).action(fn).to<S>() / .finish(v) / .fail(msg),
  and on.after(d).to<S>()/.fail(). The framework-provided run() builds the
  table once and loops: await any declared event or the timeout, evaluate
  matching entries in declaration order, check guard, run action,
  transition. Guards = bool(Derived&, const E&), actions sync or
  Coro::Task<void>. to<S>() static-asserts S in States<>. Reactive and
  imperative State subclasses mix freely in one machine.

8 new tests (Reactive): guarded reactive state + action ordering mixed
with an imperative terminal; await_event_for timeout vs event; reactive
after().to<> firing vs event beating the deadline. 973 green, ASan+UBSan
clean, timer tests stable across 12 runs, -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 01:11:53 +03:00
1 parent e941a48007
commit 422a7705c5
4 files changed
+682 -32

No files matched your search

+58 -6
View File
@@ -7,15 +7,22 @@
#include <any>
#include <atomic>
#include <chrono>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <map>
#include <mutex>
#include <optional>
#include <semaphore>
#include <span>
#include <thread>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <vector>
namespace Void::Fsm::Detail
{
@@ -79,10 +86,29 @@ namespace Void::Fsm::Detail
// Mailbox ops — consumer thread only (called from awaiters that
// run on the executor, and from the worker drain).
[[nodiscard]] bool try_take(const std::type_info& type,
std::any& out);
void set_waiter(const std::type_info& type,
std::coroutine_handle<> cont, std::any* slot);
using TimerId = std::uint64_t;
/// Pop the oldest buffered event whose type is in `types`.
[[nodiscard]] bool
try_take_any(std::span<const std::type_info* const> types,
EventEnvelope& out);
/// Suspend until an event of one of `types` arrives, or (if
/// `deadline` is set) the deadline passes. `slot` receives the
/// matched event; `*timed_out` is set true on timeout.
void set_waiter(
std::span<const std::type_info* const> types,
std::coroutine_handle<> cont, EventEnvelope* slot,
bool* timed_out,
std::optional<std::chrono::steady_clock::time_point> deadline);
/// Schedule `on_fire` at `deadline`. Returns an id for
/// cancel_timer.
TimerId add_timer(std::chrono::steady_clock::time_point deadline,
std::function<void()>
on_fire);
void cancel_timer(TimerId id);
// ── worker lifecycle ─────────────────────────────────────────
/// Spawn the worker thread (idempotent).
@@ -108,18 +134,44 @@ namespace Void::Fsm::Detail
void deliver(EventEnvelope& env);
void run_loop();
void wake() noexcept;
void fire_due_timers();
[[nodiscard]] std::optional<std::chrono::steady_clock::time_point>
next_deadline() const;
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::unordered_map<std::type_index, std::deque<std::any>> m_buffers;
struct Waiter {
const std::type_info* type{nullptr};
std::vector<const std::type_info*> types;
std::coroutine_handle<> cont{};
std::any* slot{nullptr};
EventEnvelope* slot{nullptr};
bool* timed_out{nullptr};
TimerId timer{0};
[[nodiscard]] bool active() const noexcept
{
return static_cast<bool>(cont);
}
[[nodiscard]] bool wants(const std::type_info& t) const
{
for (const auto* ty : types) {
if (*ty == t) {
return true;
}
}
return false;
}
};
Waiter m_waiter;
struct Timer {
std::chrono::steady_clock::time_point deadline;
std::function<void()> on_fire;
};
std::map<TimerId, Timer> m_timers;
TimerId m_next_timer{1};
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_done{false};
+353 -5
View File
@@ -9,7 +9,9 @@
#include <Void/Service/Registry.hpp>
#include <any>
#include <array>
#include <atomic>
#include <chrono>
#include <coroutine>
#include <cstdint>
#include <expected>
@@ -155,6 +157,14 @@ namespace Void::Fsm
return m_machine->template await_event<E>();
}
/// Await E or time out (nullopt on timeout).
template <typename E, typename Rep, typename Period>
[[nodiscard]] auto await_event_for(
std::chrono::duration<Rep, Period> d) const
{
return m_machine->template await_event_for<E>(d);
}
template <typename Sub, typename... Args>
[[nodiscard]] auto run_child(Args&&... args) const
{
@@ -173,6 +183,258 @@ namespace Void::Fsm
Machine* m_machine{nullptr};
};
// ── reactive (declarative) states ─────────────────────────────
//
// A reactive state declares a transition table instead of an
// imperative run(): it waits for the declared events (or a
// timeout), checks guards in order, runs actions, and
// transitions. Mix freely with imperative State subclasses.
//
// struct Idle : Reactive {
// void transitions(TransitionBuilder& on) override {
// on.event<Go>().guard([](Idle& s, const Go& g){...})
// .action([](Idle& s, const Go&){...})
// .to<Running>();
// on.event<Stop>().to<Done>();
// on.after(5s).to<TimedOut>();
// }
// };
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;
std::string target_name; // for introspection
};
struct TransitionTable {
std::vector<EventEntry> events;
bool has_timeout{false};
std::chrono::steady_clock::duration timeout_after{};
Step timeout_step;
};
template <typename E> class EventClause
{
public:
explicit EventClause(TransitionTable& table)
: m_table(&table)
{
}
EventClause&
guard(std::function<bool(Derived&, const E&)> g)
{
m_guard = std::move(g);
return *this;
}
EventClause& action(
std::function<Coro::Task<void>(Derived&, const E&)> a)
{
m_action = std::move(a);
return *this;
}
EventClause&
action(std::function<void(Derived&, const E&)> a)
{
m_action =
[a = std::move(a)](Derived& d,
const E& e) -> Coro::Task<void> {
a(d, e);
co_return;
};
return *this;
}
template <typename S> void to()
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Derived::States::template contains<S>(),
"to<S>: S is not in this machine's "
"States<...> list");
}
commit(Step::transition(typeid(S)),
Machine::template state_type_name<S>());
}
void finish()
requires std::is_void_v<ResultT>
{
commit(Step::success(std::any{}), "(success)");
}
template <typename V>
void finish(V&& value)
requires(!std::is_void_v<ResultT>)
{
commit(Step::success(
std::any{ResultT(std::forward<V>(value))}),
"(success)");
}
void fail(std::string message)
{
commit(Step::failure(FsmError{std::move(message)}),
"(fail)");
}
private:
void commit(Step step, std::string target)
{
EventEntry entry;
entry.type = &typeid(E);
if (m_guard) {
entry.guard = [g = std::move(m_guard)](
Derived& d, const std::any& a) {
return g(d, std::any_cast<const E&>(a));
};
}
if (m_action) {
entry.action =
[a = std::move(m_action)](
Derived& d,
const std::any& any) -> Coro::Task<void> {
co_await a(d, std::any_cast<const E&>(any));
};
}
entry.step = std::move(step);
entry.target_name = std::move(target);
m_table->events.push_back(std::move(entry));
}
TransitionTable* m_table;
std::function<bool(Derived&, const E&)> m_guard;
std::function<Coro::Task<void>(Derived&, const E&)>
m_action;
};
class AfterClause
{
public:
AfterClause(TransitionTable& table,
std::chrono::steady_clock::duration after)
: m_table(&table), m_after(after)
{
}
template <typename S> void to()
{
if constexpr (requires { typename Derived::States; }) {
static_assert(
Derived::States::template contains<S>(),
"after().to<S>: S not in States<...>");
}
m_table->has_timeout = true;
m_table->timeout_after = m_after;
m_table->timeout_step = Step::transition(typeid(S));
}
void fail(std::string message)
{
m_table->has_timeout = true;
m_table->timeout_after = m_after;
m_table->timeout_step =
Step::failure(FsmError{std::move(message)});
}
private:
TransitionTable* m_table;
std::chrono::steady_clock::duration m_after;
};
class TransitionBuilder
{
public:
explicit TransitionBuilder(TransitionTable& table)
: m_table(&table)
{
}
template <typename E> [[nodiscard]] EventClause<E> event()
{
return EventClause<E>{*m_table};
}
template <typename Rep, typename Period>
[[nodiscard]] AfterClause
after(std::chrono::duration<Rep, Period> d)
{
return AfterClause{
*m_table,
std::chrono::duration_cast<
std::chrono::steady_clock::duration>(d)};
}
private:
TransitionTable* m_table;
};
class Reactive : public State
{
public:
[[nodiscard]] Detail::StateKind
kind() const noexcept override
{
return Detail::StateKind::Reactive;
}
/// Declare this state's event/timeout transitions.
virtual void transitions(TransitionBuilder& on) = 0;
Coro::Task<Step> run() final
{
TransitionTable table;
{
TransitionBuilder builder{table};
transitions(builder);
}
std::vector<const std::type_info*> types;
types.reserve(table.events.size());
for (const auto& e : table.events) {
types.push_back(e.type);
}
for (;;) {
std::optional<std::chrono::steady_clock::time_point>
deadline;
if (table.has_timeout) {
deadline = std::chrono::steady_clock::now() +
table.timeout_after;
}
auto ev = co_await this->machine().await_any_event(
types, deadline);
if (!ev) {
co_return std::move(table.timeout_step);
}
Derived& d = this->self();
bool matched = false;
for (auto& e : table.events) {
if (*e.type != *ev->type) {
continue;
}
if (e.guard && !e.guard(d, ev->value)) {
continue;
}
if (e.action) {
co_await e.action(d, ev->value);
}
co_return std::move(e.step);
}
(void)matched; // unmatched event is dropped
}
}
};
// ── construction ──────────────────────────────────────────────
explicit Machine(Options options = {}) : m_options(options)
{
@@ -323,22 +585,98 @@ namespace Void::Fsm
{
struct Awaiter {
Detail::ExecutionContext* ctx;
std::any slot;
std::array<const std::type_info*, 1> types;
Detail::EventEnvelope env;
[[nodiscard]] bool await_ready()
{
return ctx->try_take(typeid(E), slot);
return ctx->try_take_any(types, env);
}
void await_suspend(std::coroutine_handle<> h)
{
ctx->set_waiter(typeid(E), h, &slot);
ctx->set_waiter(types, h, &env, nullptr,
std::nullopt);
}
[[nodiscard]] E await_resume()
{
return std::any_cast<E>(std::move(slot));
return std::any_cast<E>(std::move(env.value));
}
};
return Awaiter{m_ctx.get(), {}};
return Awaiter{m_ctx.get(), {&typeid(E)}, {}};
}
/// Await an event of type E or time out after `duration`;
/// returns std::nullopt on timeout.
template <typename E, typename Rep, typename Period>
[[nodiscard]] auto
await_event_for(std::chrono::duration<Rep, Period> duration)
{
struct Awaiter {
Detail::ExecutionContext* ctx;
std::array<const std::type_info*, 1> types;
Detail::EventEnvelope env;
bool timed_out{false};
std::chrono::steady_clock::time_point deadline;
[[nodiscard]] bool await_ready()
{
return ctx->try_take_any(types, env);
}
void await_suspend(std::coroutine_handle<> h)
{
ctx->set_waiter(types, h, &env, &timed_out,
deadline);
}
[[nodiscard]] std::optional<E> await_resume()
{
if (timed_out) {
return std::nullopt;
}
return std::any_cast<E>(std::move(env.value));
}
};
return Awaiter{m_ctx.get(),
{&typeid(E)},
{},
false,
std::chrono::steady_clock::now() + duration};
}
/// Await any of several event types (optional deadline); used
/// by reactive states. Returns the matched envelope or nullopt
/// on timeout.
[[nodiscard]] auto await_any_event(
std::vector<const std::type_info*> types,
std::optional<std::chrono::steady_clock::time_point> deadline)
{
struct Awaiter {
Detail::ExecutionContext* ctx;
std::vector<const std::type_info*> types;
Detail::EventEnvelope env;
bool timed_out{false};
std::optional<std::chrono::steady_clock::time_point>
deadline;
[[nodiscard]] bool await_ready()
{
return ctx->try_take_any(types, env);
}
void await_suspend(std::coroutine_handle<> h)
{
ctx->set_waiter(types, h, &env, &timed_out,
deadline);
}
[[nodiscard]] std::optional<Detail::EventEnvelope>
await_resume()
{
if (timed_out) {
return std::nullopt;
}
return std::move(env);
}
};
return Awaiter{
m_ctx.get(), std::move(types), {}, false, deadline};
}
// ── nesting ───────────────────────────────────────────────────
@@ -459,6 +797,16 @@ namespace Void::Fsm
return nullptr;
}
template <typename S>
[[nodiscard]] static std::string state_type_name()
{
#ifdef VOID_HAS_FSM_REFLECTION
return std::string{std::meta::identifier_of(^^S)};
#else
return typeid(S).name();
#endif
}
template <typename S> [[nodiscard]] std::string state_name()
{
#ifdef VOID_HAS_FSM_REFLECTION