diff --git a/include/Void/Fsm/Detail/Awaiter.hpp b/include/Void/Fsm/Detail/Awaiter.hpp index 88f719a..b675a35 100644 --- a/include/Void/Fsm/Detail/Awaiter.hpp +++ b/include/Void/Fsm/Detail/Awaiter.hpp @@ -1,41 +1,90 @@ #pragma once #include +#include #include #include #include #include +#include #include #include namespace Void::Fsm::Detail { - /// One awaiter for every "wait for an event (optionally with a deadline)" - /// operation on a machine. `Storage` is the type-list container (a - /// std::array for fixed sets, a std::vector for dynamic ones); `Resume` is - /// the projection `(EventEnvelope&&, bool timed_out) -> R` that shapes the - /// awaited value (the matched event, an optional on timeout, a variant, - /// …). Built on ExecutionContext::{try_take_any,set_waiter}. + struct WaiterCancelFn { + ExecutionContext* ctx{nullptr}; + ExecutionContext::WaiterId waiter_id{0}; + + void operator()() const + { + if (ctx != nullptr && waiter_id != 0) { + (void)ctx->try_post_control( + [c = ctx, wid = waiter_id] { c->cancel_waiter(wid); }); + } + } + }; + + /// Unified awaiter for awaiting an event (or event set), optional timeout + /// on injected clock, and cooperative stop cancellation across both + /// per-state scope stop and caller-supplied OperationOptions stop tokens. template struct EventAwaiter { - ExecutionContext* ctx; - Storage types; - EventEnvelope env; + ExecutionContext* ctx{nullptr}; + Storage types{}; + EventEnvelope env{}; bool timed_out{false}; - std::optional deadline; - Resume resume; + bool cancelled{false}; + std::optional deadline{}; + Resume resume{}; + ExecutionContext::ScopeId scope{ExecutionContext::kNoScope}; + std::stop_token scope_stop{}; + std::stop_token user_stop{}; + ExecutionContext::WaiterId waiter_id{0}; + std::optional> scope_cb{}; + std::optional> user_cb{}; [[nodiscard]] bool await_ready() { - return ctx->try_take_any(span(), env); + if (scope_stop.stop_requested() || user_stop.stop_requested()) { + cancelled = true; + return true; + } + if (ctx != nullptr && !types.empty() && + ctx->try_take_any(span(), env)) { + return true; + } + if (deadline.has_value() && ctx != nullptr && + ctx->clock().now() >= *deadline) { + timed_out = true; + return true; + } + return false; } + void await_suspend(std::coroutine_handle<> h) { - ctx->set_waiter(span(), h, &env, &timed_out, deadline); + waiter_id = ctx->set_waiter(span(), h, &env, &timed_out, + deadline, scope, &cancelled); + if (scope_stop.stop_possible()) { + scope_cb.emplace(scope_stop, + WaiterCancelFn{ctx, waiter_id}); + } + if (user_stop.stop_possible()) { + user_cb.emplace(user_stop, WaiterCancelFn{ctx, waiter_id}); + } } - [[nodiscard]] decltype(auto) await_resume() + + decltype(auto) await_resume() { - return resume(std::move(env), timed_out); + scope_cb.reset(); + user_cb.reset(); + if constexpr (std::is_invocable_v) { + return resume(std::move(env), timed_out, cancelled); + } else { + return resume(std::move(env), timed_out); + } } private: @@ -49,10 +98,24 @@ namespace Void::Fsm::Detail template [[nodiscard]] auto make_event_awaiter( ExecutionContext* ctx, Storage types, - std::optional deadline, - Resume resume) + std::optional deadline, + Resume resume, + ExecutionContext::ScopeId scope = ExecutionContext::kNoScope, + std::stop_token scope_stop = {}, std::stop_token user_stop = {}) { return EventAwaiter{ - ctx, std::move(types), {}, false, deadline, std::move(resume)}; + ctx, + std::move(types), + {}, + false, + false, + deadline, + std::move(resume), + scope, + std::move(scope_stop), + std::move(user_stop), + 0, + std::nullopt, + std::nullopt}; } } // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp index fbf42da..1734782 100644 --- a/include/Void/Fsm/Detail/Engine.hpp +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include #include @@ -14,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -28,17 +31,14 @@ namespace Void::Fsm::Detail { /// Type-erased state. Concrete states derive the single Machine:: /// 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 on_enter(); virtual Coro::Task 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 { 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(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 + try_post(EventEnvelope env); void post(EventEnvelope env); + [[nodiscard]] Void::Result::Result + try_post_control(std::function 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 types, std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out, - std::optional deadline); + std::optional 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 - 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 + try_add_timer(Time::MonotonicClock::time_point deadline, + std::function on_fire, + ScopeId scope = kNoScope); + TimerId add_timer(Time::MonotonicClock::time_point deadline, + std::function 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 - next_deadline() const; + struct BufferedEvent { + std::any value; + std::size_t bytes{0}; + }; - Async::ManualExecutor m_executor; - Async::MpscQueue m_queue; - - std::unordered_map> m_buffers; - using WaiterId = std::uint64_t; struct Waiter { WaiterId id{0}; + ScopeId scope{kNoScope}; std::vector 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 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 + next_deadline() const; + + const Time::MonotonicClock* m_clock; + FsmLimits m_limits; + Async::Executor* m_external_executor{nullptr}; + Async::ManualExecutor m_executor; + + Async::MpscQueue m_queue; + std::atomic m_queued_events{0}; + std::atomic m_queued_bytes{0}; + + Async::MpscQueue> m_control_queue; + std::atomic m_queued_control{0}; + + std::unordered_map> + m_buffers; + std::size_t m_buffered_events{0}; + std::size_t m_buffered_bytes{0}; + std::vector m_waiters; WaiterId m_next_waiter{1}; - struct Timer { - std::chrono::steady_clock::time_point deadline; - std::function on_fire; - }; std::map m_timers; TimerId m_next_timer{1}; + std::atomic m_next_scope{1}; + std::atomic 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 m_sleeping{false}; + std::atomic m_pump_scheduled{false}; std::atomic m_done{false}; std::atomic m_paused{false}; std::atomic m_worker_started{false}; diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index 13ecb24..db9372e 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -11,20 +12,28 @@ #include #include #include +#include #include #include +#include +#include #include #include #include #include #include #include +#include +#include #include #include #include #include +#include #include +#include +#include #include #include #include @@ -43,6 +52,50 @@ namespace Void::Fsm { + namespace Detail + { + struct CancelledException final : std::exception { + const char* what() const noexcept override + { + return "fsm operation cancelled"; + } + }; + + struct YieldAwaiter { + Async::Executor* exec{nullptr}; + + [[nodiscard]] bool await_ready() const noexcept + { + return exec == nullptr; + } + void await_suspend(std::coroutine_handle<> h) const + { + exec->post(h); + } + void await_resume() const noexcept {} + }; + + struct LatchResumeAwaiter { + bool ready{false}; + std::function)> arm{}; + + [[nodiscard]] bool await_ready() const noexcept { return ready; } + void await_suspend(std::coroutine_handle<> h) const + { + arm(h); + } + void await_resume() const noexcept {} + }; + + [[nodiscard]] inline std::size_t + estimate_checkpoint_bytes(const Checkpoint& cp) + { + return cp.machine_type.size() + cp.state_id.size() + + cp.resume_label.size() + + Void::Json::serialize(cp.state).size() + 64; + } + } // namespace Detail + /// Options for a Machine (namespace scope to dodge the GCC /// nested-default-arg trap). struct MachineOptions { @@ -53,7 +106,7 @@ namespace Void::Fsm /// at the sub-state it last reached (shallow history). enum class Resume { Initial, History }; - /// A transition record handed to observers. + /// A transition record handed to observers and stored in bounded history. struct Transition { std::string from; std::string to; @@ -61,48 +114,12 @@ namespace Void::Fsm }; // ── Machine ────────────────────────────────────────────────── - // - // Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it - // and declare the states as a nested struct of forward declarations: - // struct States { struct FirstState; struct SecondState; … }; - // defined out-of-line (typically in a .cpp), each deriving the single - // `State`. The Machine base auto-registers them by reflecting `States` - // (Detail/StateList.hpp) — the first declared state is the initial one - // unless `using Initial = S;`. All behaviour lives inside a state: the - // engine infers each state's role from its member signatures (entry / - // startup-entry / continuation handlers); states reach their machine (data - // + sub-methods) via self(). Events are handled imperatively inside an - // entry (co_await await_event()) — there is no declarative transition - // table. Result types are the nested `Success`/`Failure` (default void). - // - // // header - // class Login : public Void::Fsm::Machine { - // public: - // using Success = Token; - // int attempts = 0; - // struct States { struct Check; }; - // }; - // // source (namespace scope) - // struct Login::States::Check : Login::State { // entry by signature - // Coro::Task> run() { - // if (++self().attempts > 3) co_return fail(); - // co_return self().service().ok() ? succeed(Token{}) - // : next(); - // } - // }; template class Machine { public: using Options = MachineOptions; - // Result types are reflected by name from Derived's nested - // `Success`/`Failure` (default void). Because Derived is incomplete - // at base instantiation (CRTP), they cannot appear in member - // signatures or data members — only inside function templates / - // bodies, where Derived is complete. So these are alias *templates* - // (lazily resolved), the engine stores outcomes type-erased, and - // the typed Outcome is rebuilt in wait()/take_outcome(). template using Success = Detail::SuccessOf; template @@ -110,12 +127,15 @@ namespace Void::Fsm template using Outcome = Detail::OutcomeOf; + using MigrationFn = std::function( + std::uint32_t from_schema, std::uint32_t to_schema, + Json::Value& data, std::string& state_id)>; + // ── State base ──────────────────────────────────────────────── class State : public Detail::StateBase { public: - /// Typed access to the owning machine — no static_cast. [[nodiscard]] Derived& self() const noexcept { return *static_cast(m_machine); @@ -128,8 +148,6 @@ namespace Void::Fsm protected: - /// Transition to another state. Validated at compile - /// time when the machine declares a `States` list. template [[nodiscard]] StateKey next() const { if constexpr (requires { typename Derived::States; }) { @@ -141,28 +159,18 @@ namespace Void::Fsm return StateKey::transition(typeid(S)); } - /// Transition to a state registered dynamically - /// (add()/add_if()), skipping the static check. template [[nodiscard]] StateKey next_dynamic() const { return StateKey::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]] StateKey goto_state() const { return StateKey::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()); template [[nodiscard]] StateKey next_or(StateKey step) const { @@ -172,7 +180,6 @@ namespace Void::Fsm return step; } - /// Suspend for `duration` (timer-driven), then resume. template [[nodiscard]] auto delay(std::chrono::duration d) const @@ -180,15 +187,18 @@ namespace Void::Fsm return m_machine->delay(d); } - /// Retry an async sub-step up to `times`, waiting - /// `backoff` between attempts. `attempt` returns - /// Coro::Task (true = success). Returns whether it - /// eventually succeeded. + template + [[nodiscard]] auto delay_cancellable( + std::chrono::duration d, + Async::OperationOptions opts = {}) const + { + return m_machine->delay_cancellable(d, std::move(opts)); + } + template [[nodiscard]] Coro::Task with_retry(int times, - std::chrono::duration - backoff, + std::chrono::duration backoff, Fn attempt) const { for (int i = 0; i < times; ++i) { @@ -202,8 +212,6 @@ namespace Void::Fsm co_return false; } - /// Finish with the machine's typed Success result (nested - /// `Success`; nullary when it is void). [[nodiscard]] StateKey succeed() const requires std::is_void_v> { @@ -218,8 +226,6 @@ namespace Void::Fsm std::forward(value))}); } - /// Finish with the machine's typed Failure result (nested - /// `Failure`; nullary when it is void). [[nodiscard]] StateKey fail() const requires std::is_void_v> { @@ -239,12 +245,25 @@ namespace Void::Fsm return m_machine->template service(); } + /// Resolve a service handle that keeps the provider alive + /// across coroutine suspension / hot reload. + template + [[nodiscard]] Void::Result::Result> + acquire_service() const + { + return m_machine->template acquire_service(); + } + + [[nodiscard]] std::stop_token state_stop_token() const noexcept + { + return m_machine->state_stop_token(); + } + template [[nodiscard]] auto await_event() const { return m_machine->template await_event(); } - /// Await E or time out (nullopt on timeout). template [[nodiscard]] auto await_event_for( std::chrono::duration d) const @@ -252,6 +271,26 @@ namespace Void::Fsm return m_machine->template await_event_for(d); } + template + [[nodiscard]] auto await_event_cancellable( + Async::OperationOptions opts = {}) const + { + return m_machine->template await_event_cancellable( + std::move(opts)); + } + + [[nodiscard]] Coro::Task + safe_point(std::string_view resume_label = {}) const + { + return m_machine->safe_point(resume_label); + } + + [[nodiscard]] std::string_view + restored_resume_label() const noexcept + { + return m_machine->restored_resume_label(); + } + template [[nodiscard]] auto run_child(Args&&... args) const { @@ -259,13 +298,6 @@ namespace Void::Fsm std::forward(args)...); } - /// Enter a child region (composite sub-state): a nested - /// machine sharing this machine's executor, event mailbox - /// and services. This state's on_enter/on_exit wrap it, and - /// state_path() reports the parent→child chain while it - /// runs. Map the child's Outcome to a sibling transition: - /// auto r = co_await run_region(); - /// co_return r ? next() : next(); template [[nodiscard]] auto run_region(Resume resume = Resume::Initial) const @@ -273,42 +305,38 @@ namespace Void::Fsm return m_machine->template run_region(resume); } - /// Orthogonal regions: run `Subs...` concurrently on the - /// shared executor and join all, yielding a - /// std::tuple (children share events/ - /// services; map the tuple to a sibling transition). template [[nodiscard]] auto run_parallel() const { return m_machine->template run_parallel(); } - /// Race orthogonal regions: resolve on the first to finish, - /// yielding std::variant (losers keep - /// running cooperatively). template [[nodiscard]] auto run_parallel_any() const { return m_machine->template run_parallel_any(); } - /// Await whichever of several event types arrives first, - /// yielding a std::variant. Handles multiple events - /// at one level (e.g. a parent watching Cancel alongside a - /// child region's own events). + template + [[nodiscard]] auto run_parallel_structured() const + { + return m_machine + ->template run_parallel_structured(); + } + + template + [[nodiscard]] auto run_parallel_any_structured() const + { + return m_machine + ->template run_parallel_any_structured(); + } + template [[nodiscard]] auto await_any() const { return m_machine->template await_any(); } - /// Launch a sub-machine `Sub` (startup data routed to its - /// initial-state startup-entry; shares this machine's - /// executor/events/services), then transition to `Next`. - /// When Sub finishes the engine calls Next's signature - /// -matched handler — a member taking `ChildSuccess` - /// (Sub succeeded) or `ChildFailure` (Sub failed): - /// co_return startMachine(seed); template [[nodiscard]] StateKey startMachine(Args&&... args) const { @@ -327,31 +355,6 @@ namespace Void::Fsm Machine* m_machine{nullptr}; }; - // ── one State, signature-inferred roles ─────────────────────── - // - // There is a single base, `State`. The engine infers what each - // state does from member signatures (no `override`, no fixed - // names): - // - entry : a member returning - // State/Coro::Task>, - // no params (a startup-data overload may take - // the sub's startup argument); - // - continuation : members taking `ChildSuccess` / - // `ChildFailure` (the sub's typed result, read - // via .as(), after `startMachine`). - // - // Events are handled imperatively inside an entry: - // struct Idle : State { // entry - // Coro::Task run() { - // auto e = co_await await_any(); - // co_return std::holds_alternative(e) ? next() - // : next(); } - // }; - // struct After : State { // continuation - // Coro::Task ok(ChildSuccess s){ ... } - // Coro::Task no(ChildFailure f){ ... } }; - // ── construction ────────────────────────────────────────────── explicit Machine(Options options = {}) : m_options(options) { @@ -370,7 +373,7 @@ namespace Void::Fsm Machine(const Machine&) = delete; Machine& operator=(const Machine&) = delete; - // ── registration ────────────────────────────────────────────── + // ── registration & durable identities ───────────────────────── template void add() { static_assert(std::is_base_of_v, @@ -384,13 +387,17 @@ namespace Void::Fsm m_index.emplace(key, idx); m_names.push_back(state_name()); m_name_to_type.emplace(m_names.back(), &ti); + std::string durable = default_state_id(m_names.back()); + m_type_to_id.emplace(key, durable); + if (!m_id_to_type.contains(durable)) { + m_id_to_type.emplace(std::move(durable), &ti); + } m_factories.emplace( key, [this]() -> std::unique_ptr { auto s = std::make_unique(); s->m_machine = this; return s; }); - // Signature-inferred driver thunk (runs the state's entry). m_drivers.emplace(key, Detail::make_driver()); } @@ -412,22 +419,18 @@ 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) { + if (m_status.load(std::memory_order_acquire) != 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) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return; } const std::type_index key{typeid(S)}; @@ -437,11 +440,15 @@ namespace Void::Fsm } const int idx = idxIt->second; m_name_to_type.erase(m_names[static_cast(idx)]); + if (const auto idIt = m_type_to_id.find(key); + idIt != m_type_to_id.end()) { + m_id_to_type.erase(idIt->second); + m_type_to_id.erase(idIt); + } m_names.erase(m_names.begin() + idx); m_factories.erase(key); m_drivers.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; @@ -454,11 +461,9 @@ namespace Void::Fsm } } - /// Swap state `S` for `T`, preserving the initial pointer if S was - /// it. Idle-only. template void replace() { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return; } const bool was_initial = (m_initial == &typeid(S)); @@ -469,6 +474,64 @@ namespace Void::Fsm } } + /// Assign an explicit durable state identifier (used in checkpoints) + /// while Idle. Rejects empty or colliding IDs. + template + [[nodiscard]] Void::Result::Result + register_state_id(std::string durable_id) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "register_state_id requires Idle machine")); + } + if (durable_id.empty()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_argument, + "register_state_id: empty id")); + } + const std::type_index key{typeid(S)}; + if (!m_factories.contains(key)) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::not_found, + "register_state_id: state not registered")); + } + if (const auto existing = m_id_to_type.find(durable_id); + existing != m_id_to_type.end() && + existing->second != &typeid(S)) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_argument, + "register_state_id: duplicate durable id '" + + durable_id + "'")); + } + if (const auto prev = m_type_to_id.find(key); + prev != m_type_to_id.end()) { + m_id_to_type.erase(prev->second); + } + m_id_to_type.insert_or_assign(durable_id, &typeid(S)); + m_type_to_id.insert_or_assign(key, std::move(durable_id)); + return {}; + } + + void set_machine_identity(std::string machine_type, + std::uint32_t application_schema = 1) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return; + } + m_machine_type = std::move(machine_type); + m_application_schema = application_schema; + } + + void set_limits(FsmLimits limits) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return; + } + m_limits = limits; + m_has_explicit_limits = true; + } + // ── service context ─────────────────────────────────────────── void set_services(Service::ServiceRegistry& registry) noexcept { @@ -480,42 +543,77 @@ namespace Void::Fsm return m_services->template require(); } + template + [[nodiscard]] Void::Result::Result> + acquire_service() const + { + if (m_services == nullptr) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::service_unavailable, + "Machine::acquire_service: no ServiceRegistry bound")); + } + auto r = m_services->template acquire(); + if (!r) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::service_unavailable, + r.error().message())); + } + return r; + } + // ── observability ───────────────────────────────────────────── - /// Register a read-only observer fired on every transition - /// (and on the initial entry). Replaces any prior observer. void observe(std::function observer) { + std::lock_guard lk{m_obs_mu}; m_observer = std::move(observer); } - /// Transition middleware. `before(transition)` fires as a state - /// is entered (after the state changes, before it runs); - /// `after(state_name)` fires once that state finishes running. - /// Interceptors run in registration order — for logging, - /// metrics, validation around transitions. struct Interceptor { std::function before; std::function after; }; void add_interceptor(Interceptor interceptor) { + std::lock_guard lk{m_obs_mu}; m_interceptors.push_back(std::move(interceptor)); } + [[nodiscard]] std::vector transition_history() const + { + std::lock_guard lk{m_obs_mu}; + return {m_transition_history.begin(), + m_transition_history.end()}; + } + + [[nodiscard]] std::vector observer_errors() const + { + std::lock_guard lk{m_obs_mu}; + return m_observer_errors; + } + // ── lifecycle ───────────────────────────────────────────────── void start() { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return; } if (!m_ctx) { - m_ctx = std::make_shared(); + FsmLimits start_limits = m_limits; + if (!m_has_explicit_limits) { + start_limits.max_mailbox_events = 0; + start_limits.max_mailbox_bytes = 0; + start_limits.max_deferred_events = 0; + } + m_ctx = std::make_shared( + &Time::SystemMonotonicClock::instance(), start_limits, + nullptr); m_owns_ctx = true; } - m_status.store(Status::Running); - // Own the driver coroutine (rather than detaching it) so a - // machine stopped while parked on an event can destroy the - // suspended frame chain instead of leaking it. + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + m_root_stop.emplace(); + m_root_timeout.store(false, std::memory_order_release); + m_status.store(Status::Running, std::memory_order_release); m_driver.emplace(driver()); m_ctx->executor().post(m_driver->handle()); if (m_options.own_worker && m_owns_ctx) { @@ -523,8 +621,114 @@ namespace Void::Fsm } } - // Function templates so the typed Outcome resolves where Derived is - // complete (CRTP). Call sites stay `fsm.wait()` / `run_blocking()`. + /// Explicit structured async execution on borrowed executor & clock. + template + [[nodiscard]] Coro::Task>> + run(ExecutionBinding binding, + Async::OperationOptions opts = {}) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "Machine::run: machine must be Idle")); + } + if (binding.limits.max_events_per_turn == 0 || + binding.limits.max_mailbox_events == 0 || + binding.limits.max_hierarchy_depth == 0 || + binding.limits.max_child_regions == 0) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_argument, + "Machine::run: limits must be non-zero")); + } + + const auto* clk = binding.clock != nullptr + ? binding.clock + : &Time::SystemMonotonicClock::instance(); + if (opts.stop.stop_requested()) { + m_termination_reason.store(TerminationReason::cancelled, + std::memory_order_release); + fault("cancelled before start"); + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "Machine::run: cancelled before start")); + } + if (opts.deadline.has_value() && clk->now() >= *opts.deadline) { + m_termination_reason.store(TerminationReason::timed_out, + std::memory_order_release); + fault("deadline expired before start"); + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "Machine::run: deadline expired before start")); + } + + m_limits = binding.limits; + m_ctx = std::make_shared( + clk, binding.limits, binding.executor); + m_owns_ctx = true; + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + m_root_timeout.store(false, std::memory_order_release); + m_root_stop.emplace(); + + std::optional>> + ext_stop_cb; + if (opts.stop.stop_possible()) { + ext_stop_cb.emplace(opts.stop, [this] { + if (m_root_stop) { + m_root_stop->request_stop(); + } + }); + } + + Detail::ExecutionContext::TimerId deadline_timer = 0; + if (opts.deadline.has_value()) { + auto t = m_ctx->try_add_timer(*opts.deadline, [this] { + m_root_timeout.store(true, std::memory_order_release); + if (m_root_stop) { + m_root_stop->request_stop(); + } + }); + if (t) { + deadline_timer = *t; + } + } + + m_status.store(Status::Running, std::memory_order_release); + co_await drive(); + + if (deadline_timer != 0 && m_ctx) { + m_ctx->cancel_timer(deadline_timer); + } + ext_stop_cb.reset(); + if (m_owns_ctx && m_ctx) { + m_ctx->finish(); + } + + const auto st = m_status.load(std::memory_order_acquire); + const auto reason = + m_termination_reason.load(std::memory_order_acquire); + if (reason == TerminationReason::timed_out || + m_root_timeout.load(std::memory_order_acquire)) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + m_system_error ? m_system_error->message + : std::string{"fsm run timed out"})); + } + if (reason == TerminationReason::cancelled) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + m_system_error ? m_system_error->message + : std::string{"fsm run cancelled"})); + } + if (st == Status::Faulted) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::fault, + m_system_error ? m_system_error->message + : std::string{"fsm system fault"})); + } + co_return take_outcome(); + } + template Outcome wait() { if (m_ctx) { @@ -547,8 +751,6 @@ namespace Void::Fsm return wait(); } - /// The system fault (if any) — a programming error caught by the - /// engine, separate from a typed Failure result. [[nodiscard]] std::optional system_error() const { return m_system_error; @@ -558,59 +760,81 @@ namespace Void::Fsm [[nodiscard]] bool finished() const noexcept { - const auto s = m_status.load(); - return s == Status::Succeeded || s == Status::Failed || - s == Status::Faulted; + return terminal(m_status.load(std::memory_order_acquire)); } [[nodiscard]] Status status() const noexcept { - return m_status.load(); + return m_status.load(std::memory_order_acquire); + } + + [[nodiscard]] TerminationReason + termination_reason() const noexcept + { + return m_termination_reason.load(std::memory_order_acquire); + } + + [[nodiscard]] Detail::ExecutionContext* + execution_context() noexcept + { + return m_ctx.get(); + } + + [[nodiscard]] Detail::ExecutionContext::ScopeId + active_scope() const noexcept + { + return m_active_scope; } void stop() { + if (m_root_stop) { + m_root_stop->request_stop(); + } if (m_owns_ctx && m_ctx) { m_ctx->stop(); } - // The worker is joined now (no concurrent resume), so destroy - // the owned driver — this cascade-destroys the suspended - // coroutine chain (a machine parked on an event) instead of - // leaking it. Safe on a finished coroutine too. m_driver.reset(); } - /// 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) { + if (m_status.load(std::memory_order_acquire) == Status::Running) { return; } if (m_owns_ctx && m_ctx) { m_ctx->stop(); } - m_driver.reset(); // destroy the (possibly parked) driver chain + m_driver.reset(); m_ctx.reset(); m_owns_ctx = false; m_current.store(-1, std::memory_order_release); m_result_value.reset(); m_system_error.reset(); m_pending_result.reset(); + m_pending_dispatch = nullptr; m_jump.store(nullptr, std::memory_order_release); m_step = 0; + m_restored_resume_label.clear(); + m_root_stop.reset(); + m_root_timeout.store(false, std::memory_order_release); + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + { + std::lock_guard lk{m_obs_mu}; + m_transition_history.clear(); + m_observer_errors.clear(); + } + m_pending_checkpoints.clear(); 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(); @@ -618,9 +842,6 @@ namespace Void::Fsm 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) { @@ -635,17 +856,41 @@ namespace Void::Fsm } // ── events ──────────────────────────────────────────────────── + template + [[nodiscard]] Void::Result::Result + try_post(E event, Async::OperationOptions opts = {}) + { + if (opts.stop.stop_requested()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "Machine::try_post: cancelled")); + } + if (!m_ctx) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "Machine::try_post: machine not started")); + } + if (opts.deadline.has_value() && + m_ctx->clock().now() >= *opts.deadline) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "Machine::try_post: deadline expired")); + } + const std::size_t bytes = event_payload_bytes(event); + return m_ctx->try_post(Detail::EventEnvelope{ + &typeid(E), std::any{std::move(event)}, bytes}); + } + template void post(E event) { if (!m_ctx) { return; } - m_ctx->post(Detail::EventEnvelope{&typeid(E), - std::any{std::move(event)}}); + const std::size_t bytes = event_payload_bytes(event); + m_ctx->post(Detail::EventEnvelope{ + &typeid(E), std::any{std::move(event)}, bytes}); } - /// Re-post an already type-erased event (used by the reactive loop - /// to re-inject deferred events after a transition). void repost(Detail::EventEnvelope env) { if (m_ctx) { @@ -653,79 +898,119 @@ namespace Void::Fsm } } - /// 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) { + (void)m_ctx->try_post_control([] {}); m_ctx->nudge(); } } - template [[nodiscard]] auto await_event() + [[nodiscard]] std::stop_token state_stop_token() const noexcept { + if (m_active_state_stop != nullptr) { + return m_active_state_stop->get_token(); + } + if (m_root_stop.has_value()) { + return m_root_stop->get_token(); + } + return {}; + } + + template [[nodiscard]] auto await_event() + { + const std::stop_token st = state_stop_token(); return Detail::make_event_awaiter( m_ctx.get(), std::array{&typeid(E)}, std::nullopt, - [](Detail::EventEnvelope&& env, bool) { + [](Detail::EventEnvelope&& env, bool, bool cancelled) { + if (cancelled) { + throw Detail::CancelledException{}; + } return std::any_cast(std::move(env.value)); - }); + }, + m_active_scope, st); } - /// Await an event of type E or time out after `duration`; - /// returns std::nullopt on timeout. template [[nodiscard]] auto await_event_for(std::chrono::duration duration) { + const auto now = m_ctx != nullptr + ? m_ctx->clock().now() + : std::chrono::steady_clock::now(); + const std::stop_token st = state_stop_token(); return Detail::make_event_awaiter( - m_ctx.get(), std::array{&typeid(E)}, - std::chrono::steady_clock::now() + duration, - [](Detail::EventEnvelope&& env, - bool timed_out) -> std::optional { + m_ctx.get(), std::array{&typeid(E)}, now + duration, + [](Detail::EventEnvelope&& env, bool timed_out, + bool cancelled) -> std::optional { + if (cancelled) { + throw Detail::CancelledException{}; + } if (timed_out) { return std::nullopt; } return std::any_cast(std::move(env.value)); - }); + }, + m_active_scope, st); + } + + template + [[nodiscard]] auto + await_event_cancellable(Async::OperationOptions opts = {}) + { + return Detail::make_event_awaiter( + m_ctx.get(), std::array{&typeid(E)}, opts.deadline, + [](Detail::EventEnvelope&& env, bool timed_out, + bool cancelled) -> Void::Result::Result { + if (cancelled) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "await_event_cancellable: cancelled")); + } + if (timed_out) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "await_event_cancellable: deadline expired")); + } + return std::any_cast(std::move(env.value)); + }, + m_active_scope, state_stop_token(), opts.stop); } - /// 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 types, - std::optional deadline) + std::optional deadline) { return Detail::make_event_awaiter( m_ctx.get(), std::move(types), deadline, - [](Detail::EventEnvelope&& env, - bool timed_out) -> std::optional { + [](Detail::EventEnvelope&& env, bool timed_out, + bool cancelled) -> std::optional { + if (cancelled) { + throw Detail::CancelledException{}; + } if (timed_out) { return std::nullopt; } return std::move(env); - }); + }, + m_active_scope, state_stop_token()); } - /// Typed multi-event await: suspend until one of `Es...` arrives, - /// returning it as std::variant. Lets one state react to - /// several event types (parent-level handling for child regions). template [[nodiscard]] auto await_any() { return Detail::make_event_awaiter( m_ctx.get(), std::array{(&typeid(Es))...}, std::nullopt, - [](Detail::EventEnvelope&& env, - bool) -> std::variant { + [](Detail::EventEnvelope&& env, bool, + bool cancelled) -> std::variant { + if (cancelled) { + throw Detail::CancelledException{}; + } std::optional> out; ((env.type != nullptr && *env.type == typeid(Es) ? (out.emplace( @@ -735,31 +1020,72 @@ namespace Void::Fsm : false) || ...); return std::move(*out); - }); + }, + m_active_scope, state_stop_token()); } - /// Suspend for `duration`, then resume (timer-driven). template [[nodiscard]] auto delay(std::chrono::duration d) { - struct Awaiter { - Detail::ExecutionContext* ctx; - std::chrono::steady_clock::time_point deadline; + const auto now = m_ctx != nullptr + ? m_ctx->clock().now() + : std::chrono::steady_clock::now(); + return Detail::make_event_awaiter( + m_ctx.get(), std::array{}, + now + d, + [](Detail::EventEnvelope&&, bool, bool cancelled) { + if (cancelled) { + throw Detail::CancelledException{}; + } + }, + m_active_scope, state_stop_token()); + } - [[nodiscard]] bool await_ready() const noexcept - { - return false; + template + [[nodiscard]] auto delay_cancellable( + std::chrono::duration d, + Async::OperationOptions opts = {}) + { + const auto now = m_ctx != nullptr + ? m_ctx->clock().now() + : std::chrono::steady_clock::now(); + auto deadline = now + d; + if (opts.deadline.has_value() && *opts.deadline < deadline) { + deadline = *opts.deadline; + } + return Detail::make_event_awaiter( + m_ctx.get(), std::array{}, + deadline, + [](Detail::EventEnvelope&&, bool, + bool cancelled) -> Void::Result::Result { + if (cancelled) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "delay_cancellable: cancelled")); } - void await_suspend(std::coroutine_handle<> h) - { - ctx->add_timer(deadline, [c = ctx, h] { - c->executor().post(h); - }); - } - void await_resume() const noexcept {} - }; - return Awaiter{m_ctx.get(), - std::chrono::steady_clock::now() + d}; + return {}; + }, + m_active_scope, state_stop_token(), opts.stop); + } + + /// Application-declared safe point inside a running state: yields + /// one turn to let pending checkpoint requests serialize cleanly. + [[nodiscard]] Coro::Task + safe_point(std::string_view resume_label = {}) + { + if (m_ctx == nullptr) { + co_return; + } + co_await Detail::YieldAwaiter{&m_ctx->active_executor()}; + m_ctx->drain_control_queue(); + fulfill_pending_checkpoints(current_durable_id(), + std::string{resume_label}); + } + + [[nodiscard]] const std::string& + restored_resume_label() const noexcept + { + return m_restored_resume_label; } // ── nesting ─────────────────────────────────────────────────── @@ -768,24 +1094,16 @@ namespace Void::Fsm run_child(Args&&... args) { Sub child{std::forward(args)...}; - child.attach(m_ctx, m_services); + child.attach(m_ctx, m_services, m_depth + 1, m_active_state_stop); co_await child.drive(); co_return child.template take_outcome(); } - /// Composite sub-state: run `Sub` as a child region sharing this - /// machine's executor, event mailbox and services, and expose its - /// active state through this machine's state_path() while it runs - /// (parent→child chain). Returns the child's Outcome, which the - /// caller maps to a sibling transition. The calling state's - /// on_enter/on_exit naturally wrap the region. template [[nodiscard]] Coro::Task> run_region(Resume resume = Resume::Initial) { Sub child; - // History: resume at the sub-state this region last reached. - // restore() must run before attach() (which marks Running). if (resume == Resume::History) { const auto it = m_region_history.find(std::type_index{typeid(Sub)}); @@ -793,70 +1111,57 @@ namespace Void::Fsm (void)child.restore(it->second); } } - child.attach(m_ctx, m_services); + child.attach(m_ctx, m_services, m_depth + 1, m_active_state_stop); m_region_probe = [&child] { return child.state_path(); }; co_await child.drive(); m_region_probe = nullptr; - // Snapshot the leaf it reached for a later History re-entry. m_region_history[std::type_index{typeid(Sub)}] = child.serialize(); co_return child.template take_outcome(); } - /// Orthogonal regions: run `Subs...` concurrently on the shared - /// executor (interleaved — when one parks on an event, another - /// runs) and join all, yielding a tuple of their Outcomes. Children - /// are default-constructed and share this machine's - /// events/services. template [[nodiscard]] Coro::Task...>> run_parallel() { auto children = std::make_unique>(); std::apply( - [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, + m_active_state_stop), + ...); + }, *children); struct Latch { int remaining; std::coroutine_handle<> waiter{}; Async::Executor* exec; - void arrive() + void arrive(std::size_t, Status, + std::optional) { if (--remaining == 0 && waiter) { - exec->post(waiter); + exec->post_completion(waiter); } } }; auto latch = std::make_shared( static_cast(sizeof...(Subs)), - std::coroutine_handle<>{}, &m_ctx->executor()); + std::coroutine_handle<>{}, &m_ctx->active_executor()); + std::size_t idx = 0; std::apply( [&](auto&... c) { - (Async::spawn(m_ctx->executor(), - [](auto& child, std::shared_ptr l) - -> Coro::Task { - co_await child.drive(); - l->arrive(); - }(c, latch)), + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), ...); }, *children); - struct Awaiter { - std::shared_ptr latch; - [[nodiscard]] bool await_ready() const noexcept - { - return latch->remaining == 0; - } - void await_suspend(std::coroutine_handle<> h) const - { - latch->waiter = h; - } - void await_resume() const noexcept {} - }; - co_await Awaiter{latch}; + co_await Detail::LatchResumeAwaiter{ + latch->remaining == 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; co_return std::apply( [](auto&... c) { @@ -866,75 +1171,52 @@ namespace Void::Fsm *children); } - /// Like run_parallel but resolves on the **first** child to finish, - /// yielding a std::variant holding the winner's - /// outcome. The losers keep running cooperatively (coroutines - /// aren't preemptible) — the children are kept alive by the spawned - /// tasks until they finish, so a loser parked forever leaks its - /// frame until the machine stops. Document at call sites. template [[nodiscard]] Coro::Task...>> run_parallel_any() { - // Shared so losers (which outlive this call) keep it alive. auto children = std::make_shared>(); std::apply( - [&](auto&... c) { (c.attach(m_ctx, m_services), ...); }, + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, + m_active_state_stop), + ...); + }, *children); struct Latch { int first{-1}; std::coroutine_handle<> waiter{}; Async::Executor* exec; - void arrive(int idx) + std::shared_ptr> keep; + void arrive(std::size_t idx, Status, + std::optional) { if (first < 0) { - first = idx; + first = static_cast(idx); if (waiter) { - exec->post(waiter); + exec->post_completion(waiter); } } } }; auto latch = std::make_shared( - -1, std::coroutine_handle<>{}, &m_ctx->executor()); + -1, std::coroutine_handle<>{}, &m_ctx->active_executor(), + children); - int idx = 0; + std::size_t idx = 0; std::apply( [&](auto&... c) { - ( - [&] { - const int my = idx++; - Async::spawn( - m_ctx->executor(), - [](auto& child, - std::shared_ptr> - keep, - std::shared_ptr - l, - int i) -> Coro::Task { - co_await child.drive(); - l->arrive(i); - (void)keep; - }(c, children, latch, my)); - }(), - ...); + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), + ...); }, *children); - struct Awaiter { - std::shared_ptr latch; - [[nodiscard]] bool await_ready() const noexcept - { - return latch->first >= 0; - } - void await_suspend(std::coroutine_handle<> h) const - { - latch->waiter = h; - } - void await_resume() const noexcept {} - }; - co_await Awaiter{latch}; + co_await Detail::LatchResumeAwaiter{ + latch->first >= 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; const auto winner = static_cast(latch->first); co_return [&](std::index_sequence) @@ -949,9 +1231,256 @@ namespace Void::Fsm }(std::index_sequence_for{}); } - /// Build a Launch step: run `Sub` (constructed from `args`) on this - /// machine's shared executor, then enter `Next` carrying Sub's - /// outcome as a LaunchResult. Reached via State::startMachine. + /// Structured parallel-all: enforces hierarchy depth and live child + /// region limits, stops siblings on any child system Fault, and + /// ALWAYS joins every child before returning. + template + [[nodiscard]] Coro::Task...>>> + run_parallel_structured() + { + constexpr std::size_t n = sizeof...(Subs); + static_assert(n > 0, "run_parallel_structured needs >= 1 sub"); + if (m_ctx == nullptr) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "run_parallel_structured: no active ExecutionContext")); + } + if (m_depth + 1 > m_ctx->limits().max_hierarchy_depth) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_structured: max_hierarchy_depth exceeded")); + } + if (!m_ctx->try_acquire_child_regions(n)) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_structured: max_child_regions exceeded")); + } + + struct RegionGuard { + Detail::ExecutionContext* ctx; + std::size_t count; + ~RegionGuard() { ctx->release_child_regions(count); } + } guard{m_ctx.get(), n}; + + std::stop_source group_stop; + std::optional>> link; + if (state_stop_token().stop_possible()) { + link.emplace(state_stop_token(), + [&group_stop] { group_stop.request_stop(); }); + } + + auto children = std::make_shared>(); + std::apply( + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, &group_stop), + ...); + }, + *children); + + struct Latch { + std::size_t remaining; + std::coroutine_handle<> waiter{}; + Async::Executor* exec; + std::stop_source* stop_src; + std::shared_ptr keep_alive; + std::optional fault{}; + + void arrive(std::size_t, Status st, + std::optional err) + { + if (st == Status::Faulted && !fault.has_value()) { + fault = err.value_or( + FsmError{"parallel child faulted"}); + if (stop_src != nullptr) { + stop_src->request_stop(); + } + } + if (--remaining == 0 && waiter) { + exec->post_completion(waiter); + } + } + }; + auto latch = std::make_shared( + n, std::coroutine_handle<>{}, &m_ctx->active_executor(), + &group_stop, children); + + std::size_t idx = 0; + std::apply( + [&](auto&... c) { + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), + ...); + }, + *children); + + co_await Detail::LatchResumeAwaiter{ + latch->remaining == 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; + link.reset(); + + if (latch->fault.has_value()) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::fault, latch->fault->message)); + } + + co_return std::apply( + [](auto&... c) { + return std::tuple...>{ + c.template take_outcome()...}; + }, + *children); + } + + /// Structured race-any: picks earliest finisher with deterministic + /// child-declaration-order tie-break within the same dispatch turn, + /// requests stop on all losers, and ALWAYS joins EVERY loser before + /// returning. Application Failure can win; system Fault is returned + /// as supervisory error. + template + [[nodiscard]] Coro::Task...>>> + run_parallel_any_structured() + { + constexpr std::size_t n = sizeof...(Subs); + static_assert(n > 0, + "run_parallel_any_structured needs >= 1 sub"); + if (m_ctx == nullptr) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "run_parallel_any_structured: no active ExecutionContext")); + } + if (m_depth + 1 > m_ctx->limits().max_hierarchy_depth) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_any_structured: max_hierarchy_depth exceeded")); + } + if (!m_ctx->try_acquire_child_regions(n)) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "run_parallel_any_structured: max_child_regions exceeded")); + } + + struct RegionGuard { + Detail::ExecutionContext* ctx; + std::size_t count; + ~RegionGuard() { ctx->release_child_regions(count); } + } guard{m_ctx.get(), n}; + + std::stop_source race_stop; + std::optional>> link; + if (state_stop_token().stop_possible()) { + link.emplace(state_stop_token(), + [&race_stop] { race_stop.request_stop(); }); + } + + auto children = std::make_shared>(); + std::apply( + [&](auto&... c) { + (c.attach(m_ctx, m_services, m_depth + 1, &race_stop), + ...); + }, + *children); + + struct Latch { + std::size_t remaining; + bool woke_first{false}; + std::coroutine_handle<> waiter{}; + Detail::ExecutionContext* ctx; + Async::Executor* exec; + std::shared_ptr keep_alive; + std::array completed{}; + std::array turns{}; + std::array statuses{}; + std::array, n> faults{}; + + void arrive(std::size_t idx, Status st, + std::optional err) + { + completed[idx] = true; + turns[idx] = ctx->dispatch_turn(); + statuses[idx] = st; + faults[idx] = std::move(err); + --remaining; + if (!woke_first) { + woke_first = true; + if (waiter) { + auto w = std::exchange(waiter, {}); + exec->post_completion(w); + } + } else if (remaining == 0 && waiter) { + auto w = std::exchange(waiter, {}); + exec->post_completion(w); + } + } + + [[nodiscard]] std::size_t pick_winner() const noexcept + { + std::uint64_t min_turn = + std::numeric_limits::max(); + for (std::size_t i = 0; i < n; ++i) { + if (completed[i] && turns[i] < min_turn) { + min_turn = turns[i]; + } + } + for (std::size_t i = 0; i < n; ++i) { + if (completed[i] && turns[i] == min_turn) { + return i; + } + } + return 0; + } + }; + auto latch = std::make_shared( + n, false, std::coroutine_handle<>{}, m_ctx.get(), + &m_ctx->active_executor(), children); + + std::size_t idx = 0; + std::apply( + [&](auto&... c) { + (Async::spawn( + m_ctx->active_executor(), + drive_child_task(&c, latch, idx++)), + ...); + }, + *children); + + // Wait until at least one child has completed. + co_await Detail::LatchResumeAwaiter{ + latch->woke_first, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; + + // Select deterministic winner (earliest turn, declaration + // order tie-break), then cancel and join EVERY loser. + const std::size_t winner = latch->pick_winner(); + race_stop.request_stop(); + + co_await Detail::LatchResumeAwaiter{ + latch->remaining == 0, + [latch](std::coroutine_handle<> h) { latch->waiter = h; }}; + link.reset(); + + if (latch->statuses[winner] == Status::Faulted) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::fault, + latch->faults[winner] + ? latch->faults[winner]->message + : std::string{"winning race child faulted"})); + } + + co_return [&](std::index_sequence) + -> std::variant...> { + std::variant...> v; + ((I == winner ? (void)(v.template emplace( + std::get(*children) + .template take_outcome())) + : void()), + ...); + return v; + }(std::index_sequence_for{}); + } + template [[nodiscard]] StateKey start_machine(Args&&... args) { @@ -965,11 +1494,9 @@ namespace Void::Fsm auto launcher = [this, ... data = std::forward( args)]() mutable -> Coro::Task { - // Run Sub on the shared executor. Startup data (if any) is - // delivered to Sub's initial-state startup-entry via an - // injector, not the constructor. Sub child; - child.attach(m_ctx, m_services); + child.attach(m_ctx, m_services, m_depth + 1, + m_active_state_stop); if constexpr (sizeof...(Args) > 0) { child.m_startup_injector = [... d = std::move(data)]( @@ -1018,12 +1545,6 @@ namespace Void::Fsm return m_names[static_cast(idx)]; } - /// Active state chain (root → leaf). When a child region is - /// running (run_region), its path is appended, so a composite - /// state reports {composite, ...child leaf}. Unlike the lock-free - /// current_state(), the region part is consumer-consistent: read - /// it from within the machine or once it has settled (it is - /// deterministic in embedder/pump mode). [[nodiscard]] std::vector state_path() const { std::vector path; @@ -1039,20 +1560,12 @@ namespace Void::Fsm return path; } - /// All registered state names (registration order). [[nodiscard]] const std::vector& state_names() const noexcept { return m_names; } - // ── introspection / diagram ─────────────────────────────────── - // StateInfo is namespace-scope (Detail/Introspect.hpp). - - /// Structural description: every registered state (name + whether - /// it is the initial state). Transitions are chosen imperatively - /// inside each state's entry, so they are not statically knowable — - /// the description is node-level (no edges). [[nodiscard]] std::vector describe() { std::vector out; @@ -1068,14 +1581,13 @@ namespace Void::Fsm return out; } - /// Render describe() as a Mermaid stateDiagram-v2 string. [[nodiscard]] std::string to_mermaid() { const auto states = describe(); return Detail::to_mermaid(states); } - // ── persistence ─────────────────────────────────────────────── + // ── legacy persistence & boundary checkpoints ───────────────── [[nodiscard]] Json::Value serialize() const { auto obj = Json::object(); @@ -1090,7 +1602,7 @@ namespace Void::Fsm [[nodiscard]] std::expected restore(const Json::Value& state) { - if (m_status.load() != Status::Idle) { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { return std::unexpected{ FsmError{"restore requires an un-started machine"}}; } @@ -1111,22 +1623,308 @@ namespace Void::Fsm return {}; } + /// Request a bounded checkpoint at the next clean state boundary + /// or application safe_point(). Never captures mid-turn live frames. + [[nodiscard]] Coro::Task> + request_checkpoint(Async::OperationOptions opts = {}) + { + if (opts.stop.stop_requested()) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "request_checkpoint: cancelled before scheduling")); + } + const auto st = m_status.load(std::memory_order_acquire); + if (st == Status::Idle) { + co_return build_checkpoint( + m_initial != nullptr ? durable_id_for(m_initial) + : std::string{}, + m_restored_resume_label); + } + if (terminal(st) || m_ctx == nullptr) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "request_checkpoint: machine is already terminal")); + } + if (opts.deadline.has_value() && + m_ctx->clock().now() >= *opts.deadline) { + co_return Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "request_checkpoint: deadline already expired")); + } + + struct RequestState { + bool settled{false}; + Void::Result::Result result{ + Void::Result::fail(make_fsm_error( + FsmErrorCode::internal, "unsettled"))}; + std::coroutine_handle<> waiter{}; + Async::Executor* exec{nullptr}; + Detail::ExecutionContext::TimerId timer{0}; + }; + auto req = std::make_shared(); + req->exec = &m_ctx->active_executor(); + + std::optional>> stop_cb; + if (opts.stop.stop_possible()) { + stop_cb.emplace(opts.stop, [ctx = m_ctx.get(), req] { + (void)ctx->try_post_control([req] { + if (req->settled) return; + req->settled = true; + req->result = Void::Result::fail(make_fsm_error( + FsmErrorCode::cancelled, + "request_checkpoint: cancelled")); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + }); + }); + } + + auto pending_entry = PendingCheckpoint{ + .settle = + [ctx = m_ctx.get(), req]( + Void::Result::Result r) { + if (req->settled) return false; + req->settled = true; + if (req->timer != 0) { + ctx->cancel_timer(req->timer); + req->timer = 0; + } + req->result = std::move(r); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + return true; + }, + .is_done = [req] { return req->settled; }}; + + auto post_res = m_ctx->try_post_control( + [this, ctx = m_ctx.get(), req, opts, + entry = std::move(pending_entry)]() mutable { + if (req->settled) { + return; + } + if (terminal(m_status.load(std::memory_order_acquire))) { + req->settled = true; + req->result = Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "request_checkpoint: machine finished before boundary")); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + return; + } + if (opts.deadline.has_value()) { + auto t = ctx->try_add_timer( + *opts.deadline, [req] { + if (req->settled) return; + req->settled = true; + req->result = + Void::Result::fail(make_fsm_error( + FsmErrorCode::timeout, + "request_checkpoint: boundary not reached before deadline")); + if (req->waiter) { + req->exec->post_completion(req->waiter); + } + }); + if (t) { + req->timer = *t; + } + } + m_pending_checkpoints.push_back(std::move(entry)); + }); + if (!post_res) { + stop_cb.reset(); + co_return Void::Result::fail(post_res.error()); + } + + co_await Detail::LatchResumeAwaiter{ + req->settled, + [req](std::coroutine_handle<> h) { req->waiter = h; }}; + stop_cb.reset(); + co_return std::move(req->result); + } + + /// Validate-then-commit restore from a boundary Checkpoint while + /// Idle. Any schema, ID, limit, or migration error leaves this + /// machine completely unchanged. + [[nodiscard]] Void::Result::Result + restore_checkpoint(const Checkpoint& cp, + MigrationFn migrator = nullptr) + { + if (m_status.load(std::memory_order_acquire) != Status::Idle) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::invalid_state, + "restore_checkpoint requires Idle machine")); + } + if (cp.format_version != Checkpoint::kFormatVersion) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_checkpoint: unsupported checkpoint format version")); + } + if (!m_machine_type.empty() && !cp.machine_type.empty() && + cp.machine_type != m_machine_type) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_checkpoint: machine_type mismatch")); + } + if (m_limits.max_checkpoint_bytes > 0 && + Detail::estimate_checkpoint_bytes(cp) > + m_limits.max_checkpoint_bytes) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "restore_checkpoint: checkpoint exceeds max_checkpoint_bytes")); + } + + Json::Value candidate_data = cp.state; + std::string candidate_state_id = cp.state_id; + if (cp.application_schema != m_application_schema) { + if (!migrator) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_checkpoint: schema mismatch and no migrator")); + } + try { + auto mr = migrator(cp.application_schema, + m_application_schema, candidate_data, + candidate_state_id); + if (!mr) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + mr.error().message())); + } + } catch (const std::exception& ex) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + std::string{"restore_checkpoint migrator threw: "} + + ex.what())); + } catch (...) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + "restore_checkpoint migrator threw unknown exception")); + } + } + + const auto idIt = m_id_to_type.find(candidate_state_id); + if (idIt == m_id_to_type.end()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::not_found, + "restore_checkpoint: unknown durable state_id '" + + candidate_state_id + "'")); + } + + try { + auto vr = on_validate_restore(candidate_data); + if (!vr) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + vr.error().message())); + } + } catch (const std::exception& ex) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + std::string{"restore_checkpoint validator threw: "} + + ex.what())); + } catch (...) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + "restore_checkpoint validator threw unknown exception")); + } + + Json::Value rollback_snapshot = Json::object(); + bool has_rollback = false; + try { + on_serialize(rollback_snapshot); + has_rollback = true; + } catch (...) { + } + + try { + on_restore(candidate_data); + } catch (const std::exception& ex) { + if (has_rollback) { + try { + on_restore(rollback_snapshot); + } catch (...) { + } + } + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + std::string{"restore_checkpoint on_restore threw: "} + + ex.what())); + } catch (...) { + if (has_rollback) { + try { + on_restore(rollback_snapshot); + } catch (...) { + } + } + return Void::Result::fail(make_fsm_error( + FsmErrorCode::migration_failed, + "restore_checkpoint on_restore threw unknown exception")); + } + + m_initial = idIt->second; + m_restored_resume_label = cp.resume_label; + m_step = cp.transition_sequence; + return {}; + } + + /// Explicit legacy `{state, data}` reader mapping old state names + /// through an optional migration map into bounded restore_checkpoint. + [[nodiscard]] Void::Result::Result + restore_legacy_checkpoint( + const Json::Value& legacy_json, + const std::unordered_map& + state_id_map = {}, + MigrationFn migrator = nullptr) + { + const auto* st = legacy_json.find("state"); + if (st == nullptr || !st->is_string()) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::schema_mismatch, + "restore_legacy_checkpoint: malformed state field")); + } + std::string mapped_id = st->as_string(); + if (const auto it = state_id_map.find(mapped_id); + it != state_id_map.end()) { + mapped_id = it->second; + } else if (const auto nIt = m_name_to_type.find(mapped_id); + nIt != m_name_to_type.end()) { + mapped_id = durable_id_for(nIt->second); + } + + Checkpoint cp; + cp.format_version = Checkpoint::kFormatVersion; + cp.machine_type = m_machine_type; + cp.application_schema = 1; + if (const auto* sv = legacy_json.find("application_schema"); + sv != nullptr && sv->is_int()) { + cp.application_schema = + static_cast(sv->as_int()); + } + cp.state_id = std::move(mapped_id); + if (const auto* data = legacy_json.find("data")) { + cp.state = *data; + } else { + cp.state = Json::object(); + } + return restore_checkpoint(cp, std::move(migrator)); + } + protected: virtual void on_serialize(Json::Value& /*data*/) const {} virtual void on_restore(const Json::Value& /*data*/) {} + [[nodiscard]] virtual Void::Result::Result + on_validate_restore(const Json::Value& /*data*/) const + { + return {}; + } - /// Machine-level entry/exit hooks (default no-ops; override for - /// machine-wide setup/teardown). `on_machine_enter()` runs once - /// before the initial state is entered; `on_machine_exit()` runs - /// once when the machine reaches a terminal outcome (Success, - /// Failure, or a system Fault). Per-state entry/exit lives on the - /// state itself (State::on_enter()/on_exit()). virtual void on_machine_enter() {} virtual void on_machine_exit() {} - /// Called on every transition (and the initial entry). Default - /// logs at debug; override for custom observability. virtual void on_transition(std::string_view from, std::string_view to) { @@ -1136,18 +1934,49 @@ namespace Void::Fsm private: - template - friend class Machine; // run_child reaches child internals + template friend class Machine; + + struct PendingCheckpoint { + std::function)> + settle; + std::function is_done; + }; + + template + static Coro::Task drive_child_task( + Sub* child, std::shared_ptr latch, std::size_t idx) + { + co_await child->drive(); + latch->arrive(idx, child->status(), child->system_error()); + } void attach(std::shared_ptr ctx, - Service::ServiceRegistry* services) + Service::ServiceRegistry* services, + std::size_t depth = 1, + std::stop_source* parent_stop = nullptr) { m_ctx = std::move(ctx); m_owns_ctx = false; + m_depth = depth; + if (m_ctx != nullptr) { + m_limits = m_ctx->limits(); + } if (services != nullptr) { m_services = services; } - m_status.store(Status::Running); + m_termination_reason.store(TerminationReason::none, + std::memory_order_release); + m_root_stop.emplace(); + m_parent_stop_link.reset(); + if (parent_stop != nullptr) { + m_parent_stop_link.emplace( + parent_stop->get_token(), [this] { + if (m_root_stop) { + m_root_stop->request_stop(); + } + }); + } + m_status.store(Status::Running, std::memory_order_release); } template [[nodiscard]] std::string state_name() @@ -1159,6 +1988,22 @@ namespace Void::Fsm #endif } + template + [[nodiscard]] static std::string + default_state_id(const std::string& fallback_name) + { +#ifdef VOID_HAS_FSM_REFLECTION + constexpr auto id_ann = + Void::Meta::annotation_of(^^S); + if constexpr (id_ann.has_value()) { + if (!id_ann->value.view().empty()) { + return std::string{id_ann->value.view()}; + } + } +#endif + return fallback_name; + } + [[nodiscard]] std::string state_name_for(const std::type_info* type) const { @@ -1169,6 +2014,104 @@ namespace Void::Fsm return {}; } + [[nodiscard]] std::string + durable_id_for(const std::type_info* type) const + { + if (type == nullptr) { + return {}; + } + if (const auto it = m_type_to_id.find(std::type_index{*type}); + it != m_type_to_id.end()) { + return it->second; + } + return state_name_for(type); + } + + [[nodiscard]] std::string current_durable_id() const + { + const int idx = m_current.load(std::memory_order_acquire); + if (idx < 0 || idx >= static_cast(m_names.size())) { + return {}; + } + if (const auto nIt = + m_name_to_type.find(m_names[static_cast(idx)]); + nIt != m_name_to_type.end()) { + return durable_id_for(nIt->second); + } + return m_names[static_cast(idx)]; + } + + [[nodiscard]] Void::Result::Result + build_checkpoint(std::string state_id, + std::string resume_label = {}) const + { + Checkpoint cp; + cp.format_version = Checkpoint::kFormatVersion; + cp.machine_type = m_machine_type; + cp.application_schema = m_application_schema; + cp.transition_sequence = m_step; + cp.state_id = std::move(state_id); + cp.resume_label = std::move(resume_label); + Json::Value data = Json::object(); + try { + on_serialize(data); + } catch (const std::exception& ex) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + std::string{"on_serialize threw: "} + ex.what())); + } catch (...) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "on_serialize threw unknown exception")); + } + cp.state = std::move(data); + if (m_limits.max_checkpoint_bytes > 0 && + Detail::estimate_checkpoint_bytes(cp) > + m_limits.max_checkpoint_bytes) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "checkpoint exceeds max_checkpoint_bytes")); + } + return cp; + } + + void fulfill_pending_checkpoints(const std::string& next_state_id, + const std::string& resume_label) + { + if (m_pending_checkpoints.empty()) { + return; + } + auto pending = std::move(m_pending_checkpoints); + m_pending_checkpoints.clear(); + for (auto& p : pending) { + if (p.is_done && p.is_done()) { + continue; + } + (void)p.settle(build_checkpoint(next_state_id, resume_label)); + } + } + + void reject_pending_checkpoints(const Void::Result::Error& err) + { + if (m_pending_checkpoints.empty()) { + return; + } + auto pending = std::move(m_pending_checkpoints); + m_pending_checkpoints.clear(); + for (auto& p : pending) { + if (p.is_done && p.is_done()) { + continue; + } + (void)p.settle(Void::Result::fail(err)); + } + } + + void record_observer_error(std::string msg) + { + std::lock_guard lk{m_obs_mu}; + m_observer_errors.push_back(std::move(msg)); + } + void set_current(const std::type_info* type) { std::string from = current_state(); @@ -1178,52 +2121,120 @@ namespace Void::Fsm } std::string to = current_state(); ++m_step; - on_transition(from, to); const Transition t{from, to, m_step}; - if (m_observer) { - m_observer(t); + + std::function observer_copy; + std::vector interceptors_copy; + { + std::lock_guard lk{m_obs_mu}; + if (m_limits.max_retained_transitions > 0) { + m_transition_history.push_back(t); + while (m_transition_history.size() > + m_limits.max_retained_transitions) { + m_transition_history.pop_front(); + } + } + observer_copy = m_observer; + interceptors_copy = m_interceptors; } - for (const auto& interceptor : m_interceptors) { + + try { + on_transition(from, to); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"on_transition: "} + ex.what()); + } catch (...) { + record_observer_error("on_transition: unknown exception"); + } + if (observer_copy) { + try { + observer_copy(t); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"observer: "} + ex.what()); + } catch (...) { + record_observer_error("observer: unknown exception"); + } + } + for (const auto& interceptor : interceptors_copy) { if (interceptor.before) { - interceptor.before(t); + try { + interceptor.before(t); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"interceptor.before: "} + + ex.what()); + } catch (...) { + record_observer_error( + "interceptor.before: unknown exception"); + } } } } void fire_after(std::string_view state) { - for (const auto& interceptor : m_interceptors) { + std::vector interceptors_copy; + { + std::lock_guard lk{m_obs_mu}; + interceptors_copy = m_interceptors; + } + for (const auto& interceptor : interceptors_copy) { if (interceptor.after) { - interceptor.after(state); + try { + interceptor.after(state); + } catch (const std::exception& ex) { + record_observer_error( + std::string{"interceptor.after: "} + + ex.what()); + } catch (...) { + record_observer_error( + "interceptor.after: unknown exception"); + } } } } - // Record a system fault (programming error) — separate from a - // typed Failure result. Sets status Faulted + system_error. void fault(std::string message) { m_system_error = FsmError{std::move(message)}; + if (m_termination_reason.load(std::memory_order_acquire) == + TerminationReason::none) { + m_termination_reason.store(TerminationReason::faulted, + std::memory_order_release); + } Void::Log::error("Fsm", "system fault: {}", m_system_error->message); m_status.store(Status::Faulted, std::memory_order_release); + reject_pending_checkpoints(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "machine faulted before checkpoint boundary")); } - // The state loop. Type-erased: stores the Success/Failure payload - // in m_result_value and sets m_status; the typed Outcome is rebuilt - // in take_outcome() where Derived is complete. Runs on the - // executor. Coro::Task drive() { const std::type_info* cur = m_initial; if (cur == nullptr) { fault("no initial state"); + m_parent_stop_link.reset(); co_return; } on_machine_enter(); bool first = true; for (;;) { - // Apply an external jump() at this transition boundary. + if (m_root_stop && m_root_stop->stop_requested()) { + m_termination_reason.store( + m_root_timeout.load(std::memory_order_acquire) + ? TerminationReason::timed_out + : TerminationReason::cancelled, + std::memory_order_release); + fault(m_root_timeout.load(std::memory_order_acquire) + ? "deadline expired" + : "cancelled"); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } if (const auto* j = m_jump.exchange(nullptr, std::memory_order_acq_rel); j != nullptr) { @@ -1235,37 +2246,124 @@ namespace Void::Fsm if (it == m_factories.end()) { fault("transition to unregistered state"); on_machine_exit(); + m_parent_stop_link.reset(); co_return; } + + // Boundary checkpoint right before next state enters and + // causes effects (note: during initial entry this captures + // clean entry state). + if (m_ctx != nullptr) { + m_ctx->drain_control_queue(); + } + fulfill_pending_checkpoints(durable_id_for(cur), {}); + set_current(cur); auto state = it->second(); - co_await state->on_enter(); - // Decide how the state runs: a launched sub's result (via - // the bound dispatcher), the startup injector for the first - // state, or the signature-inferred driver thunk. + + const auto state_scope = m_ctx->allocate_scope(); + std::stop_source state_stop; + std::optional>> + root_to_state; + if (m_root_stop.has_value()) { + root_to_state.emplace( + m_root_stop->get_token(), + [&state_stop] { state_stop.request_stop(); }); + } + m_active_scope = state_scope; + m_active_state_stop = &state_stop; + StateKey step; - if (m_pending_dispatch) { - LaunchResult pending = std::move(*m_pending_result); - auto dispatch = std::move(m_pending_dispatch); - m_pending_result.reset(); - m_pending_dispatch = nullptr; - if (pending.kind == LaunchResult::Kind::Fault) { - fault(std::move(pending.fault.message)); - on_machine_exit(); - co_return; + bool body_failed = false; + bool body_cancelled = false; + std::string body_error; + + try { + co_await state->on_enter(); + if (m_pending_dispatch) { + LaunchResult pending = std::move(*m_pending_result); + auto dispatch = std::move(m_pending_dispatch); + m_pending_result.reset(); + m_pending_dispatch = nullptr; + if (pending.kind == LaunchResult::Kind::Fault) { + body_failed = true; + body_error = std::move(pending.fault.message); + } else { + step = co_await dispatch(*state, + std::move(pending)); + } + } else if (first && m_startup_injector) { + auto inject = std::move(m_startup_injector); + m_startup_injector = nullptr; + step = co_await inject(*state); + } else { + step = co_await m_drivers.at(std::type_index{*cur})( + *state); } - step = co_await dispatch(*state, std::move(pending)); - } else if (first && m_startup_injector) { - auto inject = std::move(m_startup_injector); - m_startup_injector = nullptr; - step = co_await inject(*state); - } else { - step = co_await m_drivers.at(std::type_index{*cur})( - *state); + } catch (const Detail::CancelledException&) { + body_cancelled = true; + } catch (const std::exception& ex) { + body_failed = true; + body_error = ex.what(); + } catch (...) { + body_failed = true; + body_error = "state execution threw unknown exception"; } first = false; - co_await state->on_exit(); + + // Scope exit before on_exit() and state destruction: stop + // child scope, cancel waiters, and purge timers. + m_active_state_stop = nullptr; + state_stop.request_stop(); + root_to_state.reset(); + if (m_ctx != nullptr) { + m_ctx->cancel_scope(state_scope); + m_ctx->purge_scope(state_scope); + } + m_active_scope = Detail::ExecutionContext::kNoScope; + + bool exit_failed = false; + std::string exit_error; + try { + co_await state->on_exit(); + } catch (const std::exception& ex) { + exit_failed = true; + exit_error = + std::string{"on_exit threw: "} + ex.what(); + } catch (...) { + exit_failed = true; + exit_error = "on_exit threw unknown exception"; + } + state.reset(); fire_after(current_state()); + + if (exit_failed) { + fault(std::move(exit_error)); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } + if (body_cancelled || + (m_root_stop && m_root_stop->stop_requested())) { + m_termination_reason.store( + m_root_timeout.load(std::memory_order_acquire) + ? TerminationReason::timed_out + : TerminationReason::cancelled, + std::memory_order_release); + fault(m_root_timeout.load(std::memory_order_acquire) + ? "deadline expired" + : "cancelled"); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } + if (body_failed) { + fault(std::move(body_error)); + on_machine_exit(); + m_parent_stop_link.reset(); + co_return; + } + switch (step.kind()) { case StateKey::Kind::Transition: cur = step.target(); @@ -1278,20 +2376,35 @@ namespace Void::Fsm continue; case StateKey::Kind::Success: m_result_value = std::move(step.payload()); + m_termination_reason.store( + TerminationReason::succeeded, + std::memory_order_release); m_status.store(Status::Succeeded, std::memory_order_release); + reject_pending_checkpoints(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "machine succeeded before checkpoint boundary")); on_machine_exit(); + m_parent_stop_link.reset(); co_return; case StateKey::Kind::Fail: m_result_value = std::move(step.payload()); + m_termination_reason.store( + TerminationReason::failed, + std::memory_order_release); m_status.store(Status::Failed, std::memory_order_release); + reject_pending_checkpoints(make_fsm_error( + FsmErrorCode::checkpoint_rejected, + "machine failed before checkpoint boundary")); on_machine_exit(); + m_parent_stop_link.reset(); co_return; case StateKey::Kind::Fault: fault(std::any_cast(step.payload()) .message); on_machine_exit(); + m_parent_stop_link.reset(); co_return; } } @@ -1300,15 +2413,11 @@ namespace Void::Fsm Coro::Task driver() { co_await drive(); - if (m_owns_ctx) { + if (m_owns_ctx && m_ctx) { m_ctx->finish(); } } - // Rebuild the typed Outcome from the type-erased result. Function - // template so SuccessOf/FailureOf resolve where Derived is - // complete. A system fault yields a default-constructed error arm - // (consult system_error()). template Outcome take_outcome() { using Succ = Detail::SuccessOf; @@ -1330,7 +2439,7 @@ namespace Void::Fsm std::unexpect, std::any_cast(m_result_value)}; } - default: // Faulted / not finished + default: static_assert( std::is_default_constructible_v, "a machine with a non-default-constructible " @@ -1342,6 +2451,9 @@ namespace Void::Fsm } Options m_options; + FsmLimits m_limits{}; + bool m_has_explicit_limits{false}; + std::size_t m_depth{0}; std::shared_ptr m_ctx; bool m_owns_ctx{false}; Service::ServiceRegistry* m_services{nullptr}; @@ -1350,7 +2462,6 @@ namespace Void::Fsm std::type_index, std::function()>> m_factories; - // Per-state signature-inferred driver thunk (runs the entry). std::unordered_map< std::type_index, std::function(Detail::StateBase&)>> @@ -1359,43 +2470,45 @@ namespace Void::Fsm std::vector m_names; std::unordered_map m_name_to_type; + std::unordered_map m_type_to_id; + std::unordered_map m_id_to_type; const std::type_info* m_initial{nullptr}; + std::string m_machine_type; + std::uint32_t m_application_schema{1}; + std::string m_restored_resume_label; std::atomic m_current{-1}; std::atomic m_status{Status::Idle}; - // Type-erased finished result (Success or Failure payload), rebuilt - // typed in take_outcome(); system faults in m_system_error. + std::atomic m_termination_reason{ + TerminationReason::none}; std::any m_result_value; std::optional m_system_error; + + mutable std::mutex m_obs_mu; std::function m_observer; std::vector m_interceptors; + std::deque m_transition_history; + std::vector m_observer_errors; std::uint64_t m_step{0}; - // Active child region's path provider (run_region); consulted by - // state_path(). Set/cleared on the consumer thread. std::function()> m_region_probe; - - // Per-region-type snapshot of the leaf last reached, for - // Resume::History re-entry. std::unordered_map m_region_history; - // Set by a Launch step's sub-machine result; consumed by the next - // state via the bound dispatcher below. std::optional m_pending_result; StateKey::Dispatch m_pending_dispatch; - - // Seeds the initial state's startup-entry with launch data (set by - // the parent's launcher before driving this machine). std::function(Detail::StateBase&)> m_startup_injector; - // External jump request (jump()); applied by drive() at the - // next transition boundary. std::atomic m_jump{nullptr}; + std::optional m_root_stop; + std::optional>> + m_parent_stop_link; + std::atomic m_root_timeout{false}; + Detail::ExecutionContext::ScopeId m_active_scope{ + Detail::ExecutionContext::kNoScope}; + std::stop_source* m_active_state_stop{nullptr}; - // The owned top-level driver coroutine (worker mode). Holding it - // (rather than detaching via Async::spawn) lets stop() destroy the - // suspended frame chain of a machine parked on an event. + std::vector m_pending_checkpoints; std::optional> m_driver; }; template using State = Machine::State; diff --git a/include/Void/Fsm/Orchestrator.hpp b/include/Void/Fsm/Orchestrator.hpp index fb8b344..3733846 100644 --- a/include/Void/Fsm/Orchestrator.hpp +++ b/include/Void/Fsm/Orchestrator.hpp @@ -1,27 +1,73 @@ #pragma once #include +#include #include +#include +#include +#include #include +#include +#include #include #include +#include +#include #include #include namespace Void::Fsm { + enum class SupervisionMode : std::uint8_t { + StopOnFault = 0, + BoundedRestart + }; + + struct SupervisionPolicy { + SupervisionMode mode{SupervisionMode::StopOnFault}; + std::size_t max_restarts{3}; + std::chrono::nanoseconds restart_window{std::chrono::seconds{60}}; + std::chrono::nanoseconds initial_backoff{ + std::chrono::milliseconds{10}}; + }; + + struct OrchestratorLimits { + std::size_t max_supervised{1024}; + }; + + struct SupervisionEvent { + enum class Kind : std::uint8_t { + Launched = 0, + RestartScheduled, + Restarted, + Released, + Exhausted + }; + Kind kind{Kind::Launched}; + Status status{Status::Idle}; + TerminationReason reason{TerminationReason::none}; + std::size_t restarts{0}; + std::string detail{}; + }; + namespace Detail { // Type-erased supervised FSM. Models wrap a concrete Machine - // subclass; the orchestrator only needs lifecycle + status. + // subclass; the orchestrator drives lifecycle, status, and bounded + // restart. class FsmConcept { public: virtual ~FsmConcept() = default; virtual void stop() = 0; + virtual void restart() = 0; [[nodiscard]] virtual Status status() const = 0; + [[nodiscard]] virtual TerminationReason + termination_reason() const = 0; + [[nodiscard]] virtual std::optional + system_error() const = 0; }; template class FsmModel final : public FsmConcept @@ -34,10 +80,21 @@ namespace Void::Fsm } void stop() override { m_fsm->stop(); } + void restart() override { m_fsm->restart(); } [[nodiscard]] Status status() const override { return m_fsm->status(); } + [[nodiscard]] TerminationReason + termination_reason() const override + { + return m_fsm->termination_reason(); + } + [[nodiscard]] std::optional + system_error() const override + { + return m_fsm->system_error(); + } [[nodiscard]] F& get() noexcept { return *m_fsm; } @@ -45,10 +102,27 @@ namespace Void::Fsm std::unique_ptr m_fsm; }; + + struct SupervisedEntry { + std::shared_ptr model; + SupervisionPolicy policy{}; + std::vector + restart_timestamps; + std::optional + next_restart_at; + std::atomic restarts{0}; + mutable std::mutex evidence_mu; + bool released{false}; + Status final_status{Status::Idle}; + TerminationReason final_reason{TerminationReason::none}; + std::optional final_error{}; + }; } // namespace Detail - /// A non-owning supervision handle to a launched FSM: query status and - /// stop it. The Orchestrator owns the FSM's lifetime. + /// Owning handle to a supervised FSM instance: holds a shared_ptr so + /// immutable termination evidence and any still-required cleanup ownership + /// survive even after the Orchestrator releases a finished entry from + /// active supervision. class FsmHandle { public: @@ -57,48 +131,92 @@ namespace Void::Fsm void stop() const { - if (m_impl) { - m_impl->stop(); + if (m_entry && m_entry->model) { + m_entry->model->stop(); } } [[nodiscard]] Status status() const { - return m_impl ? m_impl->status() : Status::Idle; + if (!m_entry) { + return Status::Idle; + } + std::lock_guard lk{m_entry->evidence_mu}; + if (m_entry->released) { + return m_entry->final_status; + } + return m_entry->model ? m_entry->model->status() : Status::Idle; } - [[nodiscard]] bool finished() const + [[nodiscard]] bool finished() const { return terminal(status()); } + + [[nodiscard]] TerminationReason termination_reason() const { - const auto s = status(); - return s == Status::Succeeded || s == Status::Failed; + if (!m_entry) { + return TerminationReason::none; + } + std::lock_guard lk{m_entry->evidence_mu}; + if (m_entry->released) { + return m_entry->final_reason; + } + return m_entry->model ? m_entry->model->termination_reason() + : TerminationReason::none; + } + + [[nodiscard]] std::optional system_error() const + { + if (!m_entry) { + return std::nullopt; + } + std::lock_guard lk{m_entry->evidence_mu}; + if (m_entry->released) { + return m_entry->final_error; + } + return m_entry->model ? m_entry->model->system_error() + : std::nullopt; + } + + [[nodiscard]] std::size_t restart_count() const noexcept + { + return m_entry + ? m_entry->restarts.load(std::memory_order_acquire) + : 0; } [[nodiscard]] explicit operator bool() const noexcept { - return m_impl != nullptr; + return m_entry != nullptr && m_entry->model != nullptr; } private: friend class Orchestrator; - explicit FsmHandle(std::shared_ptr impl) - : m_impl(std::move(impl)) + explicit FsmHandle(std::shared_ptr entry) + : m_entry(std::move(entry)) { } - std::shared_ptr m_impl; + std::shared_ptr m_entry; }; // ── Orchestrator ────────────────────────────────────────────────────── - // Owns a ServiceRegistry and supervises a set of FSM instances. Each - // launched FSM is injected with the registry as its context, so its - // states resolve dependencies by interface (no concrete coupling), and - // is started immediately. stop_all() winds everything down. class Orchestrator { public: - Orchestrator() = default; + using ObserverCallback = + std::function; + + explicit Orchestrator( + const Time::MonotonicClock* clock = nullptr, + OrchestratorLimits limits = {}) noexcept + : m_clock(clock != nullptr + ? clock + : &Time::SystemMonotonicClock::instance()), + m_limits(limits) + { + } + ~Orchestrator() { stop_all(); } Orchestrator(const Orchestrator&) = delete; @@ -109,8 +227,6 @@ namespace Void::Fsm return m_registry; } - /// Call on_start() on lifecycle services. Call before launching - /// FSMs that expect started services. void start_services() { m_registry.start_all(); @@ -118,36 +234,177 @@ namespace Void::Fsm m_services_stopped = false; } - /// Construct F, inject the registry, start it, and supervise. - /// F must derive Fsm::Machine<...> (provides set_services / - /// start / stop / status). + template + [[nodiscard]] Void::Result::Result + try_launch(SupervisionPolicy policy, Args&&... args) + { + std::vector observers_copy; + std::shared_ptr entry; + { + reap_finished_and_notify(); + std::lock_guard lock{m_mutex}; + if (m_limits.max_supervised > 0 && + m_entries.size() >= m_limits.max_supervised) { + return Void::Result::fail(make_fsm_error( + FsmErrorCode::limit_exceeded, + "Orchestrator: max_supervised limit reached")); + } + auto fsm = + std::make_unique(std::forward(args)...); + fsm->set_services(m_registry); + fsm->start(); + auto model = + std::make_shared>(std::move(fsm)); + entry = std::make_shared(); + entry->model = std::move(model); + entry->policy = policy; + m_entries.push_back(entry); + } + + notify_observers(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Launched, + .status = entry->model->status(), + .reason = entry->model->termination_reason(), + .restarts = 0, + .detail = {}}); + return FsmHandle{std::move(entry)}; + } + template FsmHandle launch(Args&&... args) { - auto fsm = std::make_unique(std::forward(args)...); - fsm->set_services(m_registry); - fsm->start(); - auto model = - std::make_shared>(std::move(fsm)); - std::lock_guard lock{m_mutex}; - m_running.push_back(model); - return FsmHandle{model}; + auto r = try_launch(SupervisionPolicy{}, + std::forward(args)...); + return r ? *r : FsmHandle{}; } - /// Stop and release every supervised FSM, then stop services. - void stop_all() + /// Drive supervision rules (bounded restarts with injected Time + /// backoff, and releasing terminal entries while handles keep + /// immutable evidence). Returns actions taken (restarts + releases). + std::size_t supervise_step() { - std::vector> running; + std::vector events; + std::vector> + to_restart; + const auto now = m_clock->now(); + { std::lock_guard lock{m_mutex}; - running.swap(m_running); + for (auto it = m_entries.begin(); it != m_entries.end();) { + auto& e = *it; + const auto st = e->model->status(); + if (!terminal(st)) { + ++it; + continue; + } + + if (e->policy.mode == SupervisionMode::BoundedRestart && + st == Status::Faulted) { + std::erase_if( + e->restart_timestamps, [&](const auto ts) { + return (now - ts) >= + e->policy.restart_window; + }); + if (e->restart_timestamps.size() < + e->policy.max_restarts) { + if (!e->next_restart_at.has_value()) { + const std::size_t attempt = + e->restart_timestamps.size(); + const auto shift = + attempt < 16 ? attempt : 16; + const auto backoff = + e->policy.initial_backoff * + (std::size_t{1} << shift); + e->next_restart_at = now + backoff; + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind:: + RestartScheduled, + .status = st, + .reason = + e->model->termination_reason(), + .restarts = e->restarts.load( + std::memory_order_acquire), + .detail = e->model->system_error() + ? e->model->system_error() + ->message + : std::string{}}); + ++it; + continue; + } + if (now < *e->next_restart_at) { + ++it; + continue; + } + e->restart_timestamps.push_back(now); + e->next_restart_at.reset(); + e->restarts.fetch_add( + 1, std::memory_order_acq_rel); + to_restart.push_back(e); + ++it; + continue; + } + + snapshot_released_evidence(*e); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Exhausted, + .status = e->final_status, + .reason = e->final_reason, + .restarts = + e->restarts.load(std::memory_order_acquire), + .detail = + e->final_error + ? e->final_error->message + : std::string{"restart budget exhausted"}}); + it = m_entries.erase(it); + continue; + } + + snapshot_released_evidence(*e); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Released, + .status = e->final_status, + .reason = e->final_reason, + .restarts = + e->restarts.load(std::memory_order_acquire), + .detail = e->final_error ? e->final_error->message + : std::string{}}); + it = m_entries.erase(it); + } } - for (auto& m : running) { - m->stop(); + + for (auto& e : to_restart) { + e->model->restart(); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Restarted, + .status = e->model->status(), + .reason = e->model->termination_reason(), + .restarts = e->restarts.load(std::memory_order_acquire), + .detail = {}}); + } + + const std::size_t count = events.size(); + for (const auto& ev : events) { + notify_observers(ev); + } + return count; + } + + /// Release finished stop-on-fault (or non-faulted) entries from + /// active supervision while existing handles retain evidence. + std::size_t reap_finished() { return reap_finished_and_notify(); } + + void stop_all() + { + std::vector> running; + { + std::lock_guard lock{m_mutex}; + running.swap(m_entries); + } + for (auto& e : running) { + e->model->stop(); + snapshot_released_evidence(*e); } running.clear(); - // Balance start_services() exactly once (stop_all may run - // explicitly and again from the destructor). if (m_services_started && !m_services_stopped) { m_registry.stop_all(); m_services_stopped = true; @@ -157,16 +414,118 @@ namespace Void::Fsm [[nodiscard]] std::size_t running_count() const { std::lock_guard lock{m_mutex}; - return m_running.size(); + return m_entries.size(); + } + + std::size_t observe_supervision(ObserverCallback cb) + { + std::lock_guard lock{m_obs_mu}; + const std::size_t id = m_next_obs_id++; + m_observers.emplace_back(id, std::move(cb)); + return id; + } + + void remove_supervision_observer(std::size_t id) + { + std::lock_guard lock{m_obs_mu}; + std::erase_if(m_observers, [id](const auto& pair) { + return pair.first == id; + }); + } + + [[nodiscard]] std::vector observer_errors() const + { + std::lock_guard lock{m_obs_mu}; + return m_observer_errors; } private: + static void + snapshot_released_evidence(Detail::SupervisedEntry& entry) + { + std::lock_guard elk{entry.evidence_mu}; + if (entry.released) { + return; + } + entry.final_status = entry.model->status(); + entry.final_reason = entry.model->termination_reason(); + entry.final_error = entry.model->system_error(); + entry.released = true; + } + + std::size_t reap_finished_and_notify() + { + std::vector events; + { + std::lock_guard lock{m_mutex}; + for (auto it = m_entries.begin(); it != m_entries.end();) { + auto& e = *it; + const auto st = e->model->status(); + if (!terminal(st)) { + ++it; + continue; + } + if (e->policy.mode == SupervisionMode::BoundedRestart && + st == Status::Faulted) { + ++it; + continue; + } + snapshot_released_evidence(*e); + events.push_back(SupervisionEvent{ + .kind = SupervisionEvent::Kind::Released, + .status = e->final_status, + .reason = e->final_reason, + .restarts = + e->restarts.load(std::memory_order_acquire), + .detail = e->final_error ? e->final_error->message + : std::string{}}); + it = m_entries.erase(it); + } + } + for (const auto& ev : events) { + notify_observers(ev); + } + return events.size(); + } + + void notify_observers(const SupervisionEvent& ev) + { + std::vector copy; + { + std::lock_guard lock{m_obs_mu}; + copy.reserve(m_observers.size()); + for (const auto& [id, fn] : m_observers) { + if (fn) { + copy.push_back(fn); + } + } + } + for (const auto& fn : copy) { + try { + fn(ev); + } catch (const std::exception& ex) { + std::lock_guard lock{m_obs_mu}; + m_observer_errors.push_back(ex.what()); + } catch (...) { + std::lock_guard lock{m_obs_mu}; + m_observer_errors.push_back("observer threw unknown"); + } + } + } + + const Time::MonotonicClock* m_clock; + OrchestratorLimits m_limits{}; Service::ServiceRegistry m_registry; mutable std::mutex m_mutex; - std::vector> m_running; + std::vector> m_entries; bool m_services_started{false}; bool m_services_stopped{false}; + + mutable std::mutex m_obs_mu; + std::vector> m_observers; + std::vector m_observer_errors; + std::size_t m_next_obs_id{1}; }; } // namespace Void::Fsm diff --git a/include/Void/Fsm/StateKey.hpp b/include/Void/Fsm/StateKey.hpp index 205e9f5..6d42a92 100644 --- a/include/Void/Fsm/StateKey.hpp +++ b/include/Void/Fsm/StateKey.hpp @@ -1,10 +1,22 @@ #pragma once +#include #include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include #include #include +#include +#include #include #include @@ -33,6 +45,153 @@ namespace Void::Fsm Faulted // stopped by a system fault (see system_error()) }; + /// Canonical shared predicate identifying every terminal Status value. + [[nodiscard]] constexpr bool terminal(Status s) noexcept + { + return s == Status::Succeeded || s == Status::Failed || + s == Status::Faulted; + } + + /// Why a machine finished (preserving Status values while distinguishing + /// cooperative cancellation and deadline expiration from application + /// outcomes and system faults). + enum class TerminationReason : std::uint8_t { + none = 0, + succeeded, + failed, + faulted, + cancelled, + timed_out + }; + + enum class FsmErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + invalid_state = 2, + not_found = 3, + overloaded = 4, + cancelled = 5, + timeout = 6, + limit_exceeded = 7, + fault = 8, + checkpoint_rejected = 9, + schema_mismatch = 10, + migration_failed = 11, + service_unavailable = 12, + internal = 13 + }; + + [[nodiscard]] inline Void::Result::Error + make_fsm_error(FsmErrorCode code, std::string message = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case FsmErrorCode::none: + kind = ErrorKind::internal; + break; + case FsmErrorCode::invalid_argument: + kind = ErrorKind::invalid_argument; + break; + case FsmErrorCode::invalid_state: + case FsmErrorCode::checkpoint_rejected: + kind = ErrorKind::conflict; + break; + case FsmErrorCode::not_found: + case FsmErrorCode::service_unavailable: + kind = ErrorKind::not_found; + break; + case FsmErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case FsmErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case FsmErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case FsmErrorCode::limit_exceeded: + kind = ErrorKind::exhausted; + break; + case FsmErrorCode::schema_mismatch: + case FsmErrorCode::migration_failed: + kind = ErrorKind::corrupt; + break; + case FsmErrorCode::fault: + case FsmErrorCode::internal: + kind = ErrorKind::internal; + break; + } + return Error{kind, std::move(message), + ErrorCode{Void::Result::kFsmErrorDomain, + static_cast(code)}}; + } + + /// Explicit resource and scheduling bounds for FSM execution. + struct FsmLimits { + std::size_t max_mailbox_events{1024}; + std::size_t max_mailbox_bytes{std::size_t{4} * 1024 * 1024}; + std::size_t max_deferred_events{256}; + std::size_t max_timers{1024}; + std::size_t max_child_regions{128}; + std::size_t max_hierarchy_depth{32}; + std::size_t max_retained_transitions{256}; + std::size_t max_checkpoint_bytes{std::size_t{4} * 1024 * 1024}; + std::size_t max_events_per_turn{64}; + std::chrono::nanoseconds max_turn_duration{ + std::chrono::milliseconds{1}}; + std::size_t max_control_messages{256}; + }; + + /// Explicit borrowed execution binding passed to Machine::run(). + struct ExecutionBinding { + Async::Executor* executor{nullptr}; + const Time::MonotonicClock* clock{ + &Time::SystemMonotonicClock::instance()}; + FsmLimits limits{}; + }; + + /// Versioned boundary checkpoint capturing machine identity, schema, + /// durable state ID, optional application safe-point resume label, and + /// serialized application state. + struct Checkpoint { + static constexpr std::uint32_t kFormatVersion = 1; + std::uint32_t format_version{kFormatVersion}; + std::string machine_type; + std::uint32_t application_schema{1}; + std::uint64_t transition_sequence{0}; + std::string state_id; + std::string resume_label; + Json::Value state; + }; + + /// Annotation tag specifying a durable state ID (`[[= Void::Fsm::StateId{"..."}]]`). + struct StateId { + Void::Meta::Str value; + }; + + /// Byte-size accounting helper for typed event admission into bounded + /// FSM mailboxes. + template + [[nodiscard]] constexpr std::size_t event_payload_bytes(const E& e) noexcept + { + if constexpr (requires { + { + e.payload_bytes() + } -> std::convertible_to; + }) { + return static_cast(e.payload_bytes()); + } else if constexpr (std::is_same_v, + std::string>) { + return sizeof(E) + e.size(); + } else { + return sizeof(E); + } + } + /// The outcome of a sub-machine launched via startMachine(): /// a typed Success value, a typed Failure value, or a system fault. struct LaunchResult { diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp index 89cb9ba..5d5d703 100644 --- a/src/Fsm/Engine.cpp +++ b/src/Fsm/Engine.cpp @@ -1,22 +1,152 @@ #include +#include #include #include namespace Void::Fsm::Detail { + namespace + { + Coro::Task external_pump_task( + std::weak_ptr 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 StateBase::on_enter() { co_return; } Coro::Task 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 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 + ExecutionContext::try_post_control(std::function 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 types, std::coroutine_handle<> cont, EventEnvelope* slot, bool* timed_out, - std::optional deadline) + std::optional 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 - 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> 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::try_add_timer( + Time::MonotonicClock::time_point deadline, + std::function 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 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::optional ExecutionContext::next_deadline() const { - std::optional next; + std::optional 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> 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(); } diff --git a/src/Fsm/module.cmake b/src/Fsm/module.cmake index cc6af1f..72d3063 100644 --- a/src/Fsm/module.cmake +++ b/src/Fsm/module.cmake @@ -1,3 +1,3 @@ void_add_module(Fsm - INTERNAL_DEPS Async Core Data Functional Log Service + INTERNAL_DEPS Async Core Data Functional Time Log Service ) diff --git a/tests/package/FsmOnly/CMakeLists.txt b/tests/package/FsmOnly/CMakeLists.txt new file mode 100644 index 0000000..e212e09 --- /dev/null +++ b/tests/package/FsmOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidFsmOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Fsm) + +add_executable(void_fsm_only_consumer main.cpp) +target_link_libraries(void_fsm_only_consumer PRIVATE Void::Fsm) +target_compile_features(void_fsm_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME FsmOnlyConsumer COMMAND void_fsm_only_consumer) diff --git a/tests/package/FsmOnly/main.cpp b/tests/package/FsmOnly/main.cpp new file mode 100644 index 0000000..4be33d8 --- /dev/null +++ b/tests/package/FsmOnly/main.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include + +#include + +struct ConsumerMachine : public Void::Fsm::Machine { + using Success = int; + + struct States { + struct Start : State { + Void::Coro::Task run() + { + co_return succeed(42); + } + }; + }; +}; + +Void::Coro::Task drive_consumer_fsm( + Void::Fsm::ExecutionBinding binding, + std::optional>>* out) +{ + ConsumerMachine fsm; + *out = co_await fsm.run(binding); +} + +int main() +{ + if (!Void::Fsm::terminal(Void::Fsm::Status::Faulted)) { + return 1; + } + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + std::optional>> out; + Void::Async::spawn( + exec, + drive_consumer_fsm( + {.executor = &exec, .clock = &clock}, &out)); + (void)exec.drain(); + if (!out.has_value() || !out->has_value() || !out->value().has_value()) { + return 2; + } + return out->value().value() == 42 ? 0 : 3; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 1d00274..e23d018 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -282,6 +282,16 @@ if(_has_configuration_async) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_fsm Fsm Async Core Data Functional Time Log Service) +if(_has_fsm) + run_consumer(FsmOnly "${install_prefix}" "FsmOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/Fsm/FsmHardening.cpp b/tests/standalone/Fsm/FsmHardening.cpp new file mode 100644 index 0000000..07a4d00 --- /dev/null +++ b/tests/standalone/Fsm/FsmHardening.cpp @@ -0,0 +1,1108 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace void_fsm_hardening_test +{ + using Void::Coro::Task; + using Void::Fsm::Checkpoint; + using Void::Fsm::ExecutionBinding; + using Void::Fsm::FsmError; + using Void::Fsm::FsmErrorCode; + using Void::Fsm::FsmLimits; + using Void::Fsm::Machine; + using Void::Fsm::MachineOptions; + using Void::Fsm::Orchestrator; + using Void::Fsm::OrchestratorLimits; + using Void::Fsm::State; + using Void::Fsm::StateId; + using Void::Fsm::StateKey; + using Void::Fsm::Status; + using Void::Fsm::SupervisionEvent; + using Void::Fsm::SupervisionMode; + using Void::Fsm::SupervisionPolicy; + using Void::Fsm::TerminationReason; + using Void::Fsm::Transition; + using namespace std::chrono_literals; + + template + Task assign_task_result(Task task, std::optional* out) + { + *out = co_await task; + } + + template + T drive_task(Void::Async::ManualExecutor& exec, Task task) + { + std::optional out; + Void::Async::spawn(exec, assign_task_result(std::move(task), &out)); + (void)exec.drain(); + return std::move(*out); + } + + struct Ping { + int value{0}; + }; + + struct NeverEvent { + }; + + struct SizedEvent { + std::size_t bytes{0}; + [[nodiscard]] std::size_t payload_bytes() const noexcept + { + return bytes; + } + }; + + // ── Supervision test machines ──────────────────────────────────────── + class FaultingWorker : public Machine + { + public: + + using Success = int; + + struct States { + struct Boom : State { + Task run() + { + throw std::runtime_error("worker fault"); + co_return succeed(0); + } + }; + }; + + explicit FaultingWorker(std::atomic* runs = nullptr) + : m_runs(runs) + { + } + + protected: + + void on_machine_enter() override + { + if (m_runs != nullptr) { + m_runs->fetch_add(1, std::memory_order_acq_rel); + } + } + + private: + + std::atomic* m_runs; + }; + + class ParkedWorker : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + auto r = + co_await await_event_cancellable(); + if (!r) { + co_return succeed(0); + } + co_return succeed(r->value); + } + }; + }; + }; + + template bool wait_handle_finished(const HandleT& h) + { + for (int i = 0; i < 500; ++i) { + if (h.finished()) { + return true; + } + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + return h.finished(); + } + + // ── Scope, timer purge, exit fault, observer isolation ─────────────── + class CancellableWaitFsm : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + auto r = + co_await await_event_cancellable(); + if (!r) { + co_return succeed(-1); + } + co_return succeed(r->value); + } + }; + }; + + CancellableWaitFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class TimerPurgeFsm : public Machine + { + public: + + using Success = int; + + std::atomic* orphaned_timer_fired{nullptr}; + bool* limit_hit{nullptr}; + const Void::Time::MonotonicClock* clock{nullptr}; + + struct States { + struct First : State { + Task run() + { + auto* ctx = machine().execution_context(); + const auto scope = machine().active_scope(); + const auto now = self().clock->now(); + auto t1 = ctx->try_add_timer( + now + 20ms, + [flag = self().orphaned_timer_fired] { + if (flag != nullptr) { + flag->store( + true, std::memory_order_release); + } + }, + scope); + Void::Testing::require(t1.has_value()); + + auto t2 = ctx->try_add_timer( + now + 30ms, [] {}, scope); + Void::Testing::require(t2.has_value()); + + auto t3 = ctx->try_add_timer( + now + 40ms, [] {}, scope); + if (self().limit_hit != nullptr) { + *self().limit_hit = + (!t3.has_value() && + t3.error().code().value == + static_cast( + FsmErrorCode::limit_exceeded)); + } + co_return next(); + } + }; + + struct Second : State { + Task run() + { + (void)co_await await_event_cancellable(); + co_return succeed(7); + } + }; + }; + + TimerPurgeFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class ExitThrowFsm : public Machine + { + public: + + using Success = int; + + struct States { + struct S1 : State { + Task run() { co_return succeed(1); } + Task on_exit() override + { + throw std::runtime_error("exit cleanup error"); + co_return; + } + }; + }; + + ExitThrowFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class BoundedHistoryFsm : public Machine + { + public: + + using Success = int; + int steps{0}; + + struct States { + struct Step : State { + Task run() + { + if (++self().steps >= 8) { + co_return succeed(self().steps); + } + co_return next(); + } + }; + }; + + BoundedHistoryFsm() : Machine(MachineOptions{.own_worker = false}) {} + }; + + // ── Structured parallel & race machines ────────────────────────────── + struct SharedRaceFlags { + std::atomic loser_exited{false}; + std::atomic co_child_exited{false}; + }; + + inline SharedRaceFlags* g_flags = nullptr; + + class FastFailChild : public Machine + { + public: + + using Success = int; + using Failure = FsmError; + + struct States { + struct Run : State { + Task run() + { + (void)co_await delay_cancellable(1ms); + co_return fail(FsmError{"winner_fail"}); + } + }; + }; + }; + + class ForeverLoserChild : public Machine + { + public: + + using Success = int; + + struct States { + struct Park : State { + Task run() + { + (void)co_await await_event_cancellable< + NeverEvent>(); + co_return succeed(0); + } + Task on_exit() override + { + if (g_flags != nullptr) { + g_flags->loser_exited.store( + true, std::memory_order_release); + } + co_return; + } + }; + }; + }; + + class RaceParent : public Machine + { + public: + + using Success = int; + using Failure = FsmError; + + struct States { + struct Race : State { + Task run() + { + auto r = co_await run_parallel_any_structured< + FastFailChild, ForeverLoserChild>(); + if (!r) { + co_return fail( + FsmError{r.error().message()}); + } + if (r->index() == 0) { + auto& winner = std::get<0>(*r); + if (!winner.has_value()) { + co_return fail(winner.error()); + } + } + co_return succeed(99); + } + }; + }; + + RaceParent() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class TieChildA : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + (void)co_await delay_cancellable(10ms); + co_return succeed(1); + } + }; + }; + }; + + class TieChildB : public Machine + { + public: + + using Success = int; + + struct States { + struct Wait : State { + Task run() + { + (void)co_await delay_cancellable(5ms); + co_return succeed(2); + } + }; + }; + }; + + class TieRaceParent : public Machine + { + public: + + using Success = int; + + struct States { + struct Race : State { + Task run() + { + auto r = co_await run_parallel_any_structured< + TieChildA, TieChildB>(); + if (!r) { + co_return succeed(-1); + } + co_return succeed(static_cast(r->index())); + } + }; + }; + + TieRaceParent() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class FaultParent : public Machine + { + public: + + using Success = int; + std::string observed_error{}; + + class CoopSibling : public Machine + { + public: + + using Success = int; + + struct States { + struct Park : State { + Task run() + { + (void)co_await await_event_cancellable< + NeverEvent>(); + co_return succeed(1); + } + Task on_exit() override + { + if (g_flags != nullptr) { + g_flags->co_child_exited.store( + true, + std::memory_order_release); + } + co_return; + } + }; + }; + }; + + class BoomSibling : public Machine + { + public: + + using Success = int; + + struct States { + struct Boom : State { + Task run() + { + throw std::runtime_error( + "sibling fault"); + co_return succeed(0); + } + }; + }; + }; + + struct States { + struct JoinAll : State { + Task run() + { + auto r = co_await run_parallel_structured< + CoopSibling, BoomSibling>(); + if (!r) { + self().observed_error = + r.error().message(); + co_return succeed(-1); + } + co_return succeed(1); + } + }; + }; + + FaultParent() : Machine(MachineOptions{.own_worker = false}) {} + }; + + class MailboxMachine : public Machine + { + public: + + using Success = int; + int drained{0}; + + struct States { + struct Drain : State { + Task run() + { + for (;;) { + auto ev = + co_await await_event_cancellable< + SizedEvent>(); + if (!ev) { + co_return succeed(self().drained); + } + if (ev->bytes == 0) { + co_return succeed(self().drained); + } + ++self().drained; + } + } + }; + }; + + MailboxMachine() : Machine(MachineOptions{.own_worker = false}) {} + }; + + // ── Checkpoints, migration & service lease machines ────────────────── + struct ICounterSvc : Void::Service::IService { + virtual int version() const = 0; + }; + + struct CounterSvcImpl final : ICounterSvc { + int ver{1}; + explicit CounterSvcImpl(int v) : ver(v) {} + std::string_view service_name() const override + { + return "CounterSvc"; + } + int version() const override { return ver; } + }; + + class WorkflowMachine : public Machine + { + public: + + using Success = int; + + struct Data { + int count{0}; + std::string note{"init"}; + }; + Data data; + bool fail_validation{false}; + int first_handle_ver{0}; + std::uint64_t first_handle_gen{0}; + int second_handle_ver{0}; + std::uint64_t second_handle_gen{0}; + std::string seen_resume_label; + + struct States { + struct [[= StateId{"v2.ingest"}]] Ingest : State { + Task run() + { + self().data.count += 1; + co_await safe_point("after_step1"); + auto h1 = acquire_service(); + if (h1) { + self().first_handle_ver = (*h1)->version(); + self().first_handle_gen = h1->generation(); + } + (void)co_await await_event_cancellable(); + if (h1) { + self().first_handle_ver = (*h1)->version(); + } + auto h2 = acquire_service(); + if (h2) { + self().second_handle_ver = + (*h2)->version(); + self().second_handle_gen = h2->generation(); + } + co_return next(); + } + }; + + struct [[= StateId{"v2.process"}]] Process : State { + Task run() + { + self().seen_resume_label = + std::string{restored_resume_label()}; + self().data.count += 10; + co_return succeed(self().data.count); + } + }; + }; + + WorkflowMachine() : Machine(MachineOptions{.own_worker = false}) + { + set_machine_identity("Workflow", 2); + } + + protected: + + void on_serialize(Void::Json::Value& out) const override + { + out = Void::Json::to_json(data); + } + + Void::Result::Result + on_validate_restore(const Void::Json::Value& in) const override + { + if (fail_validation) { + return Void::Result::fail(Void::Fsm::make_fsm_error( + FsmErrorCode::migration_failed, + "rejected by validator")); + } + const auto* c = in.find("count"); + if (c == nullptr || !c->is_int() || c->as_int() < 0) { + return Void::Result::fail(Void::Fsm::make_fsm_error( + FsmErrorCode::migration_failed, "negative count")); + } + return {}; + } + + void on_restore(const Void::Json::Value& in) override + { + auto parsed = Void::Json::from_json(in); + if (parsed.has_value()) { + data = std::move(*parsed); + } + } + }; + +} // namespace void_fsm_hardening_test + +using namespace void_fsm_hardening_test; + +// @tag reflection +Void::Testing::Test fsm_faulted_terminal_handle_and_supervision_bounds() +{ + Void::Testing::expect(Void::Fsm::terminal(Status::Succeeded)); + Void::Testing::expect(Void::Fsm::terminal(Status::Failed)); + Void::Testing::expect(Void::Fsm::terminal(Status::Faulted)); + Void::Testing::expect(!Void::Fsm::terminal(Status::Idle)); + Void::Testing::expect(!Void::Fsm::terminal(Status::Running)); + + Void::Time::ManualClock clock; + Orchestrator orch{&clock, OrchestratorLimits{.max_supervised = 2}}; + + std::vector seen_kinds; + std::size_t inside_running_count = 999; + orch.observe_supervision([&](const SupervisionEvent& ev) { + seen_kinds.push_back(ev.kind); + // Must execute outside Orchestrator's m_mutex without deadlock. + inside_running_count = orch.running_count(); + }); + orch.observe_supervision([](const SupervisionEvent&) { + throw std::runtime_error("supervision observer threw"); + }); + + // StopOnFault: FsmHandle::finished() treats Faulted as terminal, and + // handle retains immutable evidence after reap_finished(). + auto h_fault = orch.try_launch(SupervisionPolicy{}); + Void::Testing::require(h_fault.has_value()); + Void::Testing::require(wait_handle_finished(*h_fault)); + Void::Testing::expect(h_fault->finished()); + Void::Testing::expect_eq(h_fault->status(), Status::Faulted); + Void::Testing::expect_eq(h_fault->termination_reason(), + TerminationReason::faulted); + Void::Testing::require(h_fault->system_error().has_value()); + + Void::Testing::expect_eq(orch.reap_finished(), std::size_t{1}); + Void::Testing::expect_eq(orch.running_count(), std::size_t{0}); + Void::Testing::expect(h_fault->finished()); + Void::Testing::expect_eq(h_fault->status(), Status::Faulted); + Void::Testing::expect(inside_running_count <= 2); + Void::Testing::expect(!orch.observer_errors().empty()); + + // Enforce max_supervised = 2. + auto p1 = orch.try_launch(SupervisionPolicy{}); + auto p2 = orch.try_launch(SupervisionPolicy{}); + Void::Testing::require(p1.has_value() && p2.has_value()); + auto p3 = orch.try_launch(SupervisionPolicy{}); + Void::Testing::expect(!p3.has_value()); + Void::Testing::expect_eq( + p3.error().code().value, + static_cast(FsmErrorCode::limit_exceeded)); + orch.stop_all(); + + // BoundedRestart: 3 restarts within 60s on injected ManualClock with + // exponential backoff (10ms, 20ms, 40ms), then budget exhausted. + std::atomic runs{0}; + SupervisionPolicy br_policy{ + .mode = SupervisionMode::BoundedRestart, + .max_restarts = 3, + .restart_window = 60s, + .initial_backoff = 10ms, + }; + auto br = orch.try_launch(br_policy, &runs); + Void::Testing::require(br.has_value()); + Void::Testing::require(wait_handle_finished(*br)); + + const std::chrono::milliseconds backoffs[] = {10ms, 20ms, 40ms}; + for (std::size_t i = 0; i < 3; ++i) { + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1}); + // Halfway through backoff: must not restart prematurely. + (void)clock.advance(backoffs[i] / 2); + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{0}); + Void::Testing::expect_eq(br->restart_count(), i); + + (void)clock.advance(backoffs[i] - backoffs[i] / 2); + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1}); + Void::Testing::expect_eq(br->restart_count(), i + 1); + Void::Testing::require(wait_handle_finished(*br)); + } + + // 4th fault within 60s exhausts restart budget and releases active slot. + Void::Testing::expect_eq(orch.supervise_step(), std::size_t{1}); + Void::Testing::expect_eq(orch.running_count(), std::size_t{0}); + Void::Testing::expect_eq(br->restart_count(), std::size_t{3}); + Void::Testing::expect_eq(br->status(), Status::Faulted); + Void::Testing::expect_eq(runs.load(), 4); + Void::Testing::expect(!seen_kinds.empty()); +} + +// @tag reflection +Void::Testing::Test fsm_structured_scopes_cancellation_timers_and_exit_fault() +{ + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + + // Deadline timeout + external stop token cancellation via ExecutionBinding. + { + CancellableWaitFsm fsm; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}, + {.deadline = clock.now() + 50ms}), + &out)); + (void)exec.drain(); + Void::Testing::expect(!out.has_value()); + (void)clock.advance(50ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(out.has_value()); + Void::Testing::expect(!out->has_value()); + Void::Testing::expect_eq( + out->error().code().value, + static_cast(FsmErrorCode::timeout)); + Void::Testing::expect_eq(fsm.status(), Status::Faulted); + Void::Testing::expect_eq(fsm.termination_reason(), + TerminationReason::timed_out); + } + { + CancellableWaitFsm fsm; + std::stop_source ss; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}, + {.stop = ss.get_token()}), + &out)); + (void)exec.drain(); + Void::Testing::expect(!out.has_value()); + ss.request_stop(); + (void)exec.drain(); + Void::Testing::require(out.has_value()); + Void::Testing::expect(!out->has_value()); + Void::Testing::expect_eq( + out->error().code().value, + static_cast(FsmErrorCode::cancelled)); + Void::Testing::expect_eq(fsm.status(), Status::Faulted); + Void::Testing::expect_eq(fsm.termination_reason(), + TerminationReason::cancelled); + } + + // Queued timer after state exit must never fire + max_timers enforced. + { + std::atomic orphan_fired{false}; + bool limit_hit{false}; + TimerPurgeFsm fsm; + fsm.orphaned_timer_fired = &orphan_fired; + fsm.limit_hit = &limit_hit; + fsm.clock = &clock; + + std::optional>> out; + FsmLimits limits; + limits.max_timers = 2; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock, .limits = limits}), + &out)); + (void)exec.drain(); + Void::Testing::expect(limit_hit); + + (void)clock.advance(100ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::expect(!orphan_fired.load(std::memory_order_acquire)); + + Void::Testing::require(fsm.try_post(Ping{1}).has_value()); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 7); + } + + // on_exit exception faults the machine cleanly. + { + ExitThrowFsm fsm; + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::expect(!res.has_value()); + Void::Testing::expect_eq(fsm.status(), Status::Faulted); + Void::Testing::expect_eq(fsm.termination_reason(), + TerminationReason::faulted); + Void::Testing::require(fsm.system_error().has_value()); + } + + // Observer throws isolated + bounded transition history (max 4). + { + BoundedHistoryFsm fsm; + fsm.observe([](const Transition&) { + throw std::runtime_error("observer failed"); + }); + fsm.add_interceptor({ + .before = [](const Transition&) { + throw std::runtime_error("interceptor before failed"); + }, + .after = [](std::string_view) { + throw std::runtime_error("interceptor after failed"); + }, + }); + FsmLimits limits; + limits.max_retained_transitions = 4; + auto res = drive_task( + exec, + fsm.run({.executor = &exec, .clock = &clock, .limits = limits})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), 8); + Void::Testing::expect_eq(fsm.transition_history().size(), + std::size_t{4}); + Void::Testing::expect_eq(fsm.observer_errors().size(), std::size_t{24}); + } +} + +// @tag reflection +Void::Testing::Test fsm_parallel_structured_loser_join_tiebreak_and_mailbox_bounds() +{ + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + SharedRaceFlags flags; + g_flags = &flags; + + // Race-any: typed Failure wins and forever-waiting loser is stopped and + // joined BEFORE run_parallel_any_structured returns. + { + RaceParent fsm; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}), &out)); + (void)exec.drain(); + Void::Testing::expect(!out.has_value()); + (void)clock.advance(1ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value()); + Void::Testing::expect(!(*out)->has_value()); + Void::Testing::expect_eq((*out)->error().message, + std::string{"winner_fail"}); + Void::Testing::expect(flags.loser_exited.load(std::memory_order_acquire)); + } + + // Same-turn completion tie-break uses child declaration order (index 0). + { + TieRaceParent fsm; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}), &out)); + (void)exec.drain(); + // Advance clock past BOTH 5ms and 10ms in one step so both timers fire + // in the same dispatch turn -> TieChildA (index 0) must win! + (void)clock.advance(20ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 0); + } + + // Structured parallel-all: sibling Fault triggers cooperative stop and join. + { + FaultParent fsm; + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), -1); + Void::Testing::expect( + flags.co_child_exited.load(std::memory_order_acquire)); + Void::Testing::expect(fsm.observed_error.find("sibling fault") != + std::string::npos); + } + + g_flags = nullptr; + + // Mailbox event/byte caps + reserved control lane + 64-event turn budget. + { + MailboxMachine fsm; + FsmLimits limits; + limits.max_mailbox_events = 3; + limits.max_mailbox_bytes = 64; + limits.max_events_per_turn = 64; + + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock, .limits = limits}), + &out)); + (void)exec.drain(); + + // Byte limit check. + auto over_bytes = fsm.try_post(SizedEvent{128}); + Void::Testing::expect(!over_bytes.has_value()); + Void::Testing::expect_eq( + over_bytes.error().code().value, + static_cast(FsmErrorCode::overloaded)); + + // Fill 3 events. + Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value()); + Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value()); + Void::Testing::require(fsm.try_post(SizedEvent{8}).has_value()); + auto over_cnt = fsm.try_post(SizedEvent{8}); + Void::Testing::expect(!over_cnt.has_value()); + Void::Testing::expect_eq( + over_cnt.error().code().value, + static_cast(FsmErrorCode::overloaded)); + + // Reserved control lane still accepts checkpoint request under user + // mailbox saturation (timed out once clock advances). + std::optional> cp_out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.request_checkpoint({.deadline = clock.now() + 5ms}), + &cp_out)); + (void)clock.advance(5ms); + (void)fsm.pump(); + (void)exec.drain(); + Void::Testing::require(cp_out.has_value()); + Void::Testing::expect(!cp_out->has_value()); + + Void::Testing::require(fsm.try_post(SizedEvent{0}).has_value()); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 3); + } + + // 64-event turn budget on pump(). + { + MailboxMachine fsm; + FsmLimits limits; + limits.max_mailbox_events = 256; + limits.max_events_per_turn = 64; + std::optional>> out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock, .limits = limits}), + &out)); + (void)exec.drain(); + + for (int i = 0; i < 100; ++i) { + Void::Testing::require(fsm.try_post(SizedEvent{4}).has_value()); + } + // One pump processes at most 64 user events before yielding. + (void)fsm.pump(); + Void::Testing::expect_eq(fsm.execution_context()->last_turn_events(), + std::size_t{64}); + (void)exec.drain(); + Void::Testing::require(fsm.try_post(SizedEvent{0}).has_value()); + (void)exec.drain(); + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 100); + } +} + +// @tag reflection +Void::Testing::Test fsm_boundary_checkpoint_migration_and_owning_service_handle() +{ + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + + // Duplicate durable StateId rejected; checkpoint at safe_point succeeds and + // survives provider swap across await via acquire_service(). + Void::Service::ServiceRegistry registry; + Void::Service::ProviderSet pset1; + pset1.add("c1", std::make_shared(1)); + Void::Testing::require(registry.start_and_publish(std::move(pset1)).has_value()); + + Checkpoint captured_cp; + { + WorkflowMachine fsm; + fsm.set_services(registry); + auto dup = fsm.register_state_id( + "v2.ingest"); + Void::Testing::expect(!dup.has_value()); + + std::optional>> out; + std::optional> cp_out; + Void::Async::spawn( + exec, + assign_task_result( + fsm.run({.executor = &exec, .clock = &clock}), &out)); + Void::Async::spawn( + exec, + assign_task_result( + fsm.request_checkpoint({.deadline = clock.now() + 100ms}), + &cp_out)); + (void)exec.drain(); + + Void::Testing::require(cp_out.has_value() && cp_out->has_value()); + captured_cp = std::move(**cp_out); + Void::Testing::expect_eq(captured_cp.state_id, + std::string{"v2.ingest"}); + Void::Testing::expect_eq(captured_cp.resume_label, + std::string{"after_step1"}); + Void::Testing::expect_eq(captured_cp.application_schema, + std::uint32_t{2}); + + // Hot-swap service from v1 -> v2 while Ingest is suspended waiting for + // Ping; Ingest's held ServiceHandle must keep v1 alive. + Void::Service::ProviderSet pset2; + pset2.add("c2", std::make_shared(2)); + Void::Testing::require( + registry.start_and_publish(std::move(pset2)).has_value()); + + Void::Testing::require(fsm.try_post(Ping{1}).has_value()); + (void)exec.drain(); + + Void::Testing::require(out.has_value() && out->has_value() && + out->value().has_value()); + Void::Testing::expect_eq(out->value().value(), 11); + Void::Testing::expect_eq(fsm.first_handle_ver, 1); + Void::Testing::expect_eq(fsm.first_handle_gen, std::uint64_t{1}); + Void::Testing::expect_eq(fsm.second_handle_ver, 2); + Void::Testing::expect_eq(fsm.second_handle_gen, std::uint64_t{2}); + } + + // Validate-then-commit restore: migration failure leaves Idle machine + // unchanged; valid migration + legacy restore succeed atomically. + { + WorkflowMachine fsm; + fsm.data.count = 42; + fsm.data.note = "untouched"; + + Checkpoint bad_schema = captured_cp; + bad_schema.application_schema = 1; + auto r1 = fsm.restore_checkpoint(bad_schema); // no migrator + Void::Testing::expect(!r1.has_value()); + Void::Testing::expect_eq( + r1.error().code().value, + static_cast(FsmErrorCode::schema_mismatch)); + Void::Testing::expect_eq(fsm.data.count, 42); + + auto r2 = fsm.restore_checkpoint( + bad_schema, [](std::uint32_t, std::uint32_t, Void::Json::Value&, + std::string&) -> Void::Result::Result { + throw std::runtime_error("migrator boom"); + }); + Void::Testing::expect(!r2.has_value()); + Void::Testing::expect_eq( + r2.error().code().value, + static_cast(FsmErrorCode::migration_failed)); + Void::Testing::expect_eq(fsm.data.count, 42); + Void::Testing::expect_eq(fsm.data.note, std::string{"untouched"}); + + // Schema 1 -> Schema 2 valid migration onto Process with resume label. + auto r3 = fsm.restore_checkpoint( + bad_schema, + [](std::uint32_t, std::uint32_t, Void::Json::Value& data, + std::string& sid) -> Void::Result::Result { + sid = "v2.process"; + data = Void::Json::object(); + data.as_object().emplace_back( + "count", Void::Json::Value{std::int64_t{20}}); + data.as_object().emplace_back("note", + Void::Json::Value{"migrated"}); + return {}; + }); + Void::Testing::require(r3.has_value()); + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), 30); + Void::Testing::expect_eq(fsm.seen_resume_label, + std::string{"after_step1"}); + } + + // Explicit legacy {state, data} reader with old->durable state map. + { + WorkflowMachine fsm; + const auto legacy = Void::Json::parse( + R"({"state":"OldProcess","data":{"count":5,"note":"legacy"}})"); + Void::Testing::require(legacy.has_value()); + const std::unordered_map id_map{ + {"OldProcess", "v2.process"}}; + auto lr = fsm.restore_legacy_checkpoint( + *legacy, id_map, + [](std::uint32_t, std::uint32_t, Void::Json::Value&, + std::string&) -> Void::Result::Result { return {}; }); + Void::Testing::require(lr.has_value()); + auto res = drive_task( + exec, fsm.run({.executor = &exec, .clock = &clock})); + Void::Testing::require(res.has_value() && res->has_value()); + Void::Testing::expect_eq(res->value(), 15); + } +}