169 lines
11 KiB
Markdown
169 lines
11 KiB
Markdown
# Fsm structured workflows and checkpoint plan
|
||
|
||
Status: PLANNED feature work. Source baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`,
|
||
inspected 2026-11-24. Requirements R-002, R-009, R-010, R-014 and R-015 apply.
|
||
Follow [architecture](../ARCHITECTURE.md) C-03–C-05, C-09, C-10 and C-13.
|
||
|
||
## Existing source baseline
|
||
|
||
[Machine.hpp](../../../include/Void/Fsm/Machine.hpp) implements
|
||
`Void::Fsm::Machine<R>`, signature/reflection-driven states, entry/exit hooks, typed
|
||
outcomes, event waits, hierarchy/history, submachines, parallel regions, race-any,
|
||
pause/restart/jump and JSON serialization. `serialize()` records a named state plus
|
||
application `on_serialize` data; `restore` requires Idle and invokes `on_restore`.
|
||
It does not save suspended coroutine stacks. `run_parallel_any` explicitly leaves
|
||
losers running; a permanently parked loser can retain a frame until stop.
|
||
|
||
[StateKey.hpp](../../../include/Void/Fsm/StateKey.hpp) defines `StateKey`, `FsmError`,
|
||
`LaunchResult` and statuses Idle/Running/Succeeded/Failed/Faulted. Machine::finished
|
||
includes Faulted, but [Orchestrator.hpp](../../../include/Void/Fsm/Orchestrator.hpp)
|
||
FsmHandle::finished currently checks only Succeeded/Failed. Despite its non-owning
|
||
comment, FsmHandle stores a shared_ptr to its model; migration must clarify ownership
|
||
from the source rather than repeat the comment.
|
||
|
||
[Engine.hpp](../../../include/Void/Fsm/Detail/Engine.hpp) and
|
||
[Engine.cpp](../../../src/Fsm/Engine.cpp) contain a shared executor/event mailbox/timer
|
||
substrate, optional owning worker and embedder pumping. Nested machines share that
|
||
substrate. [module.cmake](../../../src/Fsm/module.cmake) declares Async, Data,
|
||
Functional, Log and Service. NEW execution continues to depend on Async and optional
|
||
Service access, never on managed Runtime or Scheduler.
|
||
|
||
Existing fixtures include [basic pumping](../../../tests/standalone/Fsm/Basic.cpp),
|
||
[events](../../../tests/standalone/Fsm/Events.cpp),
|
||
[parallel regions](../../../tests/standalone/Fsm/Parallel.cpp),
|
||
[policies](../../../tests/standalone/Fsm/Policies.cpp),
|
||
[hierarchy](../../../tests/standalone/Fsm/Hierarchy.cpp),
|
||
[history](../../../tests/standalone/Fsm/History.cpp), and
|
||
[serialization](../../../tests/standalone/Fsm/Serialize.cpp). These remain regression
|
||
inputs. Graph coverage was checked; Parallel/Direct constructor gaps were directly
|
||
read. Source inspection establishes the terminal-status and race-loser gaps.
|
||
|
||
## NEW execution and supervision contract
|
||
|
||
Design sketch; additions are not available APIs:
|
||
|
||
```cpp
|
||
namespace Void::Fsm {
|
||
struct Checkpoint {
|
||
std::uint32_t format_version;
|
||
std::string machine_type;
|
||
std::uint32_t application_schema;
|
||
std::uint64_t transition_sequence;
|
||
Json::Value state; // stable state IDs + app data
|
||
};
|
||
// Machine additions:
|
||
// run(execution_binding, Async::OperationOptions) -> Task<Result<Outcome>>;
|
||
// request_checkpoint(options) -> Task<Result<Checkpoint>>;
|
||
// restore_checkpoint(const Checkpoint&) -> Result<void>; // Idle only
|
||
// post(Event, options) -> Result<void>; // bounded admission
|
||
// terminal(Status) -> bool; // one shared predicate
|
||
}
|
||
```
|
||
|
||
Execution binding borrows Async executor/scope and Time clock contracts. Keep it
|
||
Fsm-specific binding data, not another cancellation/deadline context; all public
|
||
operations use `Async::OperationOptions`. Machine state runs on one logical strand.
|
||
Cross-thread posts enqueue owned event envelopes; only that strand mutates active
|
||
state, timers, waiters and transition history. Service lookups return owning handles
|
||
retained across await, per [Service](Service.md).
|
||
|
||
Machine has a root Async scope and each entered state has a child scope. Exit first
|
||
closes state-event admission, requests child stop, joins child work, removes waiters
|
||
and timers, then runs bounded exit cleanup and enters the next state. No queued
|
||
resume targets a destroyed state. A failed exit cleanup faults the machine after
|
||
joining all remaining scopes. Stop has a separate completion reason; the first
|
||
version retains existing Status values and adds `termination_reason` rather than
|
||
silently treating cancellation as application success or introducing unreviewed enum
|
||
values. Terminal predicate includes Faulted everywhere.
|
||
|
||
Parallel-all joins every child before producing the outcome tuple; a system fault
|
||
requests sibling stop and joins before returning the fault. Parallel-any selects one
|
||
winner on the machine strand, requests stop for all losers and awaits their joins
|
||
before returning the winner. Simultaneous-ready ties use child declaration order in
|
||
the same dispatch turn. Application Failure remains a typed outcome and can win a
|
||
race; system Fault remains a separate supervisory failure. Stop/deadline uses Async's
|
||
one-terminal arbitration. A noncooperative loser delays completion and is reported;
|
||
its frame is never abandoned to meet a latency target.
|
||
|
||
Supervision policies are explicit: default stop-on-fault; optional bounded restart
|
||
with Time-driven backoff, maximum three restarts per 60-second window, and 1,024
|
||
supervised machines. A faulted child is terminal in handles/counts/waits. Release
|
||
finished models from active supervision while acquired handles retain immutable
|
||
termination evidence and any still-required cleanup ownership. User observer callbacks
|
||
run outside orchestration locks; their exceptions report observer errors independently
|
||
from the machine's committed transition.
|
||
|
||
## Checkpoint algorithm and state compatibility
|
||
|
||
Checkpoints capture state boundaries: after the prior state's child scope and exit
|
||
cleanup finish, before the next state's entry causes new effects. A parked state may
|
||
offer an explicit application safe point that drains child work and serializes its
|
||
resume label. No arbitrary suspension point is implicitly restartable. A request
|
||
that cannot reach a boundary before its deadline fails without copying a live frame.
|
||
|
||
On the strand, freeze event consumption, assign a transition sequence, copy application
|
||
data and stable state paths/history into a bounded candidate, validate its schema,
|
||
then release the freeze. Optional queued events are persisted only through an explicit
|
||
registered serializable event schema and acknowledgement sequence; default checkpoint
|
||
excludes the mailbox and requires producer replay/deduplication. Relative monotonic
|
||
timers are application intent with restart policy, never raw process clock readings.
|
||
|
||
Default checkpoint contains format version, machine identity, application schema,
|
||
stable state IDs and transition sequence. State IDs are declared durable names, not
|
||
compiler type-name spellings. Restore validates all IDs/schema/limits into a private
|
||
Idle machine and commits its prepared state once; invalid data or migration exceptions
|
||
leave it unchanged. Resume executes state entry from the selected boundary. Application
|
||
side effects require idempotent occurrence/operation IDs or an external transaction;
|
||
checkpointing does not promise exactly-once effects. [Scheduler](../subsystems/Scheduler.md)
|
||
owns durable job occurrences; Fsm owns their workflow state.
|
||
|
||
## Bounds and backend rationale
|
||
|
||
Initial implementation remains native C++ coroutines/reflection and reuses Async
|
||
structured scopes. No external workflow engine. Default mailbox 1,024 events/4 MiB,
|
||
256 deferred events, 1,024 timers, 128 live child regions, hierarchy depth 32, 256
|
||
retained transitions and checkpoint 4 MiB. Event types must provide payload accounting
|
||
for variable data. Overload is returned before enqueue; reserved control messages
|
||
ensure stop/checkpoint can progress under user-event saturation. Control capacity is
|
||
bounded by live scopes and requests, not an unbounded priority queue.
|
||
|
||
One dispatch turn processes at most 64 events or 1 ms measured by injected Time before
|
||
yielding; tests use event counts to avoid real-clock flakiness. Expired waiters are
|
||
removed before state destruction. Low-level hooks remain optional so Fsm does not
|
||
require an observability exporter or Runtime. Profile tick/transition/race/checkpoint
|
||
p50/p95/p99, throughput, frame/event allocations, peak RSS/CPU and reflection compile
|
||
cost under [PERFORMANCE](../PERFORMANCE.md); no results are asserted.
|
||
|
||
## Ordered implementation backlog
|
||
|
||
All rows are PLANNED.
|
||
|
||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||
| --- | --- | --- | --- |
|
||
| M-FSM-01 | P0 / current source | Characterize status, supervision ownership, event waits and race losers | Faulted discrepancy and indefinitely parked race fixture recorded; no claim of safe cancellation / sol_implementer |
|
||
| M-FSM-02 | P1 / M-FSM-01; M-ASYNC-03 | Inject executor/clock, root/state scopes, waiter/timer ownership | Stop at each suspension frees only after join; borrowed execution outlives final cleanup / astra_implementer |
|
||
| M-FSM-03 | P2 / M-FSM-02; M-SERVICE-02 | Structured parallel/race, terminal predicate, bounded mailbox/history and supervision | Losers stopped/joined; faults terminate all handle/wait APIs; old provider survives await / astra_implementer |
|
||
| M-FSM-04 | P2 / M-FSM-03; Data schema gate | Boundary checkpoint, stable state IDs, validate-then-restore and schema migrations | Checkpoint during mutation waits for safe point; invalid restore leaves Idle candidate unchanged / astra_implementer |
|
||
| M-FSM-05 | P3 / M-FSM-04; Plugin quiescence specification | Reloadable workflow adapter, restart policies, examples and profile harness | Reload migrates application state without frames; fault/restart cap and cleanup evidence visible / sol_implementer |
|
||
|
||
## Validation and migration
|
||
|
||
CURRENT command:
|
||
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
|
||
not rerun for documentation. PROPOSED tests require NEW scope/checkpoint APIs: race
|
||
winner with forever-waiting cooperative loser, fault during child exit, timeout versus
|
||
event delivery, queued timer after state exit, nested cancellation, event saturation,
|
||
observer reentrancy/throw, Faulted supervision, checkpoint/transition simultaneity,
|
||
schema migration failure, and restart after effects with operation-ID deduplication.
|
||
Use fake clocks and deterministic strand stepping before sanitizer stress runs.
|
||
|
||
Keep existing state declaration/reflection syntax where possible. EXISTING
|
||
`MachineOptions{.own_worker=false}` maps to explicit injected execution; owning worker
|
||
construction becomes an opt-in adapter. JSON `{state,data}` gets an explicit legacy
|
||
checkpoint reader with declared machine/schema defaults; unknown compiler-derived
|
||
state names require a migration map. Old race-any behavior is documented until the
|
||
major-release switch to join-losers; no silent semantic change. Rollback preserves
|
||
legacy readers and the original persisted checkpoint until the new version validates.
|
||
See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
|
||
[DEPENDENCIES](../DEPENDENCIES.md), and [DELIVERY](../DELIVERY.md).
|