FSM: typed Success/Failure result model (reflected nested types)

A machine is now Machine<Derived> (dropping the ResultT template param) and
declares its result types as nested types reflected *by name* — Success and
Failure (a struct or a using-alias), each defaulting to void:

    class Login : public Machine<Login> {
      using Success = Token;     // or a nested struct; default void
      struct Failure { int code; };
    };

- Outcome = std::expected<Success, Failure> (void failure -> std::monostate
  error arm). succeed(Success{...}) / fail(Failure{...}) carry the typed
  values (nullary when void). Resolved by plain dependent-name lookup
  (Detail/Result.hpp), no P2996.
- Engine/system faults (no initial state, unregistered target, no entry)
  travel a SEPARATE FsmError channel: status()==Faulted + system_error(),
  never the typed Failure. New Step::Kind::Fault carries it.
- CRTP wrinkle: Derived is incomplete at base instantiation, so the engine
  stores the result type-erased (std::any) and rebuilds the typed Outcome in
  wait()/run_blocking()/take_outcome() — function templates defaulted on
  Derived. run_child/run_region/start_machine reconstruct OutcomeOf<Sub> at
  the boundary (Sub is complete).
- Step carries Success/Failure payloads as std::any; the reactive DSL
  (finish/fail) and Continue<Sub> are reparameterised off the nested types.

Interim: Continue<Sub> keeps the named on_success/on_failure form (Phase 2
replaces it with signature-inferred ChildSuccess/ChildFailure). All FSM
tests migrated to the nested-type form. 995 tests (992 green, 3 skipped),
ASan clean, -Werror clean; the lone intermittent failure is the
pre-existing racy plugin hot-reload-under-load test (flaky on HEAD too).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 21:14:43 +03:00
1 parent 7c7c590d79
commit 9e9eb838ea
20 files changed
+487 -245

No files matched your search

+156 -68
View File
@@ -8,6 +8,7 @@
#include <Void/Fsm/Detail/Engine.hpp>
#include <Void/Fsm/Detail/Introspect.hpp>
#include <Void/Fsm/Detail/Reactive.hpp>
#include <Void/Fsm/Detail/Result.hpp>
#include <Void/Fsm/Detail/TypeName.hpp>
#include <Void/Fsm/Step.hpp>
#include <Void/Log/Log.hpp>
@@ -89,13 +90,25 @@ namespace Void::Fsm
// };
// using States = Void::Fsm::States<Check>;
// };
template <typename Derived, typename ResultT = void> class Machine
template <typename Derived> class Machine
{
public:
using result_type = ResultT;
using Options = MachineOptions;
using Outcome = std::expected<ResultT, FsmError>;
// 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 <typename D = Derived>
using Success = Detail::SuccessOf<D>;
template <typename D = Derived>
using Failure = Detail::FailureOf<D>;
template <typename D = Derived>
using Outcome = Detail::OutcomeOf<D>;
// ── State base ────────────────────────────────────────────────
class State : public Detail::StateBase
@@ -188,22 +201,36 @@ namespace Void::Fsm
co_return false;
}
/// Finish with the machine's typed Success result (nested
/// `Success`; nullary when it is void).
[[nodiscard]] Step succeed() const
requires std::is_void_v<ResultT>
requires std::is_void_v<Detail::SuccessOf<Derived>>
{
return Step::success(std::any{});
}
template <typename V>
[[nodiscard]] Step succeed(V&& value) const
requires(!std::is_void_v<ResultT>)
requires(!std::is_void_v<Detail::SuccessOf<Derived>>)
{
return Step::success(
std::any{ResultT(std::forward<V>(value))});
std::any{Detail::SuccessOf<Derived>(
std::forward<V>(value))});
}
[[nodiscard]] Step fail(std::string message) const
/// Finish with the machine's typed Failure result (nested
/// `Failure`; nullary when it is void).
[[nodiscard]] Step fail() const
requires std::is_void_v<Detail::FailureOf<Derived>>
{
return Step::failure(FsmError{std::move(message)});
return Step::failure(std::any{});
}
template <typename V>
[[nodiscard]] Step fail(V&& value) const
requires(!std::is_void_v<Detail::FailureOf<Derived>>)
{
return Step::failure(
std::any{Detail::FailureOf<Derived>{
std::forward<V>(value)}});
}
template <typename I> [[nodiscard]] I& service() const
@@ -265,10 +292,9 @@ namespace Void::Fsm
[[nodiscard]] Step startMachine(Args&&... args) const
{
static_assert(
std::is_base_of_v<
Continue<typename Sub::result_type>, Next>,
std::is_base_of_v<Continue<Sub>, Next>,
"startMachine<Sub, Next>: Next must derive "
"Continue<Sub::result_type>");
"Continue<Sub>");
return m_machine->template start_machine<Sub, Next>(
std::forward<Args>(args)...);
}
@@ -298,8 +324,8 @@ namespace Void::Fsm
// Coro::Task<Step> on_failure(FsmError e) override {
// co_return fail(e.message); }
// };
template <typename SubResult>
using Continue = Detail::Continuation<State, SubResult>;
template <typename Sub>
using Continue = Detail::Continuation<State, Sub>;
// ── reactive (declarative) states ─────────────────────────────
//
@@ -321,8 +347,7 @@ namespace Void::Fsm
// The declarative transition DSL lives in Detail/Reactive.hpp;
// these aliases give reactive states the ergonomic nested names.
using TransitionTable = Detail::TransitionTable<Derived>;
using TransitionBuilder =
Detail::TransitionBuilder<Derived, ResultT>;
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
class Reactive : public State
{
@@ -549,7 +574,9 @@ namespace Void::Fsm
}
}
Outcome wait()
// Function templates so the typed Outcome resolves where Derived is
// complete (CRTP). Call sites stay `fsm.wait()` / `run_blocking()`.
template <typename D = Derived> Outcome<D> wait()
{
if (m_ctx) {
if (m_options.own_worker && m_owns_ctx) {
@@ -562,13 +589,20 @@ namespace Void::Fsm
}
}
}
return take_outcome();
return take_outcome<D>();
}
Outcome run_blocking()
template <typename D = Derived> Outcome<D> run_blocking()
{
start();
return wait();
return wait<D>();
}
/// The system fault (if any) — a programming error caught by the
/// engine, separate from a typed Failure result.
[[nodiscard]] std::optional<FsmError> system_error() const
{
return m_system_error;
}
std::size_t pump() { return m_ctx ? m_ctx->pump() : 0; }
@@ -576,7 +610,8 @@ namespace Void::Fsm
[[nodiscard]] bool finished() const noexcept
{
const auto s = m_status.load();
return s == Status::Succeeded || s == Status::Failed;
return s == Status::Succeeded || s == Status::Failed ||
s == Status::Faulted;
}
[[nodiscard]] Status status() const noexcept
@@ -605,7 +640,8 @@ namespace Void::Fsm
m_ctx.reset();
m_owns_ctx = false;
m_current.store(-1, std::memory_order_release);
m_outcome.reset();
m_result_value.reset();
m_system_error.reset();
m_pending_result.reset();
m_jump.store(nullptr, std::memory_order_release);
m_step = 0;
@@ -764,12 +800,13 @@ namespace Void::Fsm
// ── nesting ───────────────────────────────────────────────────
template <typename Sub, typename... Args>
[[nodiscard]] Coro::Task<typename Sub::Outcome>
[[nodiscard]] Coro::Task<Detail::OutcomeOf<Sub>>
run_child(Args&&... args)
{
Sub child{std::forward<Args>(args)...};
child.attach(m_ctx, m_services);
co_return co_await child.drive();
co_await child.drive();
co_return child.template take_outcome<Sub>();
}
/// Composite sub-state: run `Sub` as a child region sharing this
@@ -779,15 +816,15 @@ namespace Void::Fsm
/// caller maps to a sibling transition. The calling state's
/// on_enter/on_exit naturally wrap the region.
template <typename Sub, typename... Args>
[[nodiscard]] Coro::Task<typename Sub::Outcome>
[[nodiscard]] Coro::Task<Detail::OutcomeOf<Sub>>
run_region(Args&&... args)
{
Sub child{std::forward<Args>(args)...};
child.attach(m_ctx, m_services);
m_region_probe = [&child] { return child.state_path(); };
auto outcome = co_await child.drive();
co_await child.drive();
m_region_probe = nullptr;
co_return std::move(outcome);
co_return child.template take_outcome<Sub>();
}
/// Build a Launch step: run `Sub` (constructed from `args`) on this
@@ -805,22 +842,26 @@ namespace Void::Fsm
[this,
tup = std::make_tuple(std::forward<Args>(
args)...)]() mutable -> Coro::Task<LaunchResult> {
auto outcome = co_await std::apply(
[this](auto&&... a) {
return this->template run_child<Sub>(
std::forward<decltype(a)>(a)...);
},
std::move(tup));
// Run Sub on the shared executor and read its raw result so
// Success / Failure / Fault are all distinguishable.
Sub child = std::make_from_tuple<Sub>(std::move(tup));
child.attach(m_ctx, m_services);
co_await child.drive();
LaunchResult lr;
if (outcome.has_value()) {
lr.ok = true;
if constexpr (!std::is_void_v<
typename Sub::result_type>) {
lr.value = std::any{std::move(*outcome)};
}
} else {
lr.ok = false;
lr.error = std::move(outcome.error());
switch (child.m_status.load(std::memory_order_acquire)) {
case Status::Succeeded:
lr.kind = LaunchResult::Kind::Success;
lr.value = std::move(child.m_result_value);
break;
case Status::Failed:
lr.kind = LaunchResult::Kind::Failure;
lr.failure = std::move(child.m_result_value);
break;
default:
lr.kind = LaunchResult::Kind::Fault;
lr.fault = child.m_system_error.value_or(
FsmError{"sub-machine fault"});
break;
}
co_return lr;
};
@@ -962,7 +1003,7 @@ namespace Void::Fsm
private:
template <typename, typename>
template <typename>
friend class Machine; // run_child reaches child internals
void attach(std::shared_ptr<Detail::ExecutionContext> ctx,
@@ -1040,13 +1081,26 @@ namespace Void::Fsm
}
}
// The state loop: build each state, run on_enter → run →
// on_exit, follow the returned Step. Runs on the executor.
Coro::Task<Outcome> drive()
// 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)};
Void::Log::error("Fsm", "system fault: {}",
m_system_error->message);
m_status.store(Status::Faulted, std::memory_order_release);
}
// 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<void> drive()
{
const std::type_info* cur = m_initial;
if (cur == nullptr) {
co_return std::unexpected{FsmError{"no initial state"}};
fault("no initial state");
co_return;
}
for (;;) {
// Apply an external jump<S>() at this transition boundary.
@@ -1058,18 +1112,22 @@ namespace Void::Fsm
}
const auto it = m_factories.find(std::type_index{*cur});
if (it == m_factories.end()) {
co_return std::unexpected{
FsmError{"transition to unregistered state"}};
fault("transition to unregistered state");
co_return;
}
set_current(cur);
auto state = it->second();
co_await state->on_enter();
// A state entered via startMachine resumes from the sub's
// result (Continue<R> dispatches); otherwise it runs.
// result; otherwise it runs.
Step step;
if (m_pending_result.has_value()) {
LaunchResult pending = std::move(*m_pending_result);
m_pending_result.reset();
if (pending.kind == LaunchResult::Kind::Fault) {
fault(std::move(pending.fault.message));
co_return;
}
step = co_await state->resume(std::move(pending));
} else {
step = co_await state->run();
@@ -1081,43 +1139,70 @@ namespace Void::Fsm
cur = step.target();
continue;
case Step::Kind::Launch:
// Run the sub-machine, stash its result, then enter
// the Next (Continue<R>) state.
m_pending_result.emplace(
co_await step.run_launch());
cur = step.target();
continue;
case Step::Kind::Success:
if constexpr (std::is_void_v<ResultT>) {
co_return Outcome{};
} else {
co_return Outcome{std::any_cast<ResultT>(
std::move(step.result()))};
}
m_result_value = std::move(step.payload());
m_status.store(Status::Succeeded,
std::memory_order_release);
co_return;
case Step::Kind::Fail:
co_return std::unexpected{step.error()};
m_result_value = std::move(step.payload());
m_status.store(Status::Failed,
std::memory_order_release);
co_return;
case Step::Kind::Fault:
fault(std::any_cast<FsmError>(step.payload())
.message);
co_return;
}
}
}
Coro::Task<void> driver()
{
Outcome outcome = co_await drive();
const bool ok = outcome.has_value();
m_outcome.emplace(std::move(outcome));
m_status.store(ok ? Status::Succeeded : Status::Failed,
std::memory_order_release);
co_await drive();
if (m_owns_ctx) {
m_ctx->finish();
}
}
Outcome take_outcome()
// Rebuild the typed Outcome from the type-erased result. Function
// template so SuccessOf/FailureOf<Derived> resolve where Derived is
// complete. A system fault yields a default-constructed error arm
// (consult system_error()).
template <typename D = Derived> Outcome<D> take_outcome()
{
if (m_outcome.has_value()) {
return std::move(*m_outcome);
using Succ = Detail::SuccessOf<D>;
using Fail = Detail::FailureOf<D>;
using Err = Detail::ErrArm<Fail>;
switch (m_status.load(std::memory_order_acquire)) {
case Status::Succeeded:
if constexpr (std::is_void_v<Succ>) {
return Outcome<D>{};
} else {
return Outcome<D>{
std::any_cast<Succ>(m_result_value)};
}
case Status::Failed:
if constexpr (std::is_void_v<Fail>) {
return Outcome<D>{std::unexpect, std::monostate{}};
} else {
return Outcome<D>{
std::unexpect,
std::any_cast<Fail>(m_result_value)};
}
default: // Faulted / not finished
static_assert(
std::is_default_constructible_v<Err>,
"a machine with a non-default-constructible "
"Failure "
"cannot represent a system fault in its Outcome; "
"check system_error()");
return Outcome<D>{std::unexpect, Err{}};
}
return std::unexpected{FsmError{"machine did not finish"}};
}
Options m_options;
@@ -1137,7 +1222,10 @@ namespace Void::Fsm
std::atomic<int> m_current{-1};
std::atomic<Status> m_status{Status::Idle};
std::optional<Outcome> m_outcome;
// Type-erased finished result (Success or Failure payload), rebuilt
// typed in take_outcome(); system faults in m_system_error.
std::any m_result_value;
std::optional<FsmError> m_system_error;
std::function<void(const Transition&)> m_observer;
std::vector<Interceptor> m_interceptors;
std::uint64_t m_step{0};