feat(fsm): structured scopes, race-loser join, boundary checkpoints, and bounded supervision

This commit is contained in:
faumaray committed 2026-11-26 16:51:35 +03:00
1 parent 1dc51d5c43
commit ef5312c4b3
11 files changed
+3819 -541

No files matched your search

+141 -54
View File
@@ -4,6 +4,8 @@
#include <Void/Async/MpscQueue.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Fsm/StateKey.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <any>
#include <atomic>
@@ -14,6 +16,7 @@
#include <deque>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <semaphore>
@@ -28,17 +31,14 @@ namespace Void::Fsm::Detail
{
/// Type-erased state. Concrete states derive the single Machine<Derived>::
/// State base; the engine drives each via a signature-inferred per-state
/// thunk (entry / reactive table / continuation handlers).
/// thunk (entry / continuation handlers).
class StateBase
{
public:
virtual ~StateBase() = default;
/// Optional entry/exit lifecycle hooks (default no-ops). The
/// state's behaviour (entry / reactive table / continuation
/// handlers) is discovered by signature via a per-state driver
/// thunk — there is no virtual run().
/// Optional entry/exit lifecycle hooks (default no-ops).
virtual Coro::Task<void> on_enter();
virtual Coro::Task<void> on_exit();
};
@@ -46,18 +46,28 @@ namespace Void::Fsm::Detail
struct EventEnvelope {
const std::type_info* type{nullptr};
std::any value;
std::size_t bytes{0};
};
/// Shared execution substrate for a machine and any machines it nests:
/// one executor + one worker thread + one typed event mailbox. A single
/// consumer (the worker, or the embedder via pump()) touches all
/// mailbox state, so state code runs lock-free and single-threaded;
/// cross-thread post() only enqueues.
/// one logical strand (owned worker, embedder pump(), or borrowed external
/// executor) + bounded event mailbox + reserved control lane + Clock-driven
/// timers. Cross-thread posts enqueue owned envelopes; only the active
/// consumer strand touches waiter/timer/buffer tables.
class ExecutionContext
: public std::enable_shared_from_this<ExecutionContext>
{
public:
ExecutionContext() = default;
using TimerId = std::uint64_t;
using WaiterId = std::uint64_t;
using ScopeId = std::uint64_t;
static constexpr ScopeId kNoScope = 0;
explicit ExecutionContext(
const Time::MonotonicClock* clock = nullptr,
FsmLimits limits = {},
Async::Executor* external_executor = nullptr);
~ExecutionContext();
ExecutionContext(const ExecutionContext&) = delete;
@@ -67,14 +77,61 @@ namespace Void::Fsm::Detail
{
return m_executor;
}
[[nodiscard]] Async::Executor& active_executor() noexcept
{
return m_external_executor != nullptr
? *m_external_executor
: static_cast<Async::Executor&>(m_executor);
}
[[nodiscard]] const Time::MonotonicClock& clock() const noexcept
{
return *m_clock;
}
[[nodiscard]] const FsmLimits& limits() const noexcept
{
return m_limits;
}
[[nodiscard]] std::uint64_t dispatch_turn() const noexcept
{
return m_dispatch_turn;
}
[[nodiscard]] std::size_t last_turn_events() const noexcept
{
return m_last_turn_events;
}
[[nodiscard]] std::size_t queued_events() const noexcept
{
return m_queued_events.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t queued_bytes() const noexcept
{
return m_queued_bytes.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t active_child_regions() const noexcept
{
return m_active_child_regions.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t timer_count() const noexcept
{
return m_timers.size();
}
// ── events (post is the only cross-thread entry point) ────────
[[nodiscard]] bool
try_acquire_child_regions(std::size_t count) noexcept;
void release_child_regions(std::size_t count) noexcept;
// ── events & control (thread-safe entry points) ──────────────
[[nodiscard]] Void::Result::Result<void>
try_post(EventEnvelope env);
void post(EventEnvelope env);
[[nodiscard]] Void::Result::Result<void>
try_post_control(std::function<void()> fn);
// Mailbox ops — consumer thread only (called from awaiters that
// run on the executor, and from the worker drain).
using TimerId = std::uint64_t;
// ── strand-only scope/waiter/timer APIs ──────────────────────
[[nodiscard]] ScopeId allocate_scope() noexcept
{
return m_next_scope.fetch_add(1, std::memory_order_relaxed);
}
/// Pop the oldest buffered event whose type is in `types`.
[[nodiscard]] bool
@@ -82,68 +139,66 @@ namespace Void::Fsm::Detail
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(
/// `deadline` is set) the deadline passes, or the waiter/scope is
/// cancelled.
WaiterId 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);
std::optional<Time::MonotonicClock::time_point> deadline,
ScopeId scope = kNoScope, bool* cancelled = nullptr);
/// 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_waiter(WaiterId id);
void cancel_scope(ScopeId scope);
void purge_scope(ScopeId scope);
void drain_control_queue();
/// Schedule `on_fire` at `deadline` (enforces max_timers).
[[nodiscard]] Void::Result::Result<TimerId>
try_add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope = kNoScope);
TimerId add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope = kNoScope);
void cancel_timer(TimerId id);
// ── worker lifecycle ─────────────────────────────────────────
/// Spawn the worker thread (idempotent).
// ── worker / pump lifecycle ──────────────────────────────────
void start_worker();
/// Mark finished and wake the worker so it can exit.
void finish();
/// Stop and join the worker.
void stop();
/// Join the worker without forcing finish (waits for the
/// driver to finish() on its own).
void join();
[[nodiscard]] bool finished() const noexcept
{
return m_done.load(std::memory_order_acquire);
}
/// Embedder-driven step: deliver queued events + run ready
/// coroutines. Returns work done count. Single consumer only.
/// A no-op (returns 0) while paused.
/// Embedder-driven step: drain control lane, fire due timers on
/// injected clock, deliver up to max_events_per_turn /
/// max_turn_duration user events, and drain internal executor.
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);
/// Called on external executor threads via scheduled task.
void run_external_pump_step();
/// Wake the consumer (e.g. to re-check an external jump request).
void set_paused(bool paused);
void nudge() { wake(); }
private:
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;
struct BufferedEvent {
std::any value;
std::size_t bytes{0};
};
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::unordered_map<std::type_index, std::deque<std::any>> m_buffers;
using WaiterId = std::uint64_t;
struct Waiter {
WaiterId id{0};
ScopeId scope{kNoScope};
std::vector<const std::type_info*> types;
std::coroutine_handle<> cont{};
EventEnvelope* slot{nullptr};
bool* timed_out{nullptr};
bool* cancelled{nullptr};
TimerId timer{0};
[[nodiscard]] bool wants(const std::type_info& t) const
@@ -156,20 +211,52 @@ namespace Void::Fsm::Detail
return false;
}
};
// Several waiters can be parked at once (parallel regions, deferred
// events). An event resumes the first (FIFO) that wants its type.
struct Timer {
Time::MonotonicClock::time_point deadline;
std::function<void()> on_fire;
ScopeId scope{kNoScope};
};
void deliver(EventEnvelope& env);
void run_loop();
void wake() noexcept;
void schedule_external_pump() noexcept;
void fire_due_timers();
[[nodiscard]] std::optional<Time::MonotonicClock::time_point>
next_deadline() const;
const Time::MonotonicClock* m_clock;
FsmLimits m_limits;
Async::Executor* m_external_executor{nullptr};
Async::ManualExecutor m_executor;
Async::MpscQueue<EventEnvelope> m_queue;
std::atomic<std::size_t> m_queued_events{0};
std::atomic<std::size_t> m_queued_bytes{0};
Async::MpscQueue<std::function<void()>> m_control_queue;
std::atomic<std::size_t> m_queued_control{0};
std::unordered_map<std::type_index, std::deque<BufferedEvent>>
m_buffers;
std::size_t m_buffered_events{0};
std::size_t m_buffered_bytes{0};
std::vector<Waiter> m_waiters;
WaiterId m_next_waiter{1};
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::atomic<ScopeId> m_next_scope{1};
std::atomic<std::size_t> m_active_child_regions{0};
std::uint64_t m_dispatch_turn{0};
std::size_t m_last_turn_events{0};
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_pump_scheduled{false};
std::atomic<bool> m_done{false};
std::atomic<bool> m_paused{false};
std::atomic<bool> m_worker_started{false};