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

+361 -40
View File
@@ -1,22 +1,152 @@
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <utility>
namespace Void::Fsm::Detail
{
namespace
{
Coro::Task<void> external_pump_task(
std::weak_ptr<ExecutionContext> weak_ctx)
{
if (auto ctx = weak_ctx.lock()) {
ctx->run_external_pump_step();
}
co_return;
}
} // namespace
// Default state lifecycle hooks (no-ops). The state's behaviour is driven
// by a per-state, signature-inferred thunk built at registration.
Coro::Task<void> StateBase::on_enter() { co_return; }
Coro::Task<void> StateBase::on_exit() { co_return; }
ExecutionContext::ExecutionContext(const Time::MonotonicClock* clock,
FsmLimits limits,
Async::Executor* external_executor)
: m_clock(clock != nullptr ? clock
: &Time::SystemMonotonicClock::instance()),
m_limits(limits), m_external_executor(external_executor)
{
}
ExecutionContext::~ExecutionContext() { stop(); }
bool ExecutionContext::try_acquire_child_regions(std::size_t count) noexcept
{
if (count == 0) {
return true;
}
std::size_t cur =
m_active_child_regions.load(std::memory_order_acquire);
for (;;) {
if (count > m_limits.max_child_regions ||
cur > m_limits.max_child_regions - count) {
return false;
}
if (m_active_child_regions.compare_exchange_weak(
cur, cur + count, std::memory_order_acq_rel,
std::memory_order_acquire)) {
return true;
}
}
}
void ExecutionContext::release_child_regions(std::size_t count) noexcept
{
if (count == 0) {
return;
}
m_active_child_regions.fetch_sub(count, std::memory_order_acq_rel);
}
Void::Result::Result<void> ExecutionContext::try_post(EventEnvelope env)
{
if (m_done.load(std::memory_order_acquire)) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"ExecutionContext::try_post: context stopped"));
}
const std::size_t bytes = env.bytes;
std::size_t cur_ev = m_queued_events.load(std::memory_order_acquire);
for (;;) {
if (m_limits.max_mailbox_events > 0 &&
cur_ev >= m_limits.max_mailbox_events) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::overloaded,
"ExecutionContext::try_post: mailbox event limit reached"));
}
if (m_queued_events.compare_exchange_weak(
cur_ev, cur_ev + 1, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
std::size_t cur_bytes = m_queued_bytes.load(std::memory_order_acquire);
for (;;) {
if (m_limits.max_mailbox_bytes > 0 &&
(bytes > m_limits.max_mailbox_bytes ||
cur_bytes > m_limits.max_mailbox_bytes - bytes)) {
m_queued_events.fetch_sub(1, std::memory_order_acq_rel);
return Void::Result::fail(make_fsm_error(
FsmErrorCode::overloaded,
"ExecutionContext::try_post: mailbox byte limit reached"));
}
if (m_queued_bytes.compare_exchange_weak(
cur_bytes, cur_bytes + bytes, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
m_queue.push(std::move(env));
wake();
return {};
}
void ExecutionContext::post(EventEnvelope env)
{
m_queue.push(std::move(env));
auto r = try_post(std::move(env));
if (!r) {
Void::Log::warn("Fsm", "dropped user event: {}",
r.error().message());
}
}
Void::Result::Result<void>
ExecutionContext::try_post_control(std::function<void()> fn)
{
if (!fn) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_argument,
"ExecutionContext::try_post_control: empty callback"));
}
if (m_done.load(std::memory_order_acquire)) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::invalid_state,
"ExecutionContext::try_post_control: context stopped"));
}
std::size_t cur = m_queued_control.load(std::memory_order_acquire);
for (;;) {
if (m_limits.max_control_messages > 0 &&
cur >= m_limits.max_control_messages) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::overloaded,
"ExecutionContext::try_post_control: control lane limit reached"));
}
if (m_queued_control.compare_exchange_weak(
cur, cur + 1, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
m_control_queue.push(std::move(fn));
wake();
return {};
}
bool ExecutionContext::try_take_any(
@@ -26,57 +156,170 @@ namespace Void::Fsm::Detail
const auto it = m_buffers.find(std::type_index{*ty});
if (it != m_buffers.end() && !it->second.empty()) {
out.type = ty;
out.value = std::move(it->second.front());
out.bytes = it->second.front().bytes;
out.value = std::move(it->second.front().value);
it->second.pop_front();
if (m_buffered_events > 0) {
--m_buffered_events;
}
m_buffered_bytes -= std::min(m_buffered_bytes, out.bytes);
return true;
}
}
return false;
}
void ExecutionContext::set_waiter(
ExecutionContext::WaiterId ExecutionContext::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, bool* cancelled)
{
Waiter w;
w.id = m_next_waiter++;
w.scope = scope;
w.types.assign(types.begin(), types.end());
w.cont = cont;
w.slot = slot;
w.timed_out = timed_out;
w.cancelled = cancelled;
w.timer = 0;
if (deadline.has_value()) {
const WaiterId id = w.id;
w.timer = add_timer(*deadline, [this, id] {
// Timeout: resume that waiter (if still parked) with timed_out.
const auto it =
std::find_if(m_waiters.begin(), m_waiters.end(),
[id](const Waiter& x) { return x.id == id; });
if (it == m_waiters.end()) {
return;
auto timer_res = try_add_timer(
*deadline,
[this, id] {
const auto it = std::find_if(
m_waiters.begin(), m_waiters.end(),
[id](const Waiter& x) { return x.id == id; });
if (it == m_waiters.end()) {
return;
}
if (it->timed_out != nullptr) {
*it->timed_out = true;
}
auto cont2 = it->cont;
m_waiters.erase(it);
active_executor().post_completion(cont2);
},
scope);
if (timer_res) {
w.timer = *timer_res;
} else {
// Fail safe rather than hanging forever if timer table is
// saturated.
if (timed_out != nullptr) {
*timed_out = true;
}
if (it->timed_out != nullptr) {
*it->timed_out = true;
}
auto cont2 = it->cont;
m_waiters.erase(it);
m_executor.post(cont2);
});
active_executor().post_completion(cont);
return w.id;
}
}
m_waiters.push_back(std::move(w));
return m_waiters.back().id;
}
ExecutionContext::TimerId ExecutionContext::add_timer(
std::chrono::steady_clock::time_point deadline,
std::function<void()>
on_fire)
void ExecutionContext::cancel_waiter(WaiterId id)
{
const auto it =
std::find_if(m_waiters.begin(), m_waiters.end(),
[id](const Waiter& x) { return x.id == id; });
if (it == m_waiters.end()) {
return;
}
cancel_timer(it->timer);
if (it->cancelled != nullptr) {
*it->cancelled = true;
} else if (it->timed_out != nullptr) {
*it->timed_out = true;
}
auto cont = it->cont;
m_waiters.erase(it);
if (cont) {
active_executor().post_completion(cont);
}
}
void ExecutionContext::cancel_scope(ScopeId scope)
{
if (scope == kNoScope) {
return;
}
std::vector<std::coroutine_handle<>> to_resume;
for (auto it = m_waiters.begin(); it != m_waiters.end();) {
if (it->scope == scope) {
cancel_timer(it->timer);
if (it->cancelled != nullptr) {
*it->cancelled = true;
} else if (it->timed_out != nullptr) {
*it->timed_out = true;
}
if (it->cont) {
to_resume.push_back(it->cont);
}
it = m_waiters.erase(it);
} else {
++it;
}
}
for (auto it = m_timers.begin(); it != m_timers.end();) {
if (it->second.scope == scope) {
it = m_timers.erase(it);
} else {
++it;
}
}
for (auto h : to_resume) {
active_executor().post_completion(h);
}
}
void ExecutionContext::purge_scope(ScopeId scope)
{
if (scope == kNoScope) {
return;
}
for (auto it = m_waiters.begin(); it != m_waiters.end();) {
if (it->scope == scope) {
cancel_timer(it->timer);
it = m_waiters.erase(it);
} else {
++it;
}
}
for (auto it = m_timers.begin(); it != m_timers.end();) {
if (it->second.scope == scope) {
it = m_timers.erase(it);
} else {
++it;
}
}
}
Void::Result::Result<ExecutionContext::TimerId>
ExecutionContext::try_add_timer(
Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire, ScopeId scope)
{
if (m_limits.max_timers > 0 && m_timers.size() >= m_limits.max_timers) {
return Void::Result::fail(make_fsm_error(
FsmErrorCode::limit_exceeded,
"ExecutionContext::try_add_timer: max_timers reached"));
}
const TimerId id = m_next_timer++;
m_timers.emplace(id, Timer{deadline, std::move(on_fire)});
m_timers.emplace(id, Timer{deadline, std::move(on_fire), scope});
return id;
}
ExecutionContext::TimerId
ExecutionContext::add_timer(Time::MonotonicClock::time_point deadline,
std::function<void()> on_fire,
ScopeId scope)
{
auto r = try_add_timer(deadline, std::move(on_fire), scope);
return r ? *r : 0;
}
void ExecutionContext::cancel_timer(TimerId id)
{
if (id != 0) {
@@ -84,10 +327,10 @@ namespace Void::Fsm::Detail
}
}
std::optional<std::chrono::steady_clock::time_point>
std::optional<Time::MonotonicClock::time_point>
ExecutionContext::next_deadline() const
{
std::optional<std::chrono::steady_clock::time_point> next;
std::optional<Time::MonotonicClock::time_point> next;
for (const auto& [id, timer] : m_timers) {
if (!next.has_value() || timer.deadline < *next) {
next = timer.deadline;
@@ -101,7 +344,7 @@ namespace Void::Fsm::Detail
if (m_timers.empty()) {
return;
}
const auto now = std::chrono::steady_clock::now();
const auto now = m_clock->now();
std::vector<std::function<void()>> due;
for (auto it = m_timers.begin(); it != m_timers.end();) {
if (it->second.deadline <= now) {
@@ -120,20 +363,36 @@ namespace Void::Fsm::Detail
void ExecutionContext::deliver(EventEnvelope& env)
{
// Route to the first parked waiter (FIFO) that wants this type — lets
// it receive the event without ever sitting in a buffer.
for (auto it = m_waiters.begin(); it != m_waiters.end(); ++it) {
if (it->wants(*env.type)) {
*it->slot = std::move(env);
cancel_timer(it->timer);
auto cont = it->cont;
m_waiters.erase(it);
m_executor.post(cont);
active_executor().post_completion(cont);
return;
}
}
// Otherwise buffer for a later await.
m_buffers[std::type_index{*env.type}].push_back(std::move(env.value));
if (m_limits.max_deferred_events > 0 &&
m_buffered_events >= m_limits.max_deferred_events) {
Void::Log::warn("Fsm",
"dropping deferred event: max_deferred_events reached");
return;
}
m_buffered_events += 1;
m_buffered_bytes += env.bytes;
m_buffers[std::type_index{*env.type}].push_back(
BufferedEvent{std::move(env.value), env.bytes});
}
void ExecutionContext::drain_control_queue()
{
while (auto fn = m_control_queue.try_pop()) {
m_queued_control.fetch_sub(1, std::memory_order_acq_rel);
if (*fn) {
(*fn)();
}
}
}
void ExecutionContext::set_paused(bool paused)
@@ -144,22 +403,81 @@ namespace Void::Fsm::Detail
std::size_t ExecutionContext::pump()
{
drain_control_queue();
if (m_paused.load(std::memory_order_acquire)) {
return 0;
}
++m_dispatch_turn;
std::size_t work = 0;
std::size_t events_this_turn = 0;
const auto turn_start = m_clock->now();
fire_due_timers();
while (auto env = m_queue.try_pop()) {
while (events_this_turn < m_limits.max_events_per_turn) {
if (m_limits.max_turn_duration.count() > 0 &&
events_this_turn > 0 &&
(m_clock->now() - turn_start) >= m_limits.max_turn_duration) {
break;
}
auto env = m_queue.try_pop();
if (!env) {
break;
}
m_queued_events.fetch_sub(1, std::memory_order_acq_rel);
m_queued_bytes.fetch_sub(env->bytes, std::memory_order_acq_rel);
deliver(*env);
++events_this_turn;
++work;
}
work += m_executor.drain();
m_last_turn_events = events_this_turn;
drain_control_queue();
if (m_external_executor == nullptr) {
work += m_executor.drain();
}
fire_due_timers();
drain_control_queue();
return work;
}
void ExecutionContext::run_external_pump_step()
{
if (m_done.load(std::memory_order_acquire)) {
m_pump_scheduled.store(false, std::memory_order_release);
return;
}
m_pump_scheduled.store(false, std::memory_order_seq_cst);
(void)pump();
if (!m_done.load(std::memory_order_acquire) &&
(!m_control_queue.empty() ||
(!m_paused.load(std::memory_order_acquire) && !m_queue.empty()))) {
schedule_external_pump();
}
}
void ExecutionContext::schedule_external_pump() noexcept
{
if (m_external_executor == nullptr ||
m_done.load(std::memory_order_acquire)) {
return;
}
auto weak = weak_from_this();
if (weak.expired()) {
return;
}
if (!m_pump_scheduled.exchange(true, std::memory_order_acq_rel)) {
Async::spawn(*m_external_executor,
external_pump_task(std::move(weak)));
}
}
void ExecutionContext::wake() noexcept
{
if (m_external_executor != nullptr) {
schedule_external_pump();
}
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
m_wakeup.release();
}
@@ -204,22 +522,25 @@ namespace Void::Fsm::Detail
const bool paused = m_paused.load(std::memory_order_acquire);
if (!paused) {
pump();
} else {
drain_control_queue();
}
if (m_done.load(std::memory_order_acquire)) {
return;
}
m_sleeping.store(true, std::memory_order_release);
// Queued events only count as wakeable work when not paused.
if ((!paused && !m_queue.empty()) ||
if ((!paused && !m_queue.empty()) || !m_control_queue.empty() ||
m_done.load(std::memory_order_acquire)) {
m_sleeping.store(false, std::memory_order_release);
continue;
}
// 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);
if (m_clock == &Time::SystemMonotonicClock::instance()) {
(void)m_wakeup.try_acquire_until(*deadline);
} else {
(void)m_wakeup.try_acquire_for(std::chrono::milliseconds{1});
}
} else {
m_wakeup.acquire();
}