Commit Graph
13 Commits
Author SHA1 Message Date
faumaray ef5312c4b3 feat(fsm): structured scopes, race-loser join, boundary checkpoints, and bounded supervision 2026-11-26 16:51:35 +03:00
faumaray cd6fc7e5f5 build: reconcile module dependency closures, Log.hpp ownership, and consumer tests (X-BASE-03) 2026-11-24 02:28:33 +03:00
faumarayandClaude Fable 5 c6b7306614 FSM (5): multi-waiter mailbox (engine foundation)
ExecutionContext had a single Waiter slot, so only one coroutine could park
on events at a time. Replace it with a FIFO list of waiters: set_waiter
appends (each with a unique id + its own timer); deliver routes an event to
the first parked waiter that wants its type, else buffers; a timeout fires
only its own waiter (found by id). Single-consumer invariant unchanged — all
mailbox mutation stays on the consumer thread.

Pure refactor (no API change); unblocks parallel regions and deferred
events. 995 tests (992 green, 3 skipped), ASan clean, -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 01:24:02 +03:00
faumarayandClaude Fable 5 ec9e466d7a FSM (4): one signature-inferred State (drops Reactive/Continue bases)
There is now a single state base, `State`. The engine infers each state's
role purely from member signatures via P2996 — no `override`, no
framework-mandated names:

  struct Work : State {                          // entry
    Coro::Task<Step> run() { ... }
    Coro::Task<Step> run(Cfg c) { ... }          // startup-entry (launch data)
  };
  struct Idle : State {                          // reactive
    void transitions(TransitionBuilder& on) { on.event<Go>().to<Run>(); }
  };
  struct After : State {                         // continuation
    Coro::Task<Step> ok(ChildSuccess auto s) { use s.value; }
    Coro::Task<Step> no(ChildFailure auto f) { use f.value; }
  };

- Detail/Roles.hpp: ChildSuccess/ChildFailure concepts over boxes, plus the
  reflection selectors (invoke_entry / invoke_startup / invoke_handler /
  dispatch_result / has_transitions / make_driver). At add<S>() a per-state
  driver thunk is stored (reactive table vs entry, by whether S has a
  TransitionBuilder& member); drive() calls it. startMachine<Sub, Next>(data)
  builds a Launch step carrying a launcher (injects data into Sub's initial
  startup-entry) + a dispatcher (dispatch_result<Next, Sub>) that builds the
  ChildSuccess/Failure box and calls Next's matching handler.
- Removed Reactive/Continue<R> bases, StateKind/kind(), StateBase::run/resume
  (only on_enter/on_exit remain virtual). Reactive states keep the same DSL.
- Toolchain note: template-for + member splicing fails inside a coroutine
  body in this GCC build, so the selectors are non-coroutines returning a
  Task<Step> (plain Step wrapped via ready_task). Discovery is
  invocability-based — no parameter-type reflection (P3096). Probe-verified.

All FSM tests migrated to the nameless style (SubMachine: Continue ->
ChildSuccess/Failure handlers + startup-entry seeding; reactive states drop
the Reactive base/override). 995 tests (992 green, 3 skipped), ASan clean,
-Werror clean; lone intermittent failure remains the pre-existing racy
plugin hot-reload-under-load test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 01:20:56 +03:00
faumarayandClaude Fable 5 9e9eb838ea 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>
2026-06-14 21:14:43 +03:00
faumarayandClaude Fable 5 7c7c590d79 FSM (3): direct control — fluent events, free jumps, lifecycle, mutation
Adds imperative ergonomics for driving and reshaping a machine. The engine
isn't preemptible mid-state (coroutines aren't interruptible), so external
controls apply at transition boundaries and mutation is Idle-only — both
documented.

- Fluent events: send(e1, e2, …) variadic post.
- Free runtime jumps: in-state goto_state<S>() reaches any registered state
  with no declared transition ("each state can be moved to another state");
  external jump<S>() requests a redirect applied by drive() at the next
  boundary (race-safe via an atomic, non-preemptive).
- Lifecycle: reset() returns a finished/idle machine to Idle (drops the
  owned ctx, clears outcome/current/jump); restart() / restart_at<S>()
  re-run; pause() / resume() (ExecutionContext gains a paused flag — the
  worker stops draining and pump() no-ops while paused; posted events
  buffer until resume()).
- Runtime mutation (Idle only): remove<S>() (re-packs indices,
  fixes the initial), set_initial<S>(), replace<S, T>().

8 new tests (Direct): send batch, goto_state skip, boundary jump (embedder
mode), restart / restart_at, remove + set_initial, replace, pause holds
events until resume. 995 green, ASan+UBSan clean, 0 flaky in 15 runs,
-Werror clean. Completes the FSM refactor plan (1-3).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 15:44:19 +03:00
faumarayandClaude Fable 5 b34226369a FSM (2): declarative sub-machine continuations (startMachine + Continue<R>)
A state can now launch a full sub-FSM and have the engine resume into a
named state that handles the result, instead of awaiting+branching by hand:

    co_return startMachine<Login, AfterLogin>(user, tries);

    struct AfterLogin : Continue<bool> {        // Login = Machine<Login,bool>
      Task<Step> on_success(bool ok) override {
        co_return ok ? next<Home>() : next<Locked>(); }
      Task<Step> on_failure(FsmError e) override { co_return fail(e.message); }
    };

- Sub runs on the parent's shared executor/event-mailbox/services (reuses
  run_child); seed data is forwarded to Sub's constructor.
- The engine dispatches on its own: on entry with a pending result it calls
  the state's resume(), which Continue<R> overrides to pick
  on_success(R)/on_failure(FsmError) by the outcome. Continue<void> takes a
  nullary on_success(). A Continue handler may itself return another
  startMachine (chaining) or any Step.
- Type-safe: startMachine<Sub, Next> static_asserts Next derives
  Continue<Sub::result_type> and is in States<>.

Mechanics: Step gains Kind::Launch carrying the target + a type-erased
launcher (a coroutine that runs the sub and maps its Outcome to a
LaunchResult); drive() awaits it, stashes the result, and the entered
state's resume() consumes it. StateBase::resume defaults to run().

5 new tests (SubMachine): success/failure dispatch, void-result nullary
on_success, chained startMachine through Continue states, and that the sub
shares the parent's event mailbox. 987 green, ASan+UBSan clean, stable
across 10 runs, -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 15:37:40 +03:00
faumarayandClaude Fable 5 422a7705c5 FSM v2 (B): timers, await_event_for, reactive/declarative states + guards
Engine: ExecutionContext gains a timer set (add_timer/cancel_timer); the
worker parks with try_acquire_until(earliest deadline) instead of a bare
acquire, and fires due timers in pump()/run_loop. The event mailbox waiter
is now multi-type (await any of N event types) and carries an optional
timeout — deliver() matches a waiting state directly (event needn't sit in
a buffer) and cancels the paired timer; the timer's fire resumes the
waiter with timed_out set. Single consumer still owns all mailbox/timer
state, so it stays lock-free for state code.

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

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

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 01:11:53 +03:00
faumarayandClaude Fable 5 e941a48007 FSM v2 (A): CRTP typed access, States<> auto-registration, lifecycle, observers
Maintainability core, breaking the state API (all FSM tests migrated):
- Machine<Derived, ResultT> (CRTP). State::self() returns Derived& — drops
  the static_cast<Derived&>(machine()) boilerplate from every state.
- `using States = Fsm::States<...>` auto-registers every state in the base
  ctor (first entry = initial unless `using Initial = S`); no more manual
  add<S>()/initial<S>() for static machines. next<S>() static_asserts S is
  in the list (unregistered targets are now a COMPILE error, not a runtime
  fail); next_dynamic<S>() + add<S>()/add_if<S>() remain for dynamic
  machines.
- Per-state lifecycle: StateBase gains virtual on_enter()/on_exit()
  (Coro::Task<void>, default no-op) run around run(); the engine visit is
  enter -> run -> exit, so entry/exit actions split out of run(). run()
  now has a default (fails) so reactive states (Phase B) needn't define it.
- Observability: virtual on_transition(from,to) (default logs via Void::Log)
  + observe(fn) called on every transition (and the initial entry) with a
  Transition{from,to,step}. state_path()/state_names() added.

Migrated Basic/Events/Nesting/Serialize/Concurrency + the Orchestrator and
service-hot-reload tests to CRTP + self() + States<>; new Lifecycle suite
(enter/run/exit ordering, observer edges, default-run failure). 968 green,
ASan+UBSan clean, -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 01:03:43 +03:00
faumarayandClaude Fable 5 cfeaf93a53 Add Service registry and rewrite Fsm as an inheritance/coroutine workflow
Service module (Void::Service):
- IService base (service_name + on_start/on_stop lifecycle).
- ServiceRegistry: type-keyed container — provide<I>(impl), get<I>()
  (nullptr if absent), require<I>() (throws), has<I>(), start_all/
  stop_all. Consumers depend only on the interface I and resolve at
  runtime (dependency inversion); a concrete that derives IService is
  recovered for lifecycle via dynamic_cast even when registered under a
  plain interface. shared_mutex; reads are the hot path.

New Void::Fsm — a single inheritance + coroutine workflow FSM replacing
the deleted statechart/compile-time FSMs:
- Derive Machine<ResultT>; declare states as nested structs deriving
  State; each implements Coro::Task<Step> run() returning next<S>() /
  succeed(...) / fail(...).
- Async by default: a non-template Detail::ExecutionContext owns one
  ManualExecutor + worker thread + a lock-free MPSC event queue + a typed
  event mailbox; a single consumer touches all mutable state so state
  code is lock-free/single-threaded. Embedder mode (own_worker=false)
  drives via pump() for deterministic tests.
- Events: co_await await_event<E>() consumes the oldest queued E (typed
  mailbox), suspending until one arrives; post<E>(e) is lock-free from
  any thread.
- Nesting: co_await run_child<Sub>(args...) runs a child on the same
  executor (shared events/services) and yields its Outcome.
- Dynamic: add<S>() / add_if<S>(cond) register states; next<unregistered>
  fails; has_state<S>() lets states branch.
- Services: set_services(registry); state.service<I>() resolves through
  the injected context.
- Observation: current_state() is a lock-free atomic-index read of an
  immutable name table (P2996 identifier_of, fallback to indexed names).
- Persistence: serialize() captures {state name, on_serialize data};
  restore() on an un-started machine resumes at the named state.

26 new tests (Service registry; FSM basic/success/fail, events incl.
cross-thread worker + order, nesting incl. failure propagation,
serialize/restore, dynamic registration, service resolution, and a
6-producer x 5k concurrent-post stress + lock-free current_state reader
check). 960 green, ASan+UBSan clean, stable across 10 runs, -Werror clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 00:39:05 +03:00
faumarayandClaude Fable 5 04cf1998bd Remove the two old FSMs ahead of the inheritance-based rewrite
Deletes the compile-time Void::StateMachine and the builder-based runtime
Void::Fsm (Definition/Machine/Event/PluginBehavior + their standalone
tests, the FSM behaviour plugins, and the FSM x Plugin integration test
and its CMake wiring). The general-purpose Plugin module and its stateful
hot-reload tests are untouched.

Both are being replaced by a single inheritance + coroutine workflow FSM
(next phase). 936 tests green (51 old FSM/StateMachine tests removed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 00:26:30 +03:00
faumarayandClaude Fable 5 ff6960a2af Fix -Werror build: drop dead variables, honor nodiscard
Surfaced by a -DVOID_WARNINGS_AS_ERRORS=ON build now that Json/Ini are
pulled into SHARED module TUs (Log, Fsm, Plugin, Configuration):
- Json::Detail::parse_number: removed the unused is_float tracking var.
- Ini::from_string: (void)-cast the nodiscard parse() result.
- Fsm::Machine::dispatch_event: removed the dead `source` variable
  (the transition already carries its source state).

Module targets now compile clean under -Wall -Wextra -Wpedantic -Werror;
967 tests green, ASan+UBSan clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 18:15:32 +03:00
faumarayandClaude Fable 5 697e07843c Add Void::Fsm - runtime hierarchical FSM with lock-free MPSC core
Definition (Builder -> immutable shared MachineDef):
- Named hierarchical states, events by name or enum identifier (P2996),
  states_from_enum, initial/parallel composites, shallow/deep history,
  deferred events, per-state timeouts, guards, entry/exit/transition
  actions (coroutine Task<void> or sync, wrapped), internal transitions.
- build() validates (initial children, transition endpoints) and
  flattens into index-addressed vectors with depth info for LCA.

Machine (one consumer, many producers):
- post() is lock-free from any thread: Vyukov MPSC push + counting-
  semaphore park/wake; the single consumer (owned worker, or embedder
  via run_pending) owns all mutable machine state with zero locks.
- Observation via seqlock over a trivially-copyable StateSnapshot of
  active leaves; readers retry, writer is wait-free, no heap.
- Run-to-completion: innermost-first transition resolution per region,
  LCA-based exit/entry ordering, history snapshotted at exit time,
  deferred events re-injected FIFO after each state change, timers via
  deadline park (generation counters kill stale fires), orthogonal
  regions dispatched independently on the single consumer.
- co_await machine.send(ev) / send_wait() resolve with SendResult after
  the step; actions are driven to completion on the consumer's
  ManualExecutor before the step ends.
- swap_definition: atomic<shared_ptr> definition swap between steps;
  identical active-leaf names adopt seamlessly (no entry re-runs, queue
  intact), otherwise initial configuration; history remapped by name.
- serialize_state()/restore_state(): JSON by state *names* for
  hot-reload and persistence; restore re-activates silently.
- start() returns only once the initial configuration is entered.

40 new tests: semantics (ordering, guards, internal/self transitions),
hierarchy + both history kinds, defer FIFO, parallel regions, timers,
coroutine actions, awaitable/blocking send, serialize/restore round
trips, seamless + fallback hot swap, and stress: 8 producers x 10k with
per-producer FIFO assertion, 4-reader seqlock tear check, 50 definition
swaps under sustained load. Green under ASan+UBSan, stable across
repeated runs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 00:49:45 +03:00