plusthree design #
Status: accepted (2026-11-17). This file is the canonical design; change it in the same commit as any change that departs from it.
plusthree is a high-performance Rust port of XState v6. A statechart can be defined in typed Rust (a builder or a proc macro) or loaded from XState MachineJSON at runtime. Both paths compile into the same flat table form (the IR) and run on the same kernel. The kernel is sans-I/O and no_std + alloc: it never sleeps or spawns anything itself, and returns effects as data for the host to carry out.
1. Goals and non-goals #
Goals
- Correct XState v6 semantics. The reference is
xstate@6.0.0-beta.3(commit8e53990), checked with differential tests against real XState (§9). Correctness wins over parity: where XState has a bug or an accidental quirk, plusthree does the correct thing and records the difference (§2). - One IR and one kernel shared by typed and JSON-loaded machines. Any semantic difference between the two paths is a bug.
- Typed by default. User-defined context, event, effect, emitted-event, input and output types. No
serde_json::Valueunless the user chooses it. - Fast. No allocation per event in steady state. Bitset configurations. Transition plans precomputed when the machine is built. Targets are in §10.
- Pure, deterministic core.
step(machine, &mut snapshot, event) -> effects, with logical timers stored in the snapshot. The host owns the clock and I/O. The same core runs under tokio, embassy, WASM, or a test with simulated time. - Compatible with the XState ecosystem: MachineJSON import, the persisted snapshot format, and inspection events. That makes Stately tooling and existing definitions usable.
Non-goals for v1
- Running JavaScript or other code embedded in JSON (
@code,@expr). JSON machines bind named implementations from a Rust registry. An evaluator trait can come later. - SCXML semantics. plusthree is an XState port, not an SCXML engine; an SCXML profile is not planned (§11).
- Durable execution (
createAsyncLogicwith journaledenq.step), and observable, listener and subscription actors. no_stdwithoutalloc.- Generating Rust code per machine. v1 interprets the tables. Codegen is a post-0.1 option (§10).
2. Semantics contract #
The reference is XState v6 native semantics. The highlights, all confirmed in the v6 source:
- State kinds:
atomic | compound | parallel | final | history(shallow|deep) | choice.- A compound state must declare
initial. - Final states are inert: they take no transitions and start no invokes.
- A
choicestate is rewritten into itsalwaystransitions.
- A compound state must declare
- Transitions: either an object
{target, context patch, input, reenter, meta}or a transition function returningOption<Transition>.- A function that returns
Noneand enqueued nothing is not enabled. Selection then falls through to the ancestors. - There are no arrays of guarded transitions. Only JSON import accepts them, as consecutive guarded transitions (§7).
- A function that returns
- Transition domain (port
getTransitionDomain+narrowParallelDomainfrompackages/core/src/stateUtils.tsverbatim):reenterdefaults to false.- Targets inside the source: the domain is the source with
reenter: true. Otherwise the domain is narrowed through parallel nodes. - Otherwise: the LCA of source and targets, narrowed through parallel nodes unless
reenter: true. Narrowing means a transition only exits the parallel region that contains its targets. - Special case: a history target that restores the source itself must exit and re-enter the source.
- Priority:
- Conflicting transitions (their exit sets intersect): the one whose source is a descendant wins, otherwise document order.
- Event matching: exact name first, then wildcard descriptors longest first.
- Order inside a microstep (§6.3 has the full list):
- Record history.
- Exit states deepest first. For each: its exit function, then stop its invokes.
- Merge transition context patches in document order.
- Enter states in document order. For each: spawn invokes, entry function, initial/history default content,
xstate.done.stateevents.
- Macrostep: the external event, then loop: eventless transitions first, otherwise the next internal event. Starting spawned or invoked children is deferred to the end of the macrostep.
- Errors abort the whole macrostep.
- If some active state handles
xstate.error.execution(onError), the macrostep reruns from the pre-event snapshot with that event. - Otherwise the status becomes
errorand all children are stopped.
- If some active state handles
- Rewritten sugar:
after,timeout,onTimeout,onDoneandonErrorbecome category events plus payload matchers. The delayed ones become logical timers scheduled on entry and cancelled on exit.
Correctness over parity. XState is the oracle wherever it behaves as intended. We do not reproduce its bugs, JavaScript artifacts or accidental behaviour. When we judge XState wrong, we:
- write down the correct behaviour and why, as an entry in
DEVIATIONS.md(citing XState docs, SCXML, or an invariant such as "the configuration is always valid"); - add a Rust test that asserts the correct behaviour;
- add the affected steps to the replay allow-list with the deviation ID and the fields or effects it changes, so every other step, and the rest of those steps, is still compared.
Where XState's intent is unclear, prefer its documentation, then SCXML, then the simplest rule that keeps the invariants. Intended v6 design choices that differ from SCXML (§2 above, such as domain narrowing and reenter: false) are not bugs; we keep them. So is the asymmetry where an unhandled child error fails the parent while an unhandled child done event is ignored: errors escalate, completion is informational (conformance NOTES #9).
Deviations from v6.
| # | Deviation | Why |
|---|---|---|
| D1 | max_microsteps defaults to 10,000 (v6: unbounded unless maxIterations). Hitting it raises an execution error. |
Infinite eventless loops must not hang a no_std target. |
| D2 | A transition function runs exactly once per selection (v6 can run it twice; #5910). | Determinism and speed. Visible only if a user function has side effects outside enq. |
| D3 | Panics are not caught by the kernel. Only Err returned from user code becomes xstate.error.execution. |
no_std, and Rust convention. The std runtime can opt in to catch_unwind. |
| D4 | A transition into a history state always yields a valid configuration. v6 computes the domain from pre-microstep history but enters the newly recorded value, which can enter an invalid configuration. The kernel picks one consistent rule and documents it in DEVIATIONS.md. |
Valid configurations are an invariant. |
| D5 | Final states schedule no after/timeout timers. v6 schedules them and later fires an empty microstep. |
Final states are inert. |
| D6 | Document order is the order written in the source, including JSON keys that look like integers. v6 inherits JS Object.keys order (integer-like keys first). |
JavaScript artifact. |
| D7 | A timer consumed in a macrostep that errors and recovers is gone from the recovered snapshot. v6 leaves it listed, and it never fires. | A dangling timer that can never fire is a bug. |
| D8 | An invoke with a timeout keeps the context patch on its onDone/onError transitions. v6 wraps them in a function and drops the patch. |
Bug. |
| D9 | A JSON action list that assigns produces a patch of only the keys it assigns. v6's machineFromJSON returns the whole {...pre, ...patch} context, so a later transition in the same microstep (for example in another parallel region) undoes an earlier one's patch. |
Bug; seen in random traces 0031, 0059, 0074, 0098. |
| D10 | JSON matches compares values by JSON equality. v6 uses Object.is, so object and array values never match. |
JavaScript artifact. |
| D11 | JSON after keys must be plain decimal milliseconds. v6 runs them through Number(), so "", " 20 ", "0x14", "1e3" and "-5" are accepted. |
JavaScript artifact. |
| D12 | An unparsable delay string is a load error at its JSON path. v6 silently uses parseFloat(s) || 0. |
Silent misconfiguration. |
| D13 | All JSON transition and choice-branch targets are resolved at load. v6 checks targets of transitions with actions, and of choice branches, only when first taken. | Errors belong at load time. |
| D14 | A root's own on["xstate.route"] is kept alongside generated routes. v6 silently replaces it when routes exist. |
Silent data loss. |
| D15 | Selection visits parallel regions (event selection) and active atomic states (eventless selection) in document order, and history values are listed in document order. v6 uses JS Set insertion order, where a re-entered state moves to the end. |
JavaScript artifact; SCXML and this section use document order. |
| D16 | An unrecovered execution error cancels every pending timer (Cancel effects, empty timer list) and stops every child, removing it from the snapshot. v6 keeps the timers listed though they never fire, and keeps the stopped children listed. |
The snapshot lists only timers that can fire (as D7) and children that run. |
| D17 | No Start effect is emitted for a child that was stopped earlier in the same macrostep, and no second Stop for a child already stopped. v6 still emits @xstate.start for it, and @xstate.stop again. |
Starting a stopped actor is a bug (conformance NOTES #10). |
| D18 | Messages between actors go through one FIFO system queue, and each actor's macrostep completes and is published before the next message is delivered, as in v6's systemTransition. v6's createActor runtime delivers synchronously and depth-first, so a child's macrostep can finish before the sender's is published. plusthree-system and plusthree-runtime both use the FIFO order. Replay compares each actor's own macrostep sequence and the causal order of messages, not the global interleaving. Events still queued for an actor when it stops are dead letters (reason stopped); systemTransition drops them silently. |
XState's two runtimes disagree; run-to-completion per actor and one deterministic order (NOTES #12). |
| D19 | Restored timers keep their remaining delay under any clock: the persisted snapshot carries each timer's deadline relative to the system's now. v6 restarts the full delay unless the clock is wall-clock. |
Restoring must not change when a timer fires (NOTES #14). |
| D20 | An error in the initial macrostep is never recovered: there is no pre-event snapshot to return to. The machine ends with status error, its initial context, an empty configuration, and a published transition event. v6 recovers only through a root onError, skips the root's entry, publishes no transition, and leaves a snapshot with no value or context. |
Consistent with the error model; no half-built snapshots (NOTES #18). |
| D21 | An inspection event's sent lists each delayed send or raise with its own event. When a later send replaces one under the same id in the macrostep, v6 shows the replacing event in both entries. |
Inspection describes what was scheduled. |
3. Architecture #
plusthree facade crate: re-exports, prelude, feature flags
├─ plusthree-ir no_std+alloc. Builder, validation, flattening, desugaring, interning -> MachineDef
├─ plusthree-core no_std+alloc. Kernel: Snapshot, step/initial, selection, microstep, effects buffer, rollback journal
├─ plusthree-derive proc macros: #[derive(Context, Event, Children)], machine! DSL (emits builder calls + typed handles)
├─ plusthree-json std. MachineJSON import/export (machine.schema.json), Registry of named impls, persisted snapshot serde
├─ plusthree-system no_std+alloc. Pure actor-system reducer (port of systemTransition / advanceSystemTime)
├─ plusthree-runtime std. Mailbox actors, clock adapters: tokio, std thread, simulated; embassy behind a feature
├─ plusthree-inspect std. @xstate.actor / @xstate.transition events, Stately inspector bridge
└─ (dev) conformance/ differential harness vs XState (Node), ported v6 tests, SCION corpus (later)
(dev) plusthree-bench criterion + gungraun instruction counts, cross-library scenarios
- Edition and MSRV: Rust 2024 edition, MSRV = the stable release 2 versions back.
- Unsafe:
coreandirare#![forbid(unsafe_code)]until a benchmark justifies an exception.
4. The IR (MachineDef) #
The builder, the macro and JSON import all produce a MachineDef. It is validated, flattened and immutable once built. Building happens once (OnceLock, or LazyLock for statics). After that, everything is index-based.
4.1 States #
States are numbered in pre-order, so StateId(u32) is the document order (v6 order). The tables use struct-of-arrays layout:
| Field | Meaning |
|---|---|
parent: [StateId] |
parent (the root points to itself) |
depth: [u8] |
depth in the tree |
kind: [Kind] |
atomic, compound, parallel, final, history(shallow|deep), choice |
subtree_end: [StateId] |
descendants of s are exactly s+1 .. subtree_end[s] |
initial: [Option<TransitionId>] |
compound states: a transition with Trigger::Initial, static targets or a function, plus input and meta |
children: [Range] |
into a child_ids array (sorted, contiguous; history states excluded, as v6 getChildren) |
entry / exit: [Option<FnId>] |
at most one entry and one exit function per state (v6) |
transitions: [Range] |
the state's own transitions, contiguous in TransitionId order; always: [Range] and the candidate index (§4.3) point into them |
history_default: [Option<TransitionId>] |
history states only (Trigger::HistoryDefault) |
invokes: [Range], timers: [Range] |
into the invoke table and the timer table (desugared after/timeout/invoke timeout, in v6 scheduling order) |
tags, meta, key, id |
metadata; id is interned and used for #id targets and StateValue |
Consequences:
is_descendant(a, b)isb < a && a < subtree_end[b], which is O(1).- "Active descendants of d" is
config & range(d+1, subtree_end[d]), computed with word masks. No per-state mask is stored. - Entry order is ascending bit order and exit order is descending bit order, so nothing is ever sorted.
4.2 Transitions #
struct TransitionDef {
source: StateId,
trigger: Trigger, // Event(TriggerKey) | Wildcard(WildcardId) | Always | Initial | HistoryDefault
guard: Option<FnId>, // matches pattern or guard, checked before the body
body: Body, // Static { targets, reenter, patch } | Function(FnId)
input: Option<FnId>, meta: Option<DataId>,
cancel_timer: Option<TimerId>,// invoke completion transitions of a timed invoke (v6 cancels the timeout)
plan: Option<StaticPlan>, // precomputed when the whole entry set is static
}
struct StaticPlan { domain: Option<StateId>, exit: Range<u32>, enter: StateSet, default_entry: StateSet }
- Static transitions get their domain, exit scope and entry set precomputed at build time. At runtime, the exit set is just
config & exit.exitisrange(domain+1, subtree_end[domain]), widened to include the domain when a reentering transition's domain is its own source, everything when the domain isNone, and empty when there are no targets.default_entryis v6'sstatesForDefaultEntry: entered compound states in it run their initial transition's content (input or function). - A plan is built only when the entry set is fully static: no history target, and default-entry completion reaches no history state and no function initial.
- Function transitions, and transitions targeting history, compute their domain at runtime (
resolve, thenenter_setafter history is recorded). That costs O(depth) with the parent/depth arrays. The states entered, ancestors included, use the history value recorded by this microstep's exits (D4); the domain is computed from the value before the microstep, which gives the same domain because a history value only changes when its parent is exited. Results for a given (source, targets, reenter) can be cached in a small LRU per machine. Benchmarks will decide whether that cache is worth having. - Default-entry completion:
default_entry[s]is a precomputedStateSet: s plus its initial chain, plus every region of each parallel state, applied recursively, together with itsstatesForDefaultEntry. When the expansion reaches a history state or a function initial it depends on runtime data, so no entry is stored and the runtime walk expands it. Entering a state by default is then one OR. This costs n² bits. Above 2,048 states the table is not built and default entry is computed by walking the tree instead.
4.3 Events and candidate lookup #
- Event names are interned into an
EventId(u32)at build time.- Typed machines have a closed alphabet:
#[derive(Event)]gives each variant a name (Event::NAMES, and theconst fnEvKind::Inc.name()on the generated fieldlessEvKind) andEvent::index(&self), the declaration index, which is amatchon the discriminant. The machine maps indices toEventIds with a table built once fromNAMES. - JSON machines with untyped events intern unknown names on demand. A name the machine never mentions can only match wildcards.
- Typed machines have a closed alphabet:
- Built-in events never use strings. Each v6 built-in event (
xstate.done.state,xstate.after,xstate.timeout.state,xstate.done.actor,xstate.error.actor,xstate.snapshot.actor,xstate.timeout.actor,xstate.error.execution) has a reservedEventId, and triggers are keyed byTriggerKey { event, arg }: the arg is theStateIdfor done.state, theTimerIdfor after and timeout.state, and theInvokeIdfor actor events. v6'smatches: {stateId}payload check therefore becomes a direct lookup. The names stay interned so user wildcards such as*orxstate.done.*match built-in events, as in v6. StateonErroris the v6 wildcardxstate.error.*. - Per-state candidate index: a sorted slice of
(TriggerKey, Range)into a shared list ofTransitionIds. A lookup with a specific arg falls back to the arg-less key.- It is precomputed with v6's
getCandidatesorder: exact matches first, then wildcards longest first. - Lookup is a linear scan for 8 entries or fewer, otherwise a binary search. When states × events ≤ 2^18 (and states ≤ 2,048), a direct
(state, event) -> Rangetable answers arg-less lookups in one load. - Per event, a
StateSetof the states with candidates for it (the listeners), plus one for wildcard groups, is built under the same state limit. Selection visits onlyconfig ∩ listeners(event), replaying v6's recursion over those states in pre-order with a stack of states waiting for their descendants; an event no active state listens to is unhandled without touching the tree. - The wildcard matches are folded into every interned event key at build time, so a lookup never has to fall back to wildcards. Names interned later (open alphabets) use
wildcard_candidates(state, name). - Final states have no candidates (v6: they take no event transitions); their eventless transitions remain.
- It is precomputed with v6's
- User
matchespatterns (shallow payload equality) become a predicateFnIdchecked before the transition body runs.
4.4 Semantics profile #
MachineDef carries Semantics { domain: V6 | Scxml, default_reenter: bool, matching: Exact | Prefix, errors: AbortMacrostep | QueueErrorEvent }. Only default_reenter exists; the other fields would arrive only with an SCXML profile, which is not planned (§11).
5. Typed API #
5.1 Types #
pub trait Types: 'static {
type Context: Context; // #[derive(Context)] or serde_json::Map for JSON machines
type Event: Event; // #[derive(Event)] enum
type Effect; // user action enum, executed by the host
type Emitted; // enq.emit payloads
type Input; type Output; type Error;
type Children: Children; // #[derive(Children)] enum, `()` when the machine has no children
}
pub trait Context: Clone {
type Patch: Default;
/// Apply a shallow patch; return the inverse patch (old values) for rollback.
fn apply(&mut self, patch: Self::Patch) -> Self::Patch;
}
Why patches instead of mutable context. In v6, transition functions run during selection against the context as it was before the microstep. Their patches are merged later, in document order, after the exit functions have run. A patch reproduces that exactly. It is also data, which makes it serializable, comparable in differential tests, and invertible for rollback.
#[derive(Context)] on struct Ctx { count: u32, name: String } generates CtxPatch { count: Option<u32>, name: Option<String> } with setter methods. For a JSON machine whose context is a serde_json::Map, the patch is a map and gets v6's {...ctx, ...patch} behavior unchanged.
Escape hatch: a user can implement Context by hand with type Patch = Self, which replaces the whole context.
What inspection may show. Context::show_fields passes inspection the fields it may show as FieldValues (flags, numbers, text, durations in milliseconds); its default passes none. #[derive(Context)] overrides it only when fields are marked #[context(show)] (through ShowField) or #[context(show_with = path)], so nothing shows unless marked and unmarked contexts generate no extra code. VariantName (#[derive(VariantName)]) names an enum value by its variant, never its data; a shown field of such a type shows its variant name, and inspection names effects with it. Both live in core so the derives work without the inspect feature; the kernel never calls them.
5.2 Implementations #
pub struct Args<'a, T: Types> { pub context: &'a T::Context, pub event: &'a Envelope<T::Event>,
pub state: StateView<'a, T>, inputs: &'a [(StateId, StateInput)] } // a.input()
pub struct Transition<T: Types> { target: Targets, patch: Option<<T::Context as Context>::Patch>,
reenter: Option<bool>, input: Option<StateInput>, meta: Option<MetaId> }
type TransitionFn<T> = dyn Fn(&Args<T>, &mut Enq<T>) -> Result<Option<Transition<T>>, T::Error> + Send + Sync;
type ActionFn<T> = dyn Fn(&Args<T>, &mut Enq<T>) -> Result<Option<Patch<T>>, T::Error> + Send + Sync; // entry/exit
- Storage: implementations live in
Arc<dyn Fn ...>, created once at build time. A call costs one indirect call, the same as afnpointer, and closures can capture data (JSON registries need this). - Ergonomics: helper traits let users return
Option<Transition>,Transition, or()instead of the fullResulttype. - State input (v6
input,_stateInputs): a transition's input is computed once, against the snapshot before the microstep, by an input function (TransitionDef::input) or set by a transition function withTransition::input(v). After the exits, the inputs of states no longer active are dropped, then each target the transition entered gets the input; a compound state entered by default gives its initial's input to the initial targets after its entry function.a.input()reads the source's input: guards and transitions see it as of before the microstep, exit functions the old input, entry functions, delays and outputs the new one. AStateInputis anAnyData(anyDebug + Send + Syncvalue; JSON machines useserde_json::Value), soTypesgets no input type; persisting needs a JSON object held as aserde_json::Value.Argsstores the snapshot's input slice and looks the input up on demand, so buildingArgsfor a guard costs no lookup.
Enq<T> writes into the caller's effects buffer, which is reused across events: enq.action(T::Effect), enq.raise(ev), enq.raise_after(ev, delay, id), enq.cancel(id), enq.emit(T::Emitted), enq.send_to(addr, ev), enq.spawn(src, opts), enq.stop(addr), enq.log(..).
User actions are a data enum (T::Effect) that the host interprets. That is what makes them allocation-free, serializable and assertable in tests. A user who really wants callbacks can make type Effect = Box<dyn FnOnce(&mut Host)>.
5.3 Definition surfaces #
Builder: the foundation, used by tests and by JSON import.
let m = Machine::<Counter>::builder("counter")
.initial("active")
.state("active", |s| s
.on_fn(EvKind::Inc, |a, _| Transition::<Counter>::stay().patch(|p| p.count(a.context.count + 1)))
.after(Duration::from_secs(5), "idle"))
.state("idle", |s| s.on(EvKind::Inc, "active"))
.build()?; // validation errors carry the state path
- One method per transition form.
on(kind, targets)is a static transition,on_fn(kind, |a, enq| ..)a transition function, andon_with(kind, |t| t.to(..).guard(..).action(..))a static transition with a guard, content orreenter;always,after,on_doneandon_errorfollow the same pattern. One genericonthat accepted both targets and closures would lose closure signature inference, so every handler would need annotated arguments. - One annotation remains: Rust types
Transition::stay().patch(|p| ..)before it learns the closure returnsTransition<Counter>, so the builder needsTransition::<Counter>::stay()(orwith_patch).machine!handlers do not: the macro declaresTransitionas the machine's transition type around each handler. - Wildcards:
on_wildcard("user.*", ..)(with_fnand_withforms) adds a transition for a v6 wildcard descriptor:*, or a prefix ending in.*, which also matches the prefix itself (user). A descriptor with an infix*, which v6 never matches, is a build error. The handler signature is the same as foron, becauseArgs::eventis already anEnvelope: a handler that can see any event reads it from there (a.event.event()for the user event, or amatchon the built-in variants). - Delay functions are named, as in v6's
delays:delay("backoff", |a| ..)declares one on a state for it and its descendants (a nearer declaration shadows), andaftertakes aDurationor a delay name. Entries with the same delay, fixed or named, share one timer and are tried in order. A name nobody declares is a build error. - Function initials:
initial_fn(|a, enq| ..)computes a compound state's initial child. - State input:
TransitionBuilder::input(|a| value)on any transition, andinitial_with(|t| t.to("child").input(|a| ..))for an initial with an input.a.sourceis the state, soa.resolve(".child")names a child;machine!handlers use the typed handles. - Invoke:
invoke(|a| Kids::Fetch(..), |i| i.id("f").on_done(..).on_error(..).on_snapshot(..).timeout(delay, ..))adds a v6 invoke. The source closure builds the wholeT::Childrenvalue, input included, when the state is entered.InvokeBuilderhas the three transition forms foron_done,on_errorandon_snapshot;timeouttakes aDurationor a named delay. Handlers read the child's typed data witha.actor_output(),a.actor_error()anda.actor_snapshot(), which returnNonefor other events. - Spawned children: actions use
enq.spawn,enq.stopandenq.send_to.on_actor(ActorEvent::Done | Error | Snapshot, "id", ..)handles one child's events by id, like v6on: { "xstate.done.actor.id": .. }: a transition on the built-in actor event, with a guard on the actor id that runs before the transition's own guard. It also sees an invoked child's events, before the invoke's own transitions, which is v6's order. - The builder numbers the
FnIds itself and builds the IR tree, so its errors are the IR'sBuildErrors with their state paths.
Macro: sugar over the builder. It checks references at compile time and generates typed state handles.
#[derive(Context, Clone, Default)] struct Ctx { count: u32 }
#[derive(Event)] enum Ev { Inc, Add { n: u32 }, Reset }
#[derive(Debug)] enum Fx { Beep(u32) }
plusthree::machine! {
Counter { context: Ctx, events: Ev, effects: Fx }
id: "counter",
initial: active,
states: {
active: {
on: {
Ev::Inc => |a, _| Transition::stay().patch(|p| p.count(a.context.count + 1)),
Ev::Add { n } => |a, enq| { enq.action(Fx::Beep(*n)); Transition::stay().patch(|p| p.count(a.context.count + n)) },
Ev::Reset => idle,
},
after: { 5s => idle },
},
idle: { on: { Ev::Inc => active } },
}
}
// generated: Counter::machine() -> &'static Machine<Counter>, mod counter::states { ACTIVE, IDLE }
// snapshot.matches(counter::states::ACTIVE)
- Event patterns as keys: a key like
Ev::Add { n }is a pattern. The macro generates the destructuring, so the handler receives typed fields. - Named implementations: handlers can also be paths to functions.
- Error locations: the macro emits one builder call per state, so validation errors point at the right source span. It also resolves every target,
initialand history default itself (v6resolveTargetrules), so a bad reference is a compile error on the offending token. - Targets and handlers: an identifier or dotted path (
idle,a.b,.child,#id) is a state; a closure, or a path with::(self::handler), is a transition function;{ target, guard, actions, reenter }is a static transition;[..]lists candidates. Inside handlers the macro declarestype Transition = Transition<Counter>, soTransition::stay().patch(|p| ..)needs no annotation, andtype Patchas the context's patch type, so an entry, exit oractionshandler returnsSome(Patch::default().count(n))without naming the generatedCtxPatch. - Wildcards: a string key in
onis a wildcard descriptor ("*" => ..,"user.*" => ..), checked at compile time. Its handlers seea.eventas anEnvelope. A binding,ev @ "user.*" => |a, enq| match ev { .. }, gives the handler the typed user event&Ev; built-in events skip such a transition, so it never has to handle them. - Delay functions:
delays: { backoff: |a| .. }on a state declares named delay functions for it and its descendants; anafterkey that is an identifier (after: { backoff => idle }) names one, and the macro checks it is in scope. - Function initials:
initial:takes a closure or a path with::as well as a child key; the function returnsTransition::to(handle). - State input: a transition object takes
input: |a| value(the event pattern's bindings are in scope), andinitial: { target: child, input: |a| value }gives the initial target an input. - Invoke:
invoke: { src: |a| Kids::Fetch(..), id: "f", registry_key: "k", on_done: .., on_error: .., on_snapshot: .., timeout: { 5s => slow } }, or a list of such objects.srcis required.on_done,on_errorandon_snapshottake a transition, or arms keyed by patterns over the child's typed output, error or snapshot, tried in order:on_done: { KidsOutput::Fetch(10) => big, KidsOutput::Fetch(n) => { target: small, actions: |_, enq| .. n .. }, _ => none }. A refutable arm on a static transition becomes a guard, its bindings are in scope in its handlers, and_also takes a completion without output. Targets and named delays are checked at compile time. - Child events in
on:"xstate.done.actor.<id>","xstate.error.actor.<id>"and"xstate.snapshot.actor.<id>"keys handle one child's events, spawned or invoked;out @ "xstate.done.actor.w"binds the typed data. They map to the builder'son_actor. Children are spawned from actions withenq.spawn.machine!does not generate theChildrenenum; declare it with#[derive(Children)]and pass it aschildren: Kids. - Handles:
StateRef<Counter>constants whoseStateIdis the state's pre-order index, computed by the macro;build()asserts them against the definition once. Handles are match patterns:Snapshot::leaf,leaf_in(region)andactive_child(parent)returnOption<StateRef<T>>, somatch snap.leaf(def) { Some(counter::states::IDLE) => .. }replaces a chain ofmatchescalls;leaveslists one active leaf per region. Children of a state live in a module named after it (player::states::on::modes::audio::MUTED).
6. Kernel #
6.1 Snapshot #
pub struct Snapshot<T: Types> {
status: Status, // Active | Done | Error | Stopped
config: StateSet, // active states incl. ancestors
context: T::Context,
history: SmallMap<StateId, StateSet>, // only history states that have a value
timers: TimerTable, // logical timers (v6 LogicalTimer)
children: Children<T>, // invoked + spawned; M4
state_inputs: SmallMap<StateId, StateInput>,
output: Option<T::Output>, error: Option<T::Error>,
counters: Counters, // next timer seq, next actor id
}
- Plain data. The snapshot holds no reference to the machine; you pass
&Machineintostep. It isSendwhenever its contents are, and cloning it never touches the machine. StateSetis a bitset that holds twou64words inline (up to 128 states) and moves to a heapBox<[u64]>above that. A const-generic[u64; N]variant is an optimization to try later.- Derived on demand, never stored:
value()(StateValue),tags(),matches(),has_tag(),can(event).canruns selection only and discards the scratch effects.
6.2 Entry points #
impl<T: Types> Machine<T> {
fn initial(&self, input: T::Input, fx: &mut Effects<T>) -> Result<Snapshot<T>, StepError<T>>;
fn step(&self, snap: &mut Snapshot<T>, ev: Envelope<T::Event>, fx: &mut Effects<T>) -> Outcome; // Handled | Unhandled | Errored
fn transition(&self, snap: &Snapshot<T>, ev: Envelope<T::Event>) -> (Snapshot<T>, Vec<Effect<T>>); // pure wrapper: clone + step
}
stepworks in place. It is the fast path.transitionmatches v6's pure API.- Observer and environment: each entry point has a
_withform (initial_with,step_with,fire_with,stop_with) that takes the actor environment (&()outside a system) and anobs: &mut impl Observer, which gets a callback for each microstep (transitions, exit/entry sets, effects).step_withtakes anEnvelope, so a system can deliver child events. The simple forms use the no-op()observer, which compiles away.Option<O>observes whenSome, so a host with optional inspection keeps one call. Tests and inspection use this hook. Outcome::Unhandledcorresponds to v6'sisUnhandled: no transition was enabled and no effects were produced, so the snapshot is unchanged.
6.3 Microstep, in bitset terms #
select(ev):
for atom in (config & atomic_mask) ascending:
for s in atom, parent(atom), ...: # walk ancestors
for t in candidates(s, key(ev)):
r = eval(t) # static: check matcher; function: call once, effects -> scratch range
if enabled(r): push (t, r) unless t already selected; next atom
resolve conflicts: exit(t) = config & range(domain(t)); a pair conflicts if exits intersect;
the descendant source wins, otherwise the earlier one;
losers' scratch effect ranges are dropped (counters rolled back)
microstep(T):
X = OR exit(t) # exit set
for h in history states whose parent ∈ X: history[h] = deep ? config&atomic&range(parent) : active children of parent
for s in X descending: exit fn -> patch+effects; Stop effects for s.invokes; config.clear(s); cancel s's timers
for t in T (selection order): apply patch (journal inverse); push its effects
E = OR enter(t) (static plan, or computed: targets + ancestors up to domain + default_entry/history expansion)
for s in E ascending: config.set(s); Spawn effects for invokes; schedule after/timeout timers;
entry fn; initial/history-default content; final -> push done.state internal
macrostep(ev):
journal.begin(); fx.mark()
T = select(ev); if T: microstep(T)
loop { T = select_eventless() (only if the last microstep changed anything); else pop internal queue; ... }
emit deferred Start effects; on error -> journal.rollback(); fx.truncate(mark); rerun with xstate.error.execution or set Error
- Work masks.
Machineprecomputesexit_work(exit function or timers),entry_work(entry function, timers, function initial, final) and the parents of history states. Exits and entries outside these masks are a single bit operation onconfig; the per-state loops run only when a mask intersects the exit or entry set. The plain microstep is the special case of one static transition with a plan (or a targetless one) touching none of the masks:config = (config − config∩exit) ∪ enteraround the transition content, exactly what the general microstep does in that case. The entry set is computed before the exits run, so function initials see the pre-microstep snapshot. - The internal queue is a
VecDequeowned by a reusable scratch area, together with the scratch effects and the selection list. Snapshots don't carry it. - The rollback journal records inverse context patches, the previous
config/history/timerswords, and counter values. It is cleared when the macrostep succeeds. Its buffers are reused, so the happy path never allocates.
6.4 Effects #
pub enum Effect<T: Types> {
Action(T::Effect), Emit(T::Emitted), Log(LogRecord),
Schedule { key: TimerKey, delay: Duration, timer: LogicalTimer<T> }, Cancel(TimerKey),
SendTo { to: Address, event: OutboundEvent<T> },
Spawn { slot: ChildSlot, src: T::Children, input: ChildInput<T> }, Start(ChildSlot), Stop(ChildSlot),
DeadLetter { reason: DeadLetterReason, event: OutboundEvent<T> },
}
- Log:
enq.log(value)and JSON@xstate.logproduceEffect::Log(LogRecord)in order with the other effects. ALogRecord(and aStateInput) is anAnyData: anyDebug + Send + Syncvalue behind anArc, read back withget::<V>(); JSON logs theargsarray as aserde_json::Value. - Order: effects come out in v6 order: exit side effects, then transition, then entry, with deferred starts last.
- Timers: the kernel records the logical timer in the snapshot and emits
Schedule, so a host can either drive time itself or persist the timer and resume later. A fired timer comes back asSysEvent::Timer(key). The kernel then consumes it, raising the delayed event internally or emittingSendTo, exactly as v6 handlesxstate.timer. Simulated time is a host concern (plusthree-runtime::SimClock).plusthree_core::host::Timers<H>is an optional host-side helper outside the kernel: it keeps the host's timer handle perTimerKeyand nets one step'sSchedule/Canceleffects into arm and disarm operations (a re-entered state yieldsCancel(k)thenSchedule(k); a state left byalwaysin the same macrostep yieldsSchedule(k)thenCancel(k)). host::Drivenremoves the loop every host that steps a machine itself repeated aroundTimers.Driven<'m, T, H, O = ()>owns&'m Machine<T>, the snapshot, the effects buffer, theTimers<H>and its op buffer, and an observerO.start(machine, input, scheduler)runsinitial;new(machine, snap)wraps a snapshot, andrestore(timers, scheduler)starts a restored snapshot's timers.step(event, scheduler) -> Outcome,fire(token, scheduler) -> Option<Outcome>andstop(scheduler) -> Outcomerun a macrostep and applyTimers, calling the scheduler for each arm (attaching the handle, and cancelling onearmedhands back) and each disarm.stopisstop_withand then cancels every timer still pending, for teardown.host::Scheduler<H>is the host's side:schedule(&mut self, delay, token) -> Handcancel(&mut self, H). It is a trait on one value, not two closures, because starting and stopping a timer usually need the same&mutcontext (a GUI toolkit's, Parcel's transaction), which two closures cannot both borrow. Calls takeimpl Scheduler<H>by value and&mut Sis a scheduler, so a host passes&mut ctxand keeps it, or a temporary.schedule_with(schedule, cancel)builds one from two closures; inference goes through its signature (Hcomes fromschedule's return, socancelcan call methods on it), which a tuple of closures would not give. The calls are monomorphized, so a scheduler costs what its methods do.NoTimers(panics if a timer starts) serves machines without timers and a start before the host's scheduler exists;Recorderis the shared test scheduler.- The caller's own effects stay in the buffer, timers removed and in order, readable with
effects()or drained witheffects_mut(); the next call clears them as the kernel does, and a stalefire(None) clears them too, so effects read after each call are never seen twice. Becauseschedulereturns the handle synchronously, a timer cancelled before it has a handle can only be one scheduled and cancelled in the same macrostep, whichTimersnets away; hosts that start timers later than they step useTimersdirectly, whosearmedhands a stale handle back. Steady state allocates nothing (the S7 allocation gate runs throughDriven), and the kernel is unchanged, so hosts that don't use it pay nothing. host::Watch<T>: Observer<T>is how an observer sees aDriven's macrosteps whole:before(Macrostep)(Event(&T::Event),Timer(&TimerKey)orStop) andafter(&Snapshot<T>), both defaulting to nothing, called only byDriven, never by the kernel, sostep_withusers andReportkeep their exact behaviour.()andOption<O>implement it.plusthree-inspect'sActorHandleimplements it by taking the event's name (or what itsshow_eventsclosure makes of it, the per-actor form ofReport::step_showing, sinceDriven::steptakes no per-call closure) before the step and callingsteppedafter it, withxstate.timerfor a fire andxstate.stopfor a stop; as the observer it already collects the transitions to highlight. A host keepsDriven<.., Option<ActorHandle>>and one code path whether inspection is on or off. The alternative, aReportmethod that takes aDriven, would have kept two call forms per host and put the inspector in the timer path; making the kernel call the hooks would have reported twice for hosts that callstep_withthenstepped.
7. JSON (plusthree-json) #
- Import:
Machine::from_json(json, &Registry<T>)parses v6machine.schema.jsoninto the builder. It returns aJsonMachine<T>, which derefs toMachine<T>and keeps the lowering's tables: v6 event objects for built-in events, and the persisted-snapshot format. JSON machines useT: JsonTypes(context, events, emitted events, output and errors areserde_jsonvalues; effects, input and children are the host's).Registrymaps names to the implementations a machine refers to: actions, guards, actors, delays.- Input. As in v6, the initial macrostep processes
xstate.initwith the machine input:Envelope::Initcarries it (typed code reads it witha.event.input()), and JSON code sees{"type":"xstate.init","input":..}throughJsonArgs::event(). A JSON machine's input type must serialize;JsontakesOption<Value>, whereNoneis v6'sundefined. - Built-in serialized actions (
@xstate.raise,@xstate.assign,@xstate.emit,@xstate.log,@xstate.cancel) and guards (@xstate.not,@xstate.stateIn) are implemented natively.@xstate.logis a no-op until the kernel has a log effect. A name the registry lacks is a load error at its JSON path. - Lowering (
MachineJson::lower) produces theMachineDefplus descriptor tables saying what eachFnId/DataIdis (guards, action lists, choice functions, literals, registry names), each with its JSON path, and the v6 identity of every transition and timer. - Each JSON transition object stays a static IR transition:
matchesandguardbecome its guard,contextandactionsits patch function, so static plans survive. Arrays of guarded transitions (allowed only in JSON) become consecutive transitions for the same trigger, which the kernel tries in order: the first enabled one wins, as in v6, which keeps them as separate definitions. - Departures from
machineFromJSON(JavaScript artifacts, §2): document order is the written order (D6); an action list's patch is only what it assigns, not v6's whole{...context, ...patch}, which lets a later parallel transition undo an earlier one's patch;matchescompares JSON values, notObject.is;afterkeys are milliseconds only when they are plain decimals, not anythingNumber()accepts; an unparsable delay string is an error, notparseFloat(s) || 0; targets of transitions with actions and of choice branches are resolved and checked when loading, not when first taken; a root's ownon["xstate.route"]is kept alongsideroutetransitions instead of being replaced. @codeand@exprare rejected with a clear error (non-goal).
- Export:
ToJson::to_json()exports any built machine (builder,machine!or JSON) as MachineJSON for Stately Studio, the visualizers and the Stately Inspector. It reads theMachineDefand turns the IR's desugared forms back into v6 sugar:aftertimers becomeafterkeys, timeoutstimeout/onTimeout, invoke completions the invoke'sonDone/onError/onSnapshot(dropping the transition v6 adds to cancel an invoke timeout),xstate.error.*on a state that declares itonError, and a state's own done eventon["xstate.done.state"]withmatches: {stateId}, the form v6 JSON writes it in. Targets are written relative to the source (.child, a sibling path) or as#id. A state gets an explicitidonly when its id is not the default path, so the exported tree has the idsMachineDef::id_ofgives (the Inspector relies on that).- What a handle stands for. For a JSON machine, the lowering's descriptors: the JSON exported is the JSON loaded, normalized as below. For a built machine, each
FnIdhas aLabel:Namedfor a path handler inmachine!(self::is_positive→is_positive; the macro passes the name, since it wraps every handler in a closure) and for a function item given to the builder (its last path segment, fromcore::any::type_name);Anonymousfor a closure;Actor { actor, guard }for anon_actorguard, exported asmatches: {actorId}plus the inner guard. Named delays are named by their declaration. - Names of closures. An anonymous implementation is named after where the machine uses it, in JSON path terms rooted at its state's id:
{id}.entry,{id}.exit,{id}.output,{id}.initial.input,{id}.choice,{id}.invoke[k](the source), and for the transition at indexiof a list,{id}.on.{event}[i],{id}.always[i],{id}.after.{key}[i],{id}.onError[i],{id}.onTimeout[i]or{id}.invoke[k].onDone[i](andonError,onSnapshot,onTimeout), with.guard,.actionsor.inputappended for its parts. The name depends only on the machine's structure, so it is stable across builds and unique in the machine. - Where MachineJSON has no slot for a function. Guards and transition content are
{"type": name}. A transition function is a targetless transition whose one action names it ({"actions": [{"type": name}]}, keeping its guard): its targets are decided at run time, and a diagram shows the name on the edge. A choice function, an input or an output function is a code reference,{"@code": name, "@lang": "plusthree"}; XState loads it with an evaluator forplusthree. A function initial has no MachineJSON form:initialnames the first child. A built machine exports no rootcontext, and typed states have nometa. - Normalization (what a JSON round trip changes;
plusthree-json/tests/export.rschecks every loadable fixture and trace machine against it): one-element lists are written without the array; defaults are dropped (reenter: false,typeatomic or compound,history: "shallow", a stateidor invokeidequal to the default); named actions and guards declared in the machine are inlined and their maps dropped, as loading does; custom actions keep onlytypeandparams;@xstate.stateInids get their#;timeoutvalues become milliseconds;delayskeeps only literal delays anafterkey names, in milliseconds;routeis expanded into the root'son["xstate.route"](D14 keeps both kinds there, so the meaning is the same);onkeys may move (a state's ownxstate.done.stateentry comes last) whilestatesandafterkeep document order; and what loading ignores is dropped:description,schemas,key,@exprLang, theactorsmap, stateinput, andcontext,versionandinternalEventsbelow the root. Definitions with@expr/@codedo not load, so they have no export.
- What a handle stands for. For a JSON machine, the lowering's descriptors: the JSON exported is the JSON loaded, normalized as below. For a built machine, each
- Persistence: v6's persisted snapshot format (
persistedSnapshot.schema.json), throughSnapshotFormatand the kernel'sSnapshotParts/Snapshot::from_parts, which checks that the parts form a reachable state.configis written as a StateValue, history as{id}arrays, timers withscheduledAt, children recursively through theChildCodechook. Restoring checks the machineidandversion. Typed machines go through serde when their context, events, output and errors areSerialize + DeserializeOwned.- D19: the kernel keeps only each timer's delay, so persisting asks the host for each timer's deadline on its clock and writes
scheduledAt= deadline − delay. Restoring takesnowon the same clock and returns each timer's remaining delay (scheduledAt + delay − now, at least 0) for the host to schedule. A timer withoutscheduledAt(v6 under a simulated clock) restarts its full delay, as in v6. For an actor system the clock is the system'snow. - Systems.
System::persistpersists the root actor: each actor persists itself (Logic::persist; a machine through itsBridge), and a machine's children are embedded by address through theChildCodec(SystemChildrenfor JSON machines):address,src,registryKey,syncSnapshotand the child's own persisted snapshot, orremote: true(with v6'sincarnationtoken) for a child that lives with another runtime.syncSnapshotis written for invoked children, and for spawned ones only when true: v6 omits it when the spawn did not set it, and the kernel does not keep the difference between unset andfalse.System::restore_fromtakes a tree of restored actors built from the same JSON: machines keep their state and timers (D19, in system time), async and callback logic start over with the input their snapshot records (NOTES #15), and remote children become stand-ins whose events go to the host (Notice::Remote). Delayed sends persist as@xstate.sendTotimers targeting"self", a child id or{"type":"parent"}; a send to a registry key is persisted as the child registered under it, and any other target is not addressable from the snapshot, as in v6. Restoring folds child ids shaped like generated ones (prefix:n) intonextActorIds, as v6 does. Actor references in a JSON context ({"@actor": address}) are data and round-trip as written.
- D19: the kernel keeps only each timer's delay, so persisting asks the host for each timer's deadline on its clock and writes
8. Actors and system #
M4 scope: children that are machines (invoke and spawn, with onDone, onError, onSnapshot and invoke timeout); async children (a Future producing output or an error); callback children; a registryKey registry and send_to by address; dead letters for missing targets.
Pure reducer: plusthree-system ports v6's experimental systemTransition / advanceSystemTime. A SystemSnapshot { now, actors, registry, messages, timers, counters } is a deterministic reducer over the whole tree of actors. It is the substrate for tests, replay and persistence.
Live runtime: plusthree-runtime provides a mailbox per actor, runs the effects after each macrostep, sends one snapshot notification per macrostep, and plugs in a clock (tokio, std, embassy, simulated).
Inspection in the Stately Inspector: plusthree-inspect (std) turns the system's Inspection notices into the messages of @statelyai/sdk's inspection protocol 2, the protocol of Stately's current, v6-aware inspector (sky.stately.ai/inspect). It is a local relay: a WebSocket server the hosted viewer connects to, so it needs no TLS, account or cloud relay. @xstate.actor becomes actorRegistered (address as sessionId, the machine's MachineJSON wrapped as @statelyai.inspection.machine, profile xstate-v6-alpha); @xstate.transition becomes actorEvent plus actorSnapshot with the transitions named by MachineDef::id_of, and actorStopped once the status is final. A host that steps machines itself, with no system, registers each with Inspector::actor and reports every macrostep to the returned ActorHandle, which is also an Observer: stepped through step_with/fire_with it records the transitions taken and the actions (built-in effects by the action types a system reports, the machine's own as effect), so the existing hook supplies them and plain step pays nothing. The Report trait's step/fire, on a handle or an Option of one, do both in one call. What could leak is opt-in: the viewer gets event names, snapshots with only the context fields marked #[context(show)] (Context::show_fields, §5.1) and unnamed effects unless the host names effects by variant (name_effects, which takes the machine so T::Effect: VariantName is checked at compile time) or supplies JSON per call (step_showing) or per actor (show_context, show_effects, stored type-erased so the handle stays untyped; the handle records its machine's effect type at registration and show_effects panics on a closure for another type instead of showing every effect as effect). Inspector::group registers an actor without a machine (no logicType, snapshot {status: active}, which the viewer shows as a running actor; without a snapshot it shows "Awaiting snapshot") to parent machines with no common root. Actors nest by session id (parent/child, made unique when taken), and a handle's registration number keeps a dropped handle from stopping an actor registered again under its id. Registering an id again under the same parent replaces that actor, reusing its session id, only once it has stopped: replacing a running actor would silently cut its live handle off, and a host that registers machines before it knows their parent, such as several sessions at the top level, would lose all but the last. ActorHandle::move_to re-parents an actor in place: it keeps its session id and re-sends actorRegistered with replaces: true and the new parentSessionId, then its last actorSnapshot (the viewer rebuilds a re-registered actor from its snapshot alone, losing the last event and actions), which the hosted viewer's reducer takes as the same actor under a new parent (its tree is built from parentSessionId, so order does not matter); late viewers get the new parent in system.init. A new session id with the old one stopped would leave a stopped copy in the viewer, which has no message to remove an actor. The legacy @statelyai/inspect package speaks XState v5's @xstate.event/@xstate.snapshot, drops v6's @xstate.transition, and its viewer draws diagrams only for signed-in users, so it is not targeted.
Children of different types. T::Children is a user-declared #[derive(Children)] enum of the actor kinds a machine can spawn. machine! can generate it. The derive also generates output and error enums, so onDone handlers receive the child's typed output rather than a dyn Any.
9. Conformance and testing #
- Differential tests against XState (primary oracle). A Node harness runs XState beta.3 on MachineJSON plus a JS registry that mirrors the Rust one. It records traces: for each event, the StateValue, context, effect list, and microsteps (from
@xstate.transitioninspection). Rust replays the traces throughfrom_jsonand requires an exact match, except for steps covered by a deviation (§2). Recorded traces are committed as fixtures, so CI does not need Node. - Random differential fuzzing. A generator builds random charts (depth up to 5, parallel regions, shallow and deep history,
always,after, transitions between regions,reenter, final states inside parallel states) and random event and time sequences. Both engines run the same input and any divergence is minimized. This targets domain narrowing, conflict resolution, history-target domains, and done events across parallel states. - Ported v6 semantic tests:
microstep.v6,parallelConformance,history,transient,after,final,order,deterministic, plus theinterpreterLawsreference model as a proptest, hand-translated into Rust tests against the typed API. - Persistence and inspection conformance: golden files from
persistenceConformance.v6,serialization.conformance.v6,inspection.conformance.v6. - Allow-list. Each entry needs a deviation ID from
DEVIATIONS.md(ormsgfor error wording) and names, as masks, what the deviation changes in its steps: a field path, an array whose order differs, or the extra items one side has, matched by a pattern (plusthree_conformance::Mask). Everything else in those steps is compared. An entry whose step matches without its masks, or that has a mask the step does not need, fails CI. Every deviation also has a Rust test asserting the correct behaviour.
XState v6 is still in beta. Re-pinning means regenerating traces, reviewing the diff, and updating the allow-list.
10. Performance #
The budgets are the measured numbers after the hot-path work (commit 3a745c0), and they are a floor that must not regress. Instruction counts are the primary metric because they do not depend on the host; nanoseconds are scaled to the original baseline host through the xstate-statemachine-rs engine measured in the same run. crates/plusthree-bench/BASELINES.md has the method, every library's numbers and the caveats.
| Scenario | Budget (instr/event) | plusthree (scaled ns) | xstate-statemachine-rs engine | XState v6 transition() |
|---|---|---|---|---|
| Flat toggle (S1) | 628 | 33 ns | 785 instr, 41.7 ns | 2.3 µs |
| Guard + context patch (S2) | 796 | 49 ns | 1,028 instr, 60.1 ns | 5.2 µs |
| 3-level nested, cross-tree (S3) | 628 | 38 ns | 867 instr, 49.8 ns | 9.9 µs |
| 2 parallel regions (S4) | 1,137 | 55 ns | 3,498 instr, 203 ns | 11.1 µs |
after timer fire, incl. schedule/cancel effects (S7) |
1,626 | 102 ns | 1,460 instr, 94.7 ns | 37 µs |
| Build a 50-state machine from JSON (S5) | 3.34 M per build | 291 µs | 128 µs | 354 µs |
| Allocations per steady-state event | 0 | 0 | 0 | — |
- A counting-allocator test enforces 0 allocations per steady-state event for S1–S4 and S7, and for S7 run through
host::Driven(s7_plusthree_drivenin the instruction counts, about 2,020 instr/event: the S7 fire plus netting its timer effects and the host's callbacks). just bench-instrruns the gungraun instruction counts and fails on a regression above 5% against the saved baseline. Run it before pushing changes to the kernel hot path or the IR.- The criterion suite also runs equivalent statig and smlang machines. Compiled dispatch costs them about 5 instructions per event, which is the floor for what codegen could reach.
- The original targets (S1 ≤ 15 ns, S2 ≤ 25 ns, S3 ≤ 40 ns, S4 ≤ 60 ns, S7 ≤ 80 ns, S5 ≤ 50 µs) were set before any measurement. S3 and S4 met them. The rest would need per-machine specialization (S1, S2, S7) or a single-pass JSON loader (S5); both are deferred below.
After 0.1 (deferred, only on a real bottleneck):
- Codegen: an opt-in
machine!backend that generates per-machine dispatch. It is a second execution path, so it ships only with an equivalence test that runs generated code against the interpreter on random machines and the conformance corpus where expressible. The interpreter stays the reference. - Single-pass JSON loader: MachineJSON values straight to the IR builder, interned names, JSON paths built only on error. Loading happens once per machine, so this waits until a user loads machines on a hot path.
- Const-generic inline
StateSet: rejected for now as too invasive while several crates changed at once; revisit if profiles point at set operations again.
11. SCXML: not planned #
Decided after 0.1.1: plusthree is complete as an XState v6 port, and an SCXML profile is not planned. XState departs from SCXML on purpose (re-entry by default, prefix event matching, partial transitions on error, inline scripts, narrow invoke), and plusthree follows XState. If SCXML documents ever need to run, the profile would differ from v6 in the places below, without forking the kernel.
The kernel would branch on Semantics in four places: the domain (v6 narrowing vs SCXML LCCA with internal/external transitions); the default for reenter; event matching (exact plus specificity-ranked wildcards vs SCXML token prefixes in document order); errors (abort and replay vs error.execution on the internal queue, aborting only the current block). Delayed events on the external queue, invoke finalize and autoforward come with the profile.
12. Milestones #
- M0, IR: workspace,
plusthree-irbuilder, validation, flattening, desugaring, interning;StateSet; property tests for flattening invariants. - M1, Kernel: atomic, compound, parallel, final, choice; object and function transitions; entry/exit; patches; raise;
always; done.state; history; selection and conflicts;can; StateValue; Observer hook. Differential harness up and running. - M2, Time and errors: logical timers (
after,timeout, delayed raise, cancel), the error model with journal rollback,max_microsteps, benchmarks plus the allocation gate. - M3, Surfaces:
#[derive(Context, Event, Children)],machine!, MachineJSON import/export, persisted snapshots. - M4, Actors: children, the system reducer, the tokio runtime, inspection, public
microsteps()/next_transitions(). - M5: embassy adapter. (An SCXML profile was dropped; see §11.)
- After 0.1: codegen and the single-pass JSON loader, only on a real bottleneck (§10).
13. Decisions #
- Event names. By default the name is the variant name verbatim (
Inc→"Inc"). Serde-style#[event(rename = "user.login")]and#[event(rename_all = "SCREAMING_SNAKE_CASE")]override it. A later#[event(flatten)]on a variant wrapping a nested enum may build dotted names:User(UserEv::Login)→"user.login". - Context updates. Patches only in v1, with generated setters:
.patch(|p| p.count(n)). Revisit anupdate(|ctx| …)form, backed by a per-macrostep arena, after writing real examples in M3. - Child typing. Users declare an explicit
#[derive(Children)]enum, which generates output and error enums.machine!can generate it frominvoke/spawndeclarations. - State ids.
StateId(u32). - License. MIT.
- Microstep-level API. M1 adds the compile-away
Observerhook; publicmicrosteps(),next_transitions()and inspection APIs come in M4.