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>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-13 00:49:45 +03:00
1 parent c74a02a5a5
commit 697e07843c
13 files changed
+3105

No files matched your search

+13
View File
@@ -48,6 +48,7 @@ VoidLibrary is a C++26 modular shared library organized as **umbrella modules**
| `Stacktrace` | SHARED | Boost.Stacktrace capture, color helpers (kept separate to isolate the Boost dep) |
| `Plugin` | SHARED | dlopen loader, C ABI, hot reload |
| `StateMachine` | INTERFACE | compile-time variant-based FSM |
| `Fsm` | SHARED | runtime hierarchical FSM (see below) |
| `Testing` / `TestingMock` | STATIC / INTERFACE | test + mock frameworks |
`include/Void/Detail/` (e.g. `Enum.hpp` — P2996 enum reflection) is not a module; it is header-only and reachable from every module via the shared include root.
@@ -133,6 +134,18 @@ Other key points:
`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(cfg, prefix)` fills an aggregate via P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`).
### Fsm module (runtime FSM)
`Void::Fsm` — full-featured runtime state machine, distinct from the compile-time `StateMachine`:
- **Definition**: `Builder` declares states by name (`state("a", parent)` — hierarchical), events (`event("go")` or from enums via reflection), `initial`, `parallel` (orthogonal regions), `history(Shallow|Deep)`, `defer`, `timeout(state, ms, event)`, `transition(from, on, to).guard(...).action(...)`, `internal(in, on)`. `build()` validates into an immutable `shared_ptr<const MachineDef>`. Names are the stable identity; ids are per-definition.
- **Actions** are `std::function<Coro::Task<void>(Machine&, const Event&)>` (sync lambdas via `SyncAction` overloads). The run-to-completion step finishes only when the action's coroutine completes; the worker drives it on its own `ManualExecutor`.
- **Concurrency (MPSC)**: `post()` is lock-free from any thread (Vyukov queue + park semaphore); exactly one consumer — the owned worker (`start()` returns once the initial configuration is entered) or the embedder via `run_pending()` when constructed with `MachineOptions{.own_worker = false}` (the deterministic mode used by most tests; note `send_wait`/queued `serialize_state` would self-deadlock there — they're for the worker mode). Observation (`current()`, `is_in`) is a seqlock read of a trivially-copyable `StateSnapshot` (≤16 active leaves).
- **send paths**: `co_await machine.send(ev[, &executor])` resolves with `SendResult{Handled,Deferred,Unhandled,Dropped}` after the step; `send_wait` blocks; resumption defaults to the machine worker.
- **Hot swap**: `swap_definition(def)` applies between steps. If every active leaf name exists in the new def, the configuration is adopted without re-running entry actions (seamless); otherwise the machine re-enters the initial configuration. History is remapped by name.
- **Persistence**: `serialize_state()` → JSON with leaf/history *names*; `restore_state(json)` on a stopped machine re-activates silently (no entry actions).
- History records are snapshotted at exit time in `perform_transition` (not incrementally) — keep it that way; incremental recording accumulates stale leaves.
## Code style
Enforced by `.clang-format` (LLVM-based): 4-space indent (tabs), 80-column limit, Linux brace wrapping style, pointer alignment right.