Machine runtime and service lifecycle
The machine runtime turns a declarative machine definition into a live service. It owns state, context, event handling, effects, and change notifications so that framework adapters can expose the same machine behavior to UI consumers. It is the runtime layer beneath the state machine platform and works with the definitions described in machine authoring.
Runtime model
The runtime combines a machine definition with user props and a framework-managed reactive store. The machine describes the allowed states and behavior. The adapter creates a service that runs that behavior in the host framework.
The definition can provide these core inputs:
- An initial state chosen from the current props.
- States with transitions, tags, entry actions, exit actions, and active effects.
- Shared context for reactive values.
- Guards that decide which transition can run.
- Actions that change context or notify external code.
- Computed values derived from the current service data.
- Watches that react to tracked prop or context changes.
The core package validates and indexes the state tree when createMachine is called. This gives the runtime one model for nested states, state IDs, target paths, inherited transitions, and state tags across all adapters.
References: packages/…/create-machine.ts• L24-41 packages/…/state.ts• L33-80 packages/…/types.ts• L196-242
Service lifecycle
The service has three lifecycle statuses: not started, started, and stopped. Starting resolves the initial state and invokes it as an entry into the machine. Stopping releases active effects, runs the machine exit actions, and prevents later events from changing the service.
The lifecycle follows this sequence:
- The adapter creates props, scope, context, refs, computed access, and the initial state.
- The adapter marks the service as started.
- The runtime enters the initial state and runs root and state entry behavior.
- The service accepts events and publishes state or context changes to consumers.
- The adapter stops the service when its host component or owner is released.
The vanilla adapter exposes this lifecycle through explicit start and stop calls. UI adapters connect the same lifecycle to their host framework mount and unmount hooks. Their returned service shape stays consistent even though the scheduling and cleanup hooks belong to each framework.
flowchart TD
A[Machine definition and props] --> B[Create service resources]
B --> C[Start or mount]
C --> D[Enter initial state]
D --> E[Process events and changes]
E --> F[Publish service snapshot]
F --> E
E --> G[Stop or unmount]
G --> H[Clean up effects]
H --> I[Run machine exit actions]
I --> J[Reject later events]
References: packages/…/machine.ts• L87-123 packages/…/machine.ts• L310-331 packages/…/machine.ts• L290-317 packages/…/types.ts• L269-290
State interpretation
The runtime treats the current state as a path in a state tree. A path can include parent and child states. Entering or leaving a path also enters or leaves the relevant parent states, so parent behavior can cover a group of child states.
Transition lookup starts at the deepest active state. If that state has no matching event, the runtime checks its parents and then the machine-level event map. A target resolves to a sibling by default, to a child when it starts with ., or to a state ID when it starts with #. Compound states resolve their configured initial child.
State consumers can use either the full state path or a broader match. Tags provide a separate way to ask whether any active state in the path has a named capability.
References: packages/…/state.ts• L94-185 packages/…/state.ts• L192-248 packages/…/types.ts• L177-194
Event processing
send accepts an event object and routes it through the active state hierarchy. Events sent before a service is started or after it is stopped do not produce normal transitions. An event with no matching transition is a no-op.
For a matching event, the runtime selects the first transition whose guard passes. It then resolves the target and applies one of three behaviors:
- A new target changes state and runs exit, transition, effect, and entry behavior.
- A transition without a target runs its actions while keeping the current state.
- A
reentertransition leaves and enters the same state again. This restarts its entry actions and active effects.
The runtime records the current and previous events in the service snapshot. Actions, guards, effects, computed values, and watches receive a shared parameter set that can read props, context, refs, state, scope, and event data.
Most adapters defer event work to a microtask. This preserves ordered processing for several sends in one turn. Public setters can mark events with replaces so that a newer queued event for the same declarative value supersedes an older one. Internal events should not use that marker because they represent distinct system signals.
sequenceDiagram
participant Consumer
participant Service
participant Machine
participant Effects
Consumer->>Service: send(event)
Service->>Machine: find transition for active state
Machine-->>Service: guarded transition or no match
alt state target changes
Service->>Effects: clean up exiting states
Service->>Machine: run exit and transition actions
Service->>Effects: start entering state effects
Service->>Machine: run entry actions
else internal transition
Service->>Machine: run transition actions
else reenter
Service->>Effects: clean up current state effects
Service->>Machine: run exit, transition, and entry behavior
end
Service-->>Consumer: publish updated snapshot
References: packages/…/machine.ts• L223-263 packages/…/machine.ts• L118-157 packages/…/machine.ts• L301-307 packages/…/replace-tracker.ts• L6-18
Action and guard behavior
Actions and guards are named behavior selected by the machine definition. The runtime resolves each name against the machine implementations and calls it with the current service parameters. A missing implementation does not create a transition or action; the runtime warns about the missing name.
Guards control transition choice. When several guarded transitions exist for one event, the runtime checks them in order and uses the first passing choice. If no guard passes, the event has no effect. Actions run in the order declared by the machine.
During a state change, the action order is stable:
- Actions for states that exit.
- Actions on the selected transition.
- Entry actions for states that enter.
Root entry and root effects run on the initial entry. Root exit actions run when the service stops.
References: packages/…/machine.ts• L265-307 packages/…/machine.ts• L168-205 packages/…/types.ts• L173-175 packages/…/machine.test.ts• L178-215
Effect management
Effects represent work that remains active while the machine or a state is active. An effect may return a cleanup function. The runtime stores cleanup by state path so it can stop the work when that path exits.
State effects start before the new state's entry actions. The runtime cleans up effects before exit actions when leaving a state. Reentering a state performs the same cleanup and setup cycle. Stopping the service cleans up all state and root effects, including effects that were started during initial entry.
Effects can send events back to the service. This lets timers, DOM listeners, observers, and other outside work drive the same transition path as consumer input. The cleanup contract is therefore important: an effect that does not release its outside work can send events after its state is no longer active.
References: packages/…/machine.ts• L168-205 packages/…/machine.ts• L285-299 packages/…/machine.ts• L317-330 packages/…/machine.test.ts• L518-595
Reactive context and derived data
Context is the machine's reactive data layer. A bindable context value can use a default value for uncontrolled use or a prop-backed value for controlled use. Actions update context through the service, while consumers read it through the service snapshot.
Computed values are read-only derivations over props, context, refs, scope, and events. Watches connect selected changes to actions. The runtime tracks the dependencies supplied by a watch and calls its action only when the dependency values change.
Context and state changes publish a fresh service view to subscribers. Framework adapters use that signal to update their consumers while keeping the machine definition framework independent.
References: packages/…/types.ts• L34-65 packages/…/machine.ts• L125-162 packages/…/machine.ts• L357-396 packages/…/machine.ts• L160-188
Consumer snapshot
The service is the runtime's consumer-facing snapshot. It exposes the current state and helpers together with the data and capabilities needed by component code.
| Snapshot area | Consumer purpose |
|---|---|
state | Read the current path, test matches, and check tags. |
context | Read or update machine-owned reactive values. |
send | Deliver an event to the machine. |
event | Read the current and previous event. |
prop | Read normalized machine props. |
computed | Read derived machine values. |
refs | Access non-reactive machine references. |
scope | Resolve the machine's DOM and identity scope. |
getStatus | Check whether the service is started or stopped. |
The vanilla service can notify direct subscribers after state or context changes. UI adapters return the same service contract through their framework hooks, so component connectors can consume machine behavior without knowing which runtime adapter is active.
References: packages/…/types.ts• L269-285 packages/…/machine.ts• L333-360 packages/…/machine.ts• L326-336
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the
Servicecontract aligned with each framework adapter so state, event, context, and status have the same meaning. - Keep state target resolution and transition lookup changes aligned with nested state types and state-index validation.
- Preserve effect cleanup ownership by state path when changing entry, exit, reenter, or stop behavior.
- Preserve queued-event ordering and
replacessemantics when changing any adapter'ssendpath. - Keep controlled context behavior aligned with bindable values so a local write does not appear as a committed change when props own the value.
- Keep subscriber publication aligned with both state changes and context changes so consumers do not receive stale snapshots.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A compound state has no valid initial child | The machine cannot resolve a complete active state path. | Validate the state tree during createMachine. |
Several queued public setter events use the same value slot without replaces | An older event can apply after a newer intent. | Mark only declarative public setter events with the shared replacement key. |
| An effect does not return or run its cleanup | Outside listeners or timers can remain active after state exit. | Store cleanup by state path and run it on exit, reenter, and stop. |
| A transition list has no passing guard | The event leaves state and context unchanged. | Add an unguarded fallback when the event must always have a valid path. |
| An event is sent after service stop | The event is ignored and no consumer update occurs. | Check service status before relying on a send. |
| A named action, guard, or effect has no implementation | The named behavior does not run and the runtime warns. | Keep definition names and implementation maps synchronized. |
Key files
| File | Why to read it |
|---|---|
| packages/…/types.ts | Defines the machine schema, transition model, service snapshot, and lifecycle statuses. |
| packages/…/state.ts | Explains state-tree indexing, target resolution, transition lookup, and exit/entry calculation. |
| packages/…/create-machine.ts | Shows how machine definitions are created and validated before runtime use. |
| packages/…/machine.ts | Shows the clearest explicit service lifecycle and event processing flow. |
| packages/…/machine.ts | Shows how the shared runtime model connects to a component lifecycle and reactive rendering. |
| packages/…/machine.ts | Shows pre-mount event buffering and replay for a framework with parent-child mount order concerns. |
| packages/…/replace-tracker.ts | Defines last-event-wins behavior for replaceable queued events. |
| packages/…/machine.test.ts | Summarizes the runtime guarantees for lifecycle, action order, guards, effects, snapshots, and queued events. |