1. Getting Started

A state chart is defined as a (nested) map. Some of this content’s behavior is configurable. The simplest setup is to use Clojure for the executable code and a simple flat data model that scopes all state charts to the session (running instance of state chart).

Note
The SCXML standard is used for the semantics and processing, and MUCH of the overall structure. We keep the idea that each node in the chart has a unique ID, but take some license with executable content. Most of the "executable content" elements described in the SCXML standard have differences since we are not using XML. Sometimes we assume you can get by with an expression on the parent element, or just a single child script node.

To make it easier to write the maps there are functions for each element type in the com.fulcrologic.statecharts.elements namespace, and it is recommended that you use these because some of them validate their parameters and children.

Once you have a state chart definition you need to create a session, which is just a running instance of the chart.

Once you have a session, you can send events to it, and look at the content of the session (or store it, etc).

Here’s a traffic light example from the src/examples directory in this repository that leverages parallel and compound states to simulate traffic lights with pedestrian signals:

(ns traffic-light
  (:require
    [com.fulcrologic.statecharts :as sc]
    [com.fulcrologic.statecharts.chart :refer [statechart]]
    [com.fulcrologic.statecharts.elements :refer [parallel state transition]]
    [com.fulcrologic.statecharts.events :refer [new-event]]
    [com.fulcrologic.statecharts.protocols :as sp]
    [com.fulcrologic.statecharts.simple :as simple]
    [com.fulcrologic.statecharts.util :refer [extend-key]]))

(def nk
  "(nk :a \"b\") => :a/b
   (nk :a/b \"c\") => :a.b/c"
  extend-key)

(defn traffic-signal [id initial]
  (let [red     (nk id "red")
        yellow  (nk id "yellow")
        green   (nk id "green")
        initial (nk id (name initial))]
    (state {:id      id
            :initial initial}
      (state {:id red}
        (transition {:event :swap-flow :target green}))
      (state {:id yellow}
        (transition {:event :swap-flow :target red}))
      (state {:id green}
        (transition {:event  :warn-traffic
                     :target yellow})))))

(defn ped-signal [id initial]
  (let [red            (nk id "red")
        flashing-white (nk id "flashing-white")
        white          (nk id "white")
        initial        (nk id (name initial))]
    (state {:id      id
            :initial initial}
      (state {:id red}
        (transition {:event :swap-flow :target white}))
      (state {:id flashing-white}
        (transition {:event :swap-flow :target red}))
      (state {:id white}
        (transition {:event :warn-pedestrians :target flashing-white})))))

(def traffic-lights
  (statechart {}
    (parallel {}
      (traffic-signal :east-west :green)
      (traffic-signal :north-south :red)

      (ped-signal :cross-ew :red)
      (ped-signal :cross-ns :white))))

(defn show-states [wmem]
  (println
    (sort
      (filter #{:north-south/red
                :north-south/yellow
                :north-south/green
                :east-west/red
                :east-west/yellow
                :east-west/green
                :cross-ns/red
                :cross-ns/white
                :cross-ns/flashing-white
                :cross-ew/red
                :cross-ew/white
                :cross-ew/flashing-white}
        (::sc/configuration wmem)))))

(def env (simple/simple-env))
(simple/register! env ::lights traffic-lights)
(def processor (::sc/processor env))
(def s0 (sp/start! processor env ::lights {::sc/session-id 1}))
(show-states s0)
(def s1 (sp/process-event! processor env s0 (new-event :warn-pedestrians)))
(show-states s1)
(def s2 (sp/process-event! processor env s1 (new-event :warn-traffic)))
(show-states s2)
(def s3 (sp/process-event! processor env s2 (new-event :swap-flow)))
(show-states s3)
(def s4 (sp/process-event! processor env s3 (new-event :warn-pedestrians)))
(show-states s4)
(def s5 (sp/process-event! processor env s4 (new-event :warn-traffic)))
(show-states s5)
(def s6 (sp/process-event! processor env s5 (new-event :swap-flow)))
(show-states s6)

If you run the items in the comment block, you’ll see:

(:cross-ew/red :cross-ns/white :east-west/green :north-south/red)
(:cross-ew/red :cross-ns/flashing-white :east-west/green :north-south/red)
(:cross-ew/red :cross-ns/flashing-white :east-west/yellow :north-south/red)
(:cross-ew/white :cross-ns/red :east-west/red :north-south/green)
(:cross-ew/flashing-white :cross-ns/red :east-west/red :north-south/green)
(:cross-ew/flashing-white :cross-ns/red :east-west/red :north-south/yellow)
(:cross-ew/red :cross-ns/white :east-west/green :north-south/red)

History support includes both shallow and deep. Here’s a shallow example:

(ns history-sample
  (:require
    [com.fulcrologic.statecharts :as sc]
    [com.fulcrologic.statecharts.chart :refer [statechart]]
    [com.fulcrologic.statecharts.elements :refer [history state transition]]
    [com.fulcrologic.statecharts.events :refer [new-event]]
    [com.fulcrologic.statecharts.protocols :as sp]
    [com.fulcrologic.statecharts.simple :as simple]))

(def sample
  (statechart {}
    (state {:id :TOP}
      (state {:id :A}
        (transition {:event :top :target :B}))
      (state {:id :B}
        ;; Could transition to :C, but that won't restore history.
        ;; Transitioning to (one of) the history nodes in C
        ;; directly restores history (you can have more than
        ;; one because you might want different "default" targets
        ;; for when there is no history).
        (transition {:event :top :target :Ch}))
      (state {:id :C}
        (transition {:event :top :target :A})
        (history {:id :Ch}
          (transition {:target :C1}))
        (state {:id :C1}
          (transition {:event :sub :target :C2}))
        (state {:id :C2}
          (transition {:event :sub :target :C1}))))))

(defn show-states [wmem] (println (sort (::sc/configuration wmem))))
(def env (simple/simple-env))
(simple/register! env `sample sample)
(def processor (::sc/processor env))

(def s0 (sp/start! processor env `sample {::sc/session-id 1}))
(show-states s0)
;; :TOP :A

(def s1 (sp/process-event! processor env s0 (new-event :top)))
(show-states s1)
;; :TOP :B

(def s2 (sp/process-event! processor env s1 (new-event :top)))
(show-states s2)
;; :TOP :C :C1

(def s3 (sp/process-event! processor env s2 (new-event :sub)))
(show-states s3)
;; :TOP :C :C2

(def s4 (sp/process-event! processor env s3 (new-event :top)))
(show-states s4)
;; :TOP :A

(def s5 (sp/process-event! processor env s4 (new-event :top)))
(show-states s5)
;; :TOP :B

(def s6 (sp/process-event! processor env s5 (new-event :top)))
(show-states s6)
;; :TOP :C :C2 (history remembered)

See the SCXML spec for how to structure elements. The structure and naming are kept close to that spec for easy cross-referencing with its documentation.

2. Autonomous State Charts

The pure functional form for the charts is interesting and useful as a building-block, but if you want a fully-function SCXML-compatible system, you needs something that can run, deliver delayed events, send events from one state chart session to another, start/stop nested state charts, etc.

In order for this to work you must have a number of things: an event queue, invocation processor(s), a data/execution model, a working memory storage facility, a state chart registry, and an event loop.

That’s a lot of different things to set up!

The com.fulcrologic.statecharts.simple namespace can set up all of these things for you, as long as you simply want to run state charts all in the same JVM in RAM. That namespace also includes helper functions for starting a new session on a chart, and sending events to arbitrary sessions.

Note
The design of this library is meant to accomplish much more complex distributed and long-lived systems, but you have to implement the various protocols for each of the above elements to build such a thing.

The basic steps for using simple are:

  1. Create a (simple/simple-env)

  2. Register your charts with the state chart registry in that env with (simple/register! env k chart)

  3. Run an event loop. The com.fulcrologic.statecharts.event-queue.core-async-event-loop/run-event-loop! uses core.async to run such a loop for you.

  4. Start one or more state charts, via the k you registered them under.

  5. (optionally) Send events (simple/send! env {:event :evt :target sessionid})

Below is an example that uses these steps, but also overrides one of the components in the env (the working memory store) so it can output messages as the state chart changes state:

(ns traffic-light-async
  "A demo that uses the core.async queue to demonstrate a running machine that can just be
   sent events and mutates in place (and handles timers in CLJC) via core.async."
  (:require
    [com.fulcrologic.statecharts :as sc]
    [com.fulcrologic.statecharts.chart :refer [statechart]]
    [com.fulcrologic.statecharts.elements :refer [Send on-entry parallel state transition]]
    [com.fulcrologic.statecharts.event-queue.core-async-event-loop :as loop]
    [com.fulcrologic.statecharts.events :as evts]
    [com.fulcrologic.statecharts.protocols :as sp]
    [com.fulcrologic.statecharts.simple :as simple]
    [com.fulcrologic.statecharts.util :refer [extend-key]]))

(def nk
  "(nk :a \"b\") => :a/b
   (nk :a/b \"c\") => :a.b/c"
  extend-key)

(def flow-time "How long to wait before flashing ped warning" 2000)
(def flashing-white-time "How long do we warn peds?" 500)
(def yellow-time "How long do we warn cars" 200)

(defn timer []
  (state {:id :timer-control}
    (state {:id :timing-flow}
      (transition {:event  :warn-pedestrians
                   :target :timing-ped-warning})
      (on-entry {}
        (Send {:event :warn-pedestrians
               :delay flow-time})))
    (state {:id :timing-ped-warning}
      (transition {:event  :warn-traffic
                   :target :timing-yellow})
      (on-entry {}
        (Send {:event :warn-traffic
               :delay flashing-white-time})))
    (state {:id :timing-yellow}
      (transition {:event  :swap-flow
                   :target :timing-flow})
      (on-entry {}
        (Send {:event :swap-flow
               :delay yellow-time})))))

(defn traffic-signal [id initial]
  (let [red     (nk id "red")
        yellow  (nk id "yellow")
        green   (nk id "green")
        initial (nk id (name initial))]
    (state {:id      id
            :initial initial}
      (state {:id red}
        (transition {:event :swap-flow :target green}))
      (state {:id yellow}
        (transition {:event :swap-flow :target red}))
      (state {:id green}
        (transition {:event  :warn-traffic
                     :target yellow})))))

(defn ped-signal [id initial]
  (let [red            (nk id "red")
        flashing-white (nk id "flashing-white")
        white          (nk id "white")
        initial        (nk id (name initial))]
    (state {:id      id
            :initial initial}
      (state {:id red}
        (transition {:event :swap-flow :target white}))
      (state {:id flashing-white}
        (transition {:event :swap-flow :target red}))
      (state {:id white}
        (transition {:event :warn-pedestrians :target flashing-white})))))

(def traffic-lights
  (statechart {}
    (parallel {}
      (timer)

      (traffic-signal :east-west :green)
      (traffic-signal :north-south :red)

      (ped-signal :cross-ew :red)
      (ped-signal :cross-ns :white))))

(defn show-states [wmem]
  (println (sort (filter #{:north-south/red
                           :north-south/yellow
                           :north-south/green
                           :east-west/red
                           :east-west/yellow
                           :east-west/green
                           :cross-ns/red
                           :cross-ns/white
                           :cross-ns/flashing-white
                           :cross-ew/red
                           :cross-ew/white
                           :cross-ew/flashing-white} (::sc/configuration wmem)))))


(comment
  ;; Setup steps
  (do
    (def session-id 1)
    ;; Override the working memory store so we can watch our working memory change
    (def wmem (let [a (atom {})] (add-watch a :printer (fn [_ _ _ n] (show-states n))) a))
    ;; Create an env that has all the components needed, but override the working memory store
    (def env (simple/simple-env
               {::sc/working-memory-store
                (reify sp/WorkingMemoryStore
                  (get-working-memory [_ _ _] @wmem)
                  (save-working-memory! [_ _ _ m] (reset! wmem m)))}))

    ;; Register the chart under a well-known name
    (simple/register! env ::lights traffic-lights)

    ;; Run an event loop that polls the queue every 100ms
    (def running? (loop/run-event-loop! env 100)))

  ;; Start takes the well-known ID of a chart that should be started. The working memory is tracked internally.
  ;; You should see the tracking installed above emit the traffic signal pattern
  (simple/start! env ::lights session-id)

  ;; Tell the state machine to exit abruptly
  (simple/send! env {:target session-id
                     :event  evts/cancel-event})

  ;; Stop event loop
  (reset! running? false))
Note
The send element has a Send (capital S) alias so you can avoid shadowing the predefined Clojure function.

3. Async Execution Engine

The library includes an async-capable execution engine built on promesa that allows expressions to return promises the algorithm awaits. When all expressions are synchronous, the overhead is minimal. When an expression returns a promise, the algorithm parks until it resolves before continuing.

Both start! and process-event! may return promises instead of plain values. Callers must handle both cases. The easiest approach is to use promesa.core/let or promesa.core/then which handle both synchronous values and promises transparently.

The motivation for this features is CLJS statecharts, because the js ecosystem has a ton of promise-based asynchrony. In CLJ, you can write script tags that block:

(state {:id :state/foo}
  (on-entry {}
    (script-fn [env data] (db/run-query! "A")) ; blocks
    (script-fn [env data]  ; runs AFTER the first script
      (if (condition-needing-loaded-data-from-a)
        (db/run-query! "B"))))
  (state {:id :nested-state} ; IS NOT entered until all scripts finish
    ...)

but in JS-land, I/O is async, meaning you end up writing a bunch of states to "track progress". IF you use the async engine, then returning a promise from a script will cause the statechart to PARK until the promise completes, allowing you to write much simpler charts.

Note
This is an opt-in feature. The Fulcro integration can use it simply by passing a single parameter when you install the statecharts support.

3.1. Setting Up the Async Engine

Use the com.fulcrologic.statecharts.simple-async namespace for automatic configuration:

(require '[com.fulcrologic.statecharts.simple-async :as simple-async])

(let [env (simple-async/simple-env)]
  (simple-async/register! env :my-chart my-chart)
  (simple-async/start! env :my-chart session-id))

Or compose manually:

(require '[com.fulcrologic.statecharts.algorithms.v20150901-async :as alg]
         '[com.fulcrologic.statecharts.execution-model.lambda-async :as lambda-async])

{::sc/processor (alg/new-processor)
 ::sc/execution-model (lambda-async/new-execution-model dm event-queue)}

The async engine requires promesa on the classpath. Add it to your deps.edn:

{:deps {funcool/promesa {:mvn/version "11.0.678"}}}

Or use the :async alias if available in the project.

3.2. Using Async Expressions

Any expression (predicates, script nodes, etc.) can return a promise:

(state {:id :loading}
  (on-entry {}
    (script {:expr (fn [env data]
                     (p/let [result (http/get "/api/data")]
                       [(ops/assign :result result)]))})))

The algorithm will automatically detect promises and await them. Synchronous expressions continue to work without change.

4. Going Deeper

You can use the SCXML guide which has examples as a pretty good reference for documentation. The document structure in XML is nearly identical to the data structure of this library:

<scxml>
  <state id="A"/>
  ...
  </scxml>
(statechart {}
  (state {:id :A})
  ...)

See the docstrings on the statechart and various elements for details of differences.

4.1. Terminology

Atomic State

A state that does not have child states.

Compound State

A state that has child states, where at most one child is active at any given time.

Parallel State

A state that has more than one compound child state, all of which are active at the same time, and thus have a child state that is active.

Configuration

When used in the context of a state chart, the configuration is the list of all active states. A state is active if it or ANY of its children are active. Thus, a parallel state chart with hierarchical states may have a rather large set of IDs in its current configuration.

Working Memory

A map of data that contains the current configuration of the state chart, and other information necessary to know its current full state (which states have had their data model initialized, possible data model tracking, etc.).

DataModel

An implementation of the data model protocol defines how the data model of your chart works. The simple implementation places the data in Working Memory, and treats lookups as paths into a single top-level map scoped to the session (running chart instance).

ExecutionModel

An implementation of this protocol is handed the expressions that are included on the state chart, and chooses how to run them. A default implementation requires that they be Clojure (fn [env data]), and simply calls them with the contextual data for their location.

External Event

An event that came from the external API, either by you calling process-event or some other actor code doing so (invocations, sends from external charts, etc.)

Internal Event

An event that came from the session that will process it. These come from the chart implementation itself (e.g. done evens) and from you using the raise element in an executable content position.

EventQueue

A FIFO queue for external event delivery. The event queue is responsible for holding onto pending External Events to "self", possibly other state chart sessions (instances of other charts), remote services (e.g. send an email), and for delayed delivery. The default implementation is a "manually polled" queue that does not support most of these features, and the delayed event delivery is manual (e.g. you have to poll it, or ask it when the next one should happen and start a timer/thread). Creating a system that runs the loop and does the timed delivery is typically how you would use these in a more serious/production environment.

Processor

An implementation of the state chart algorithm. This library comes with an implementation that follows (as closely as possible) the SCXML recommended standard from 2015. You may provide your own.

InvocationProcessor

A protocol representing things that can be invoked while in a state. Implementations are provided for state chart invocations, and (in CLJ) futures. It is a simple matter to expand the list of supported types.

WorkingMemoryStore

A protocol that represents a place to put the working memory of a state chart. This is used when you want an autonomous system that can "freeze" and "thaw" running sessions as events are received. Such a store could be in RAM (implementation provided) or in something more durable (Redis, SQL, Datomic, Filesystem).

StatechartRegistry

A protocol that allows a state chart to be saved/retrieved by a well-known name. An implementation is provided for tracking them in RAM, but you could also choose an execution model that allows your charts to be serializable, and then store the charts in something more durable.

Session

The combination of the content of the DataModel and Working Memory. I.e. the data you’d need in order to resume working from where you last left off. Sessions typically have a unique ID, which could be used to store sessions into durable storage when they are "idle", and are used for cross-session events.

Conditional Element

In state charts there is a node type (represented as a diamond) that represents a state in which the chart never "rests", but instead immediately transitions to another node based on predicate expressions. In this library (and SCXML) this is modelled with a state that has more than one transition, NONE of which have and :event qualifier (meaning they are exited as soon as they are entered, assuming there is a valid transition).

4.2. States

States may be atomic, compound (hierarchical), or parallel. The first two are generated with the state element, and the latter with parallel.

4.3. Transitions

Transitions are the consumers of events. Their "source" is their parent. Transitions can be eventless, and they can also have no target (indicating they do not change the active states, and are only for executing their content).

A state can have any number of transition elements. These are tested in order of appearance, and the first transition that matches the current circumstance is taken. Transitions are enabled when:

  • Their cond (if present) evaluates to true AND

  • Their event (if present) matches the current event’s name (See event name matching)

  • OR neither are present.

A transition that is marked external and targets its enclosing state will cause the exit/entry handlers to fire. An internal transition (that has no target at all) will not.

See the SCXML standard for other behaviors of transition.

See Shorthand Convenience for some alternative ways to represent transitions that are easier to read.

4.4. "Condition" States

Condition states from classic state charts (shown as a diamond in UML state chart notation) can be modelled using eventless transitions.

An "eventless" transition without a :cond is always enabled.

Below is a conditional state that when entered will immediately transition to either state :X or :Y, depending on the result of the first transition’s condition expression:

(state {:id :Z}
  (transition {:cond positive-balance? :target :X})
  (transition {:target :Y}))
Note
See Shorthand Convenience for a nicer-looking version of this.

4.5. Flow Control Elements

The SCXML standard (Section 3.12) defines flow control elements for conditional branching and iteration within executable content. This library provides native Clojure function equivalents:

4.5.1. If / elseif / else

Use If (capitalized to avoid collision with clojure.core/if), elseif, and else for multi-way branching inside executable content such as on-entry, on-exit, or transition bodies.

The :cond on If and elseif is an expression compatible with your execution model (typically (fn [env data] …​) returning a truthy value). Children before the first elseif or else form the "then" branch:

(on-entry {}
  (assign {:location [:x] :expr 2})
  (If {:cond (fn [_ data] (= (:x data) 1))}
    (assign {:location [:result] :expr :first})
    (elseif {:cond (fn [_ data] (= (:x data) 2))}
      (assign {:location [:result] :expr :second}))
    (elseif {:cond (fn [_ data] (= (:x data) 3))}
      (assign {:location [:result] :expr :third}))
    (else {}
      (assign {:location [:result] :expr :default}))))

Each branch can contain any executable content (including nested If statements). This is particularly useful for leveraging nested raise, allowing you to conditionally queue events on the internal queue without having the write a script or use the external queue.

4.5.2. foreach

Use foreach to iterate over a collection, executing children for each item:

  • :array — An expression returning the collection to iterate over

  • :item — A location (keyword or vector) where the current item is bound

  • :index — (optional) A location where the current zero-based index is bound

(on-entry {}
  (assign {:location [:evens] :expr []})
  (foreach {:array (fn [_ _] [1 2 3 4 5 6])
            :item  [:n]}
    (If {:cond (fn [_ data] (even? (:n data)))}
      (assign {:location [:evens]
               :expr     (fn [_ data]
                           (conj (:evens data) (:n data)))}))))

An empty collection simply skips the body. foreach and If can be freely nested.

4.5.3. The In Predicate

The W3C SCXML standard defines an In() predicate (Section 5.9) for checking whether a state is in the current configuration. This library provides In as a function that returns a predicate:

(transition {:event :check :target :next :cond (In :some-state)})

(In :some-state) returns a (fn [env data] …​) that checks whether :some-state is in the active configuration. This is useful for guards on transitions in parallel state charts where you need to coordinate across regions.

4.6. Event Processing

In a fully-fleshed system your event queue would have a corresponding runtime story, where process-event was automatically called on the correct chart/session/invocation/service when an event is available. As such, and event queue might be distributed and durable (e.g. using Kafka or the like), or might simply be something that runs in-core (a core.async go-loop).

The library includes a fully-functional system for simple applications in the simple namespace.

4.6.1. Event Name Matching

The SCXML standard describes a name matching algorithm for event names that allows for wildcard pattern matching. Event names are token-based and prefix-matched. Both . (dot) and / (slash) are treated as token separators. In this library keywords are used for event names. For example, the event name :a.b.c is matched by :a.b.c.*, :a.b.c, :a.b.*, :a.b, etc. That is to say that a transition with :event :a.b would be enabled by event :a.b.c.

Since / is also a token separator, Clojure’s namespaced keywords work naturally with prefix matching. For example, :error.network matches :error.network/timeout, and :done.invoke matches :done.invoke/child.

Important
Matching is strictly token-based, not substring-based. :foo matches :foo.bar but does not match :foobar.

The wildcard is always implied, but can be specified on a transition for clarity. Transitions are enabled and matched "in order", so you can model narrowed and catch-all behavior:

(state {:id A}
  (transition {:event :error.communication} ...)
  (transition {:event :error} ...))

where the first transition will be enabled only if the error is a communication one, and all errors will enable the second.

See the SCXML standard for the rules on transition preemption regarding conflicting transitions that match at the same time.

4.6.2. Send Targets

The SCXML standard (section 6.2.4) allows the format of the target to change based on the type, and implies that these are often URLs. The default implementation of the event queue in this library only supports targeting other state charts (see Send Types below), and when using the default send type, the target is expected to simply be a session-id, where session-id is a unique identifier, such as a GUUID.

Special target keywords

The W3C SCXML spec (§C.1.1) defines a few special string targets such as internal, #_parent, and <invokeid>. This library accepts those strings for compatibility with mechanical XML→Clojure ports, but the canonical (and recommended) form uses Clojure keywords:

Target Meaning

:_internal

Place the event on this session’s internal queue (drained in the same macrostep). Equivalent to <raise> semantics, but lets you carry data the same way <send> does.

:_parent

Send to the parent session (the session that <invoke>-d this chart). Resolves to (env/parent-session-id env) and propagates :invoke-id for parent-side correlation.

any other keyword (e.g. :my-session)

Treated as a literal session-id. This covers both the W3C #scxml<sessionid> form and the #_<invokeid> form, since this library uses the invocation id as the child’s session id.

Examples:

(Send {:event :keep-alive :target :_internal})           ;; raise on this session's internal queue
(Send {:event :report :target :_parent :data {...}})     ;; reply to invoking parent
(Send {:event :ping :target :other-session})             ;; send to a known sibling session

Other implementations of the EventQueue protocol may choose to define further refinements.

4.6.3. Send Types

The SCXML standard (section 6.2.5) defines types as a URI as well. The internal implementations in this library do not enforce this, but this library does recognize the string "http://www.w3.org/TR/scxml/#SCXMLEventProcessor" as a desire to talk to another state chart session (and is the only/default predefined value).

4.6.4. Error Handling in Executable Content (W3C §4.4 Strict Mode)

When executable content (<script>, <assign>, <send>, <foreach>, …​) raises an error, the W3C SCXML specification mandates two things:

  1. An error.execution event MUST be placed on the internal event queue, so the chart can react via a (transition {:event :error.execution …​}) handler.

  2. The remainder of the current block of executable content MUST be skipped (the offending element’s siblings do not run).

By default, this library implements (1) but not (2): an error queues error.execution, but subsequent siblings still run. This is a deliberate, backwards-compatible default for charts written before strict semantics were available.

To opt into the fully W3C-conformant behavior, use simple/strict-env instead of simple/simple-env:

(require '[com.fulcrologic.statecharts.simple :as simple])

(def env (simple/strict-env))

Or, if you assemble your own env from custom protocol implementations (a common pattern), set the flag directly:

(def env
  (-> (build-my-env)            ;; your registry, data model, etc.
      (assoc :com.fulcrologic.statecharts/errors-abort-siblings? true)))

Either way, all of the following will then abort the surrounding block on first error and route the queued error.execution event to a transition handler:

(state {:id :doing-work}
  (on-entry {}
    (script {:expr (fn [_ _] (do-something-risky))}) ;; if this throws...
    (assign {:location [:result] :expr 42}))         ;; ...this is skipped (strict mode)
  (transition {:event :error.execution :target :recovery}))

In non-strict mode the same chart still queues the error.execution event and routes to :recovery, but the assign would also have run before the transition fires. Most charts will not see a behavior difference; charts that did rely on later siblings running after a thrown earlier sibling should either fix the underlying error or stay on the default env.

4.6.5. Manual Polling Queue

There is a manually polled queue implementation in this library, with no automatic processing at all. If you want to support events that come from outside of the chart via the queue, then you have to create a loop that polls the queue and calls process-event!. If you do this, then event the delayed event delivery will work, as long as your code watches for the delayed events to appear on the queue.

(ns traffic-light
  (:require
    [com.fulcrologic.statecharts :as sc]
    [com.fulcrologic.statecharts.chart :refer [statechart]]
    [com.fulcrologic.statecharts.elements :refer [parallel state transition]]
    [com.fulcrologic.statecharts.events :refer [new-event]]
    [com.fulcrologic.statecharts.protocols :as sp]
    [com.fulcrologic.statecharts.simple :as simple]
    [com.fulcrologic.statecharts.util :refer [extend-key]]))

(def nk
  "(nk :a \"b\") => :a/b
   (nk :a/b \"c\") => :a.b/c"
  extend-key)

(defn traffic-signal [id initial]
  (let [red     (nk id "red")
        yellow  (nk id "yellow")
        green   (nk id "green")
        initial (nk id (name initial))]
    (state {:id      id
            :initial initial}
      (state {:id red}
        (transition {:event :swap-flow :target green}))
      (state {:id yellow}
        (transition {:event :swap-flow :target red}))
      (state {:id green}
        (transition {:event  :warn-traffic
                     :target yellow})))))

(defn ped-signal [id initial]
  (let [red            (nk id "red")
        flashing-white (nk id "flashing-white")
        white          (nk id "white")
        initial        (nk id (name initial))]
    (state {:id      id
            :initial initial}
      (state {:id red}
        (transition {:event :swap-flow :target white}))
      (state {:id flashing-white}
        (transition {:event :swap-flow :target red}))
      (state {:id white}
        (transition {:event :warn-pedestrians :target flashing-white})))))

(def traffic-lights
  (statechart {}
    (parallel {}
      (traffic-signal :east-west :green)
      (traffic-signal :north-south :red)

      (ped-signal :cross-ew :red)
      (ped-signal :cross-ns :white))))

(defn show-states [wmem]
  (println
    (sort
      (filter #{:north-south/red
                :north-south/yellow
                :north-south/green
                :east-west/red
                :east-west/yellow
                :east-west/green
                :cross-ns/red
                :cross-ns/white
                :cross-ns/flashing-white
                :cross-ew/red
                :cross-ew/white
                :cross-ew/flashing-white}
        (::sc/configuration wmem)))))

(def env (simple/simple-env))
(simple/register! env ::lights traffic-lights)
(def processor (::sc/processor env))
(def s0 (sp/start! processor env ::lights {::sc/session-id 1}))
(show-states s0)
(def s1 (sp/process-event! processor env s0 (new-event :warn-pedestrians)))
(show-states s1)
(def s2 (sp/process-event! processor env s1 (new-event :warn-traffic)))
(show-states s2)
(def s3 (sp/process-event! processor env s2 (new-event :swap-flow)))
(show-states s3)
(def s4 (sp/process-event! processor env s3 (new-event :warn-pedestrians)))
(show-states s4)
(def s5 (sp/process-event! processor env s4 (new-event :warn-traffic)))
(show-states s5)
(def s6 (sp/process-event! processor env s5 (new-event :swap-flow)))
(show-states s6)

4.7. Data Models

A data model is a component of the system that holds data for a given state chart’s session. The SCXML specification allows the implementation quite a bit of latitude in the interpretation of the chart’s data model. You could define scopes that nest, one global map of data that is visible everywhere, or hook your data model to an external database.

See the docstrings in the protocols namespace.

There is a predefined FlatWorkingMemoryDataModel (in data-model.working-memory-data-model) that puts all data into a single scope (a map which itself can be a nested data structure). This is the recommended model for ease of use.

There is also a predefined WorkingMemoryDataModel in that scopes data to the state in which it is declared.

Both of these put the real data in the session working memory, allowing the data, for example, to be persisted with the state of a running session when pausing it for later revival.

4.8. Execution Models

Most people will probably just use the CLJCExecutionModel, which lets you write executable content in CLJC as lambdas:

;; Use `data` to compute when this transition is "enabled"
(transition {:event :a :cond (fn [env data] (your-predicate data))}
  ;; Run some arbitrary code on this transition
  (script {:expr (fn [env data] ...)}))

There is a macro version of the script element called script-fn that can be used as a shorthand for script elements:

;; Use `data` to compute when this transition is "enabled"
(transition {:event :a :cond (fn [env data] (your-predicate data))}
  ;; Run some arbitrary code on this transition
  (script-fn [env data] ...)))

4.9. Working Memory and Identity

The working memory of the state chart is plain EDN and contains no code. It is serializable by nippy, transit, etc. Therefore, you can easily save an active state chart by value into any data store. The value is intended to be as small as possible so that storage can be efficient.

Every active state chart is assigned a ID on creation (which you can override via initialize). This is intended as part of the story to allow you to coordinate external event sources with working with instances of chart that are archived in durable storage while idle.

4.10. Accessing Running Charts from Outside the Chart

While you can work with the core algorithms as pure function, you will normally set up a standard system environment (where you provide an event queue and working memory store). When working with such a system you may have many charts running (stored in the working memory store) and can send them events via the event queue.

The com.fulcrologic.statecharts.runtime namespace includes functions which can be used to work with such a system from outside the chart itself.

current-configuration

Get the set of active states for by session id.

processing-env

Get a processing env (using a system env and session id)

session-data

Get internal state chart data from a particular state chart session.

send!

Send an event. The simple system has this function as well, and it is a standard part of the protocols, but this wrapper makes it a little more convenient to use when you already have a system env map.

Warning
Beware the term "env". In this library a system environment is a map that contains a key for the various components of the system (e.g. the event queue, processor, execution model, etc.). A processing env is an system environment which also includes the current details of a particular session and is the env you see in the lambdas in your chart. The latter can be used anywhere the former is needed, but not vice-versa.

4.11. Invocations

An invocation is an "external" service/chart/process that can be started when your state chart enters a state, exchanges events while that state is active (you can forward events and receive them). The invocation can self-terminate while the state is still active, but it will also be cancelled if your chart leaves the enclosing state.

Invocations can forward events to the target invocation, and can receive events back. An incoming event will be pre-processed by finalize elements and can update the data model before the event is further propagated through the chart. See the SCXML standard for a full description of how invocations work.

4.11.1. Passing Invocation Data

The invoke element has both a :namelist and :params argument. The former allows you to list data locations of the parent that should be copied to the child. :params is dynamic, and allows you to specify expressions that calculate values to inject into the child data model. These options can be used together, with params taking precedence.

(invoke {:namelist {[:area :x] [:target :y]}
         :params (fn [env data] {[:other :y] 42
         ...})

4.11.2. Invoking other State Charts or Futures

The library has a built-in InvocationProcessor that knows how to start other state charts via an invoke, and in CLJ there is also support for futures (which are cancelled if the state containing the invoke is exited).

The src/examples of the repository includes an example, shown below:

(ns invocations
  (:require
    [com.fulcrologic.statecharts :as sc]
    [com.fulcrologic.statecharts.algorithms.v20150901-validation :as v]
    [com.fulcrologic.statecharts.chart :refer [statechart]]
    [com.fulcrologic.statecharts.elements :refer [Send data-model final invoke log on-entry on-exit state transition]]
    [com.fulcrologic.statecharts.environment :as e]
    [com.fulcrologic.statecharts.event-queue.core-async-event-loop :as loop]
    [com.fulcrologic.statecharts.simple :as simple]
    [taoensso.timbre :as log]))

(def child-chart
  (statechart {}
    (data-model {:x 1})
    (state {}                                               ; top-level state so we can log an exit from the overall machine
      (on-exit {}
        (log {:level :info
              :label "CHILD CHART EXIT"}))

      (transition {:event  :event/exit
                   :target :state/final})

      (state {:id :X}
        (on-entry {}
          (log {:level :info
                :label "Child X" :expr (fn [_ {:keys [x]}] x)}))
        ;; NOTE: The future invocation processor is only coded for CLJ, so this invocation is ignored in CLJS
        (invoke {:id     :child/future
                 :type   :future
                 :params {:time (fn [_ {:keys [x]}] x)}
                 :src    (fn [{:keys [time]}]
                           (log/info "Invocation running for" time)
                           #?(:clj (try
                                     (Thread/sleep (long (* 1000 time)))
                                     (catch InterruptedException e
                                       (log/info "Future cancelled!")
                                       (throw e))))
                           (log/info "Future function completed")
                           {:future-result :DONE})})
        (transition {:event :done.invoke.*}
          (log {:level :info
                :label "Future indicated that it completed"
                :expr  (fn [e d]
                         (log/spy :debug d))}))
        (transition {:event :child/swap :target :Y}))
      (state {:id :Y}
        (on-entry {}
          (log {:level :info
                :label "Child Y"}))
        (on-exit {}
          (Send {:event      :child.left-y
                 :type       ::sc/chart
                 :targetexpr (fn [env data]
                               (e/parent-session-id env))}))
        (transition {:event :child/swap :target :X})))
    (final {:id :state/final})))

(comment
  (v/problems child-chart))

(def main-chart
  (statechart {}
    (state {:id :A}
      (on-entry {}
        (log {:level :info
              :label "Main A"}))
      (transition {:event :swap :target :B}))
    (state {:id :B}
      (on-entry {}
        (log {:level :info
              :label "Main B"}))
      (transition {:event :swap :target :A})
      (transition {:event :child.*}
        (log {:level :info
              :label "Child event" :expr (fn [_ data] data)}))
      (invoke {:id          :main/child
               :autoforward true                            ; be careful, sends all events through, but it is possible to cause infinite loops if child sends events in response
               :type        :statechart
               :src         `child-chart
               :params      {:x 10}
               :finalize    (fn [env data]
                              (log/info "Event from child to parent: " data))}))))

(comment
  (do
    (log/set-level! :info)                                  ; so we can see log elements
    (def session-id 42)
    (def env (simple/simple-env))
    (simple/register! env `main-chart main-chart)
    (simple/register! env `child-chart child-chart)
    (def running? (loop/run-event-loop! env 100))
    (simple/start! env `main-chart session-id))

  ;; Sending this multiple times with swap main chart states. When in B, a child chart will start.
  (simple/send! env {:target session-id
                     :event  :swap})

  (::sc/working-memory-store env)
  ;; With autoforward on, we can ferry events though to the child
  (simple/send! env {:target session-id
                     :event  :child/swap})

  ;; When the child chart is running (top chart is in :B), You can send it events.
  ;; The session ID of a child session will be the ID of the node, of if you don't supply one an autogenerated
  ;; one will be stored at idlocation with the string value <parent-session-ID `.` <generated-id>
  (simple/send! env {:target :main/child
                     :event  :child/swap})

  (simple/send! env {:target :main/child
                     :event  :event/exit})

  ;; terminate the event loop
  (reset! running? false))

4.11.3. Custom Invocation Processors

For example, suppose you want to install an invocation processor that can provide timer events on some interval. You could do something like:

(ns custom-invocation
  (:require
    [clojure.core.async :as async]
    [com.fulcrologic.statecharts :as sc]
    [com.fulcrologic.statecharts.chart :refer [statechart]]
    [com.fulcrologic.statecharts.data-model.operations :as ops]
    [com.fulcrologic.statecharts.elements :refer [invoke script-fn state transition]]
    [com.fulcrologic.statecharts.environment :as env]
    [com.fulcrologic.statecharts.event-queue.core-async-event-loop :as loop]
    [com.fulcrologic.statecharts.events :as evts]
    [com.fulcrologic.statecharts.protocols :as sp]
    [com.fulcrologic.statecharts.simple :as simple]
    [taoensso.timbre :as log]))

(deftype Timer [active-invocations]
  sp/InvocationProcessor
  (supports-invocation-type? [_this typ] (= typ :timer))
  (start-invocation! [_this {::sc/keys [event-queue]
                             :as       env} {:keys [invokeid params]}]
    (let [source-session-id (env/session-id env)
          {:keys [interval]
           :or   {interval 1000}} params
          time-id           (str source-session-id "." invokeid)
          notify!           (fn []
                              (log/info "sending notification")
                              (sp/send! event-queue env
                                {:target            source-session-id
                                 :send-id           time-id
                                 ;; IMPORTANT: If you don't include the invokeid, then it won't register in finalize
                                 :invoke-id         invokeid
                                 :source-session-id time-id
                                 :event             :interval-timer/timeout}))]
      (swap! active-invocations assoc time-id true)
      (async/go-loop []
        (async/<! (async/timeout interval))
        (if (get @active-invocations time-id)
          (do
            (notify!)
            (recur))
          (log/info "Timer loop exited")))
      true))
  (stop-invocation! [_ env {:keys [invokeid] :as data}]
    (log/spy :info data)
    (log/info "Invocation" invokeid "asked to stop")
    (let [source-session-id (env/session-id env)
          time-id           (str source-session-id "." invokeid)]
      (swap! active-invocations dissoc time-id)
      true))
  (forward-event! [_this _env _event] nil))

(defn new-timer-service
  "Create a new time service that can be invoked from a state chart."
  [] (->Timer (atom {})))

(def demo-chart
  (statechart {}
    (state {:id :A}
      (transition {:event :swap :target :B}))
    (state {:id :B}
      (transition {:event :swap :target :A})
      (transition {:event :interval-timer/timeout}
        (script-fn [_ data] (log/info "Main transition got data" (select-keys data [:B :timer-calls]))))

      (invoke {:idlocation [:B :invocation-id]
               :type       :timer
               :params     {:interval 500}
               :finalize   (fn [_env {:keys [_event timer-calls]}]
                             (log/info "Finalize got timer calls data: " [timer-calls _event])
                             ;; Finalize gets to update the model before the event is delivered...
                             [(ops/assign :timer-calls (inc (or timer-calls 0)))])}))))

(comment
  (do
    (def env (simple/simple-env {::sc/invocation-processors [(new-timer-service)]}))
    (simple/register! env `demo-chart demo-chart)
    (def queue (::sc/event-queue env))
    (def processor (::sc/processor env))
    (def session-id 42)
    (def wmem (atom {}))
    (def running? (loop/run-event-loop! env 100)))

  (simple/start! env `demo-chart session-id)

  ;; Send this one multiple times
  (simple/send! env {:target session-id
                     :event  :swap})

  ;; Send this one to exit the top level machine
  (simple/send! env {:target session-id
                     :event  evts/cancel-event})

  ;; stop the event loop
  (reset! running? false)
  )

The transition element responds to the events received by the state chart, and the invocation processor for an invoke can send such events. So, the timer service here is sending :interval-timer/timeout events.

4.11.4. Multiplex (Dynamic Fan-Out)

SCXML <invoke> declarations are static: one declaration starts exactly one child. Many real-world patterns — N voting agents, M-of-N retry, runtime-sized worker pools, heterogeneous panels of mixed children — need dynamic multiplicity that you can’t know at chart-authoring time.

The library ships with a general-purpose InvocationProcessor that fans out a single <invoke> declaration into N invocations of any other registered invocation type, with count, child type, and per-child params all computed at runtime against the parent’s data model. It preserves every standard SCXML guarantee: algorithm-managed lifecycle, a single done.invoke.<mux-id> to the grandparent when the cohort finishes, and clean parent↔child event routing.

Installation

with-multiplex is an idempotent installer — safe to call any number of times. It also installs the statechart invocation processor if it isn’t already present, because multiplex’s internal aggregator chart needs it. Users who only intend to multiplex non-statechart children (HTTP, futures, custom processors) do not need to install anything separately.

(require '[com.fulcrologic.statecharts.invocation.multiplex :as mux]
         '[com.fulcrologic.statecharts.invocation.multiplex-options :as mo]
         '[com.fulcrologic.statecharts.invocation.multiplex-processor :as mp])

(def env (-> (simple/simple-env) mp/with-multiplex))
The multiplex Element

(mux/multiplex {…​}) emits an ordinary invoke element whose type is the multiplex type.

(require '[com.fulcrologic.statecharts :as sc]
         '[com.fulcrologic.statecharts.chart :refer [statechart]]
         '[com.fulcrologic.statecharts.elements :refer [state on-entry transition final]])

;; A small "judge" chart, registered under ::judge.
(def judge-chart
  (statechart {}
    (state {:id :evaluate}
      (on-entry {}
        (script {:expr (fn [env data]
                         (mux/reply env :score-ready {:score (rand)}))}))
      (transition {:event :score-ready :target :done}))
    (final {:id :done})))

;; Parent chart with three judges fanned out by one declaration.
(def panel
  (statechart {:initial :judging}
    (state {:id :judging}
      (mux/multiplex
        {:id              :judges
         mo/child-type    ::sc/chart
         mo/count         3
         mo/child-params  (fn [_env _data idx]
                            {:src    ::judge
                             :params {:judge/idx idx}})})
      (transition {:event :done.invoke.judges :target :result}))
    (state {:id :result} ...)))

Required keys on the options map:

:id

The invokeid for this multiplex. May not have multiplex as either its name or its namespace — :multiplex, :multiplex/foo, and :foo/multiplex are all rejected at construction time (reserved as the child-sid prefix).

mo/child-type

The underlying invocation type used for every child (e.g. ::sc/chart).

mo/count

Number of children to spawn.

Optional:

mo/child-params

(fn [env data idx]) returning the full start-invocation arg shape the underlying processor expects (for statechart children this is {:src ::chart-key :params {…​}}). Defaults to a fn returning {}.

:autoforward

Pass-through to the underlying invoke. Defaults to true — the multiplex’s parent → cohort routing relies on the autoforward path, so you normally do not set this. Pass :autoforward false only if you want to disable forwarding entirely and manage cohort routing yourself (rare; mux/send will not work for that multiplex).

Runtime Dynamism

mo/count and mo/child-type may be literals OR (fn [env data]) (or 4-arity when the execution model has explode-event?). They are evaluated once at start-invocation time against the parent’s data model:

(mux/multiplex
  {:id              :workers
   mo/child-type    ::sc/chart
   mo/count         (fn [_env data] (count (:queue/jobs data)))   ; dynamic N
   mo/child-params  (fn [_env data idx]
                      {:src    ::worker
                       :params {:job (nth (:queue/jobs data) idx)}})})

mo/child-params is always a function of (env, data, idx) and is called once per child at fan-out time. If it needs event context, read :_event from data.

Child Naming and Event Matching

Each child gets the invokeid :multiplex.<mux-id>.<idx> — e.g. :multiplex.judges.0. The multiplex. prefix is critical: it prevents SCXML dot-prefix matching from conflating per-child done events with the cohort’s own done event.

Given a :judges multiplex with three children, you can match three useful granularities:

Event fired Matches done.invoke.judges Matches done.invoke.multiplex.judges Matches done.invoke.multiplex.judges.1

done.invoke.judges (cohort summary)

yes

no

no

done.invoke.multiplex.judges.0

no

yes

no

done.invoke.multiplex.judges.1

no

yes

yes

done.invoke.multiplex.judges.2

no

yes

no

(transition {:event :done.invoke.judges             :target :all-done})
(transition {:event :done.invoke.multiplex.judges   :target :one-replied})
(transition {:event :done.invoke.multiplex.judges.1 :target :judge-1-done})
Cohort Completion

When the multiplex starts, the processor synthesizes a small internal aggregator statechart and starts it at sid = <mux-id>. Each child’s ::sc/parent-session-id is set to the multiplex’s sid, so every done.invoke.<child-sid> routes to the aggregator. The aggregator counts these and transitions to its :done final state when all N have completed — at which point the W3C algorithm fires the standard done.invoke.<mux-id> event to the grandparent.

The grandparent sees exactly one summary event when the whole cohort is finished, just as it would for any ordinary <invoke>.

In addition, the aggregator re-emits each per-child done event (done.invoke.multiplex.<mux-id>.<K>) to the grandparent. User charts can therefore observe per-child completion to drive UI updates (a progress bar, a "Judge 1 complete!" toast, an early-exit decision) without having to wait for the cohort summary. All three match granularities shown above fire on the grandparent:

Grandparent transition :event Fires when

:done.invoke.judges

The whole cohort is complete. Once.

:done.invoke.multiplex.judges

ANY single judge completes (prefix-matches all per-child events). N times — once per child.

:done.invoke.multiplex.judges.1

Judge 1 specifically completes. Once.

Child Start Failures

If an underlying processor refuses to start a child — for example, a statechart child whose :src is not registered — multiplex does two things automatically:

  • Enqueues a synthetic done.invoke.multiplex.<mux-id>.<K> event to the aggregator’s session, so the aggregator’s tally still reaches N. The cohort’s done.invoke.<mux-id> still fires for the grandparent.

  • Forwards an :error.platform event to the grandparent with {:invokeid <child-sid> :reason …​} in its data so user code can react.

This applies to both sync false returns and async rejected promises. A handful of failed starts will not deadlock the cohort.

Parent to Cohort Routing

The recommended way for a grandparent to send events to a cohort is mux/send, a convenience element constructor that produces the correct <send> for you:

;; Inside a transition or on-entry in the grandparent chart:

;; Broadcast to every child (the default):
(mux/send {:target :judges :event :go :data {:payload 1}})

;; Address a specific child by index:
(mux/send {:target :judges :idx 1 :event :evaluate :data {:item the-item}})

;; Deliver to one arbitrary child:
(mux/send {:target :judges :idx :any :event :go})

Option keys:

:target

(Required.) The multiplex’s :id (keyword).

:event

(Required.) Event-name keyword to deliver.

:idx

(Optional.) Integer K, :any, or :all. Defaults to :all (broadcast).

:data

(Optional.) User data merged into the outgoing event’s :data.

mux/send works because :autoforward is on by default. If you explicitly set :autoforward false on the multiplex, mux/send will not route events to that multiplex’s children — you would have to write your own send and your own forwarding.

Under the hood, mux/send addresses the grandparent’s own session and embeds mo/to (the route) and mo/target-mux (the multiplex :id discriminator) into event data. The algorithm’s autoforward path then delivers the event to all multiplex invocations active in the parent state; each multiplex’s forward-event! checks mo/target-mux and either claims the event or no-ops. The processor strips both mo/to and mo/target-mux from event data and adds mo/from before delivering to the chosen child(ren).

Note

Writing a raw (send {:target :#_<mux-id> …​}) does not route through the multiplex: that addresses the multiplex’s aggregator session, which only handles per-child done events. Use mux/send for targeted parent → cohort routing.

Multiple Multiplexes in One State

Multiple mux/multiplex elements can live in the same parent state. Because mux/send automatically embeds the target’s :id in event data as mo/target-mux, the autoforward path delivers each event to every sibling multiplex but only the targeted multiplex acts on it; the others no-op cleanly. This lets you compose, say, a :judges cohort and a :scribes cohort side by side and address each independently.

If you author a raw <send> (not via mux/send) that triggers autoforward, the event will be processed by every active multiplex in the state — that is the standard SCXML autoforward semantic, and the legacy broadcast behavior is preserved for raw callers that omit mo/target-mux. Prefer mux/send for targeted routing.

mo/from annotates events crossing the multiplex boundary, and its shape depends on direction:

  • Parent to child (added automatically by the multiplex’s forward-event!): {:sid <grandparent-sid>}.

  • Child to parent (added by mux/reply): {:sid <child-sid> :idx <K> :invokeid <mux-id> :grandparent <grandparent-sid>}.

The asymmetry is intentional: the parent is not a member of the cohort, so it has no :idx or :invokeid. Receivers can address a follow-up at a specific child via (mux/send {:target <mux-id> :idx K :event :follow-up}).

Cohort to Outside Routing

Children call mux/reply to send an event to the grandparent (the session that declared the multiplex). It reads mo/identity from the child’s data model and merges it into outgoing event data under mo/from, so the receiver can address a follow-up back at this specific child:

(script {:expr (fn [env data]
                 (mux/reply env :score-ready {:score 0.83}))})

The grandparent receives {:score 0.83, mo/from {:sid :multiplex.judges.2 :idx 2 :invokeid :judges :grandparent <gp-sid>}} and can target a follow-up via (mux/send {:target :judges :idx 2 :event :next …​}).

mo/identity

The multiplex automatically seeds mo/identity {:sid :idx :invokeid :grandparent} into each child statechart’s data model at start. Authors generally don’t need to read it directly — mux/reply does that for them. For non-statechart child types the value is still injected into the child’s params; that processor decides how (or whether) to expose it.

Edge Case: mo/count = 0

The aggregator is started with :n 0 and an eventless transition fires immediately on entry, sending done.invoke.<mux-id> to the grandparent without spawning any children. Behaviour is symmetric with the N>0 case.

Lifecycle

When the parent state exits, the algorithm calls stop-invocation! on the multiplex. The processor stops the aggregator first (so any in-flight tally updates don’t fire a late cohort done event) and then stops all N children via their underlying processor.

Async Engines

The multiplex processor honors the library’s sync/async contract:

  • Under simple/simple-env, every sp/start-invocation! returns plain true. Multiplex returns true synchronously — no promise wrapping.

  • Under simple-async/simple-env, child or aggregator starts may return promises. Multiplex’s own start-invocation! then returns Promise<true> that resolves once all child starts AND the aggregator start have settled. stop-invocation! behaves analogously: it awaits the aggregator and child cleanups before reporting completion.

  • Children are spawned after the aggregator’s start resolves, so the aggregator’s session is always registered to receive child done events before any child can fire one.

Implementation reference: the same pattern used by invocation/statechart.cljc (the canonical async-aware invocation processor).

Limitations
  • :id cannot have multiplex as either its name or its namespace. All of :multiplex, :multiplex/foo, and :foo/multiplex are rejected at construction time, because the multiplex processor uses the multiplex. prefix on child sids and dot-prefix event matching would otherwise produce false collisions.

  • For statechart children, mo/child-params must return start-invocation maps shaped like {:src ::chart-key :params {…​}}.

  • Built-in termination policy is "all children done." First-reply, m-of-n, and other policies are not built in — compose them in the grandparent by tallying child done events yourself and emitting your own summary events.

  • Cross-cohort coordination ("fire when either of two sibling multiplexes finishes first") is also a grandparent-side pattern.

  • mo/from on outgoing events from non-statechart child processors is a convention, not enforced.

  • mux/send requires :autoforward true (the default). If you set :autoforward false, neither mux/send nor any raw <send> to #_<mux-id> will reach the cohort via forward-event! — you must implement your own targeted send mechanism.

  • mo/target-mux is library-controlled: mux/send writes it for you. User code should not normally write it directly — use mux/send.

  • Nested multiplex with shared :id: when multiple instances of the same child chart run concurrently (e.g. as siblings under an outer multiplex), each instance tries to claim the same aggregator and child session-ids. Give each inner multiplex a unique :id per outer instance — vary it from inside mo/child-params using idx to disambiguate, or author distinct child charts per outer position. This is the same explicit-id constraint that affects any SCXML <invoke> instantiated multiple times concurrently; it just bites nested fan-out harder.

5. Shorthand Convenience

Making your state chart definition cleaner is a simple matter, since it is nothing more than a nested data structure.

One thing to note is that every element of the state chart can accept a nested sequence of children, and it will automatically flatten them. This means you can write helper functions that emit sequences of children, which in turn can use other helpers that might emit sequences.

Thus, macros and functions can be used to generate common patterns. The convenience and convenience-macros nses define some examples. These two namespaces are currently ALPHA and are not API stable, but it is a simple matter to copy their content if you like any of them and want to rely on them.

The macro versions expect you to be using the lambda execution model, and require that you use a symbol for the expression (that resolves to a function). They add some additional :diagram/??? attributes to the elements that are string versions of the expression, for use in diagram tools or possibly even export.

One common pattern is to schedule a delayed event on entry to a state, but cancel (if non-delivered) on exit. This helper exists in convenience, and looks like this:

(defn send-after
  [{:keys [id delay delayexpr] :as send-props}]
  (when-not id (throw (IllegalArgumentException. "send-after's props MUST include an :id.")))
  [(on-entry {}
     (Send send-props))
   (on-exit {}
     (cancel {:sendid id}))])

There are also some simple ones (as functions) that clean up readability for common cases:

(transition {:event :E :target :target-state}
  optional-executable-elements ...)

;; has a convenience version:
(on :E :target-state
  optional-executable-elements...)

;; or if there is just a script and no target (just an event handler that stays in the same state):
(handle :E expr)
;; means:
(transition {:event :E}
  (script {:expr expr}))

A good use-case for a macro comes up when you want to emit nodes that might be better suited for a diagram tool. The UML state chart system defines a choice node which is a node that makes a decision about where to transition to. In the SCXML standard they are coded as a state that includes nothing but event-less transitions with conditions:

  (state {:id node-id :diagram/prototype :choice}
    (transition {:cond pred :target target-state})
    (transition {:cond pred2 :target target-state2})
    (transition {:target else-target-state})

Which is not only a bit noisy, but it isn’t immediately obvious to the reader that this is a node that merely makes a choice. Additionally, with the lambda execution model the predicates are code, so there is no way for them to easily be emitted to a diagram.

So there is a macro version of this called choice in the convenience-macros namespace:

  (choice {:id node-id ...}
    pred  target-state
    pred2 target-state2
    :else else-target-state)

that is not only more concise, but adds {:diagram/condition "pred"} to the transitions properties (the stringified expression of the predicate).

There is also a function version of choice in convenience that does no add the diagram note, but looks identical to the reader.

See the docstrings in those namespaces for more functions/macros that can make your charts more concise.

6. Custom Executable Content

The SCXML standard defines a number of elements it terms "Executable Content", meaning child nodes that do some action. For example, send is executable content of this on-entry node:

(state {}
  (on-entry {}
     (send ...)))

The standard allows for a compliant implementation to include extra executable content, but since this library is in Clojure you have the power of macros and functions, which XML does not.

The internals allow you to return a collection of elements from a function, which will be "spliced" in place. This allows you to easily create macros and functions that can make your state charts much easier to write. Some examples in the library source code are the com.fulcrologic.statecharts.convenience-macros/choice macro, and functions like com.fulcrologic.statecharts.integration.fulcro.ui-routes/rstate in the (legacy) Fulcro UI Routing support.

7. Integration with Fulcro

The Fulcro integration for state charts has the following general enhancements over the standard state charts:

  • Use the Fulcro app’s state database as the DataModel

  • Use core.async to automatically support an EventQueue

  • Support a "local data" area for the state chart session that won’t accidentally collide with other database concerns.

  • Allow for the use of actors (a component abstraction) and aliases (to database locations)

  • Supply an extensible set of operations that executable elements can leverage:

    • The ability to use Fulcro’s load to populate the state database.

    • The ability to invoke remote mutations.

    • The ability to leverage mutation helpers for optimistic updates.

Namespace aliases used in this document:

[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.statecharts.elements :as ele]
[com.fulcrologic.statecharts :as sc]
[com.fulcrologic.statecharts.chart :as chart]
[com.fulcrologic.statecharts.data-model.working-memory-data-model :as wmdm]
[com.fulcrologic.statecharts.data-model.operations :as ops]
[com.fulcrologic.statecharts.integration.fulcro :as scf]
[com.fulcrologic.statecharts.integration.fulcro.operations :as fop]
[com.fulcrologic.statecharts.integration.fulcro.async-operations :as afop]
[com.fulcrologic.statecharts.protocols :as sp]

7.1. Basic Usage

There are three basic steps: install the support, register machines, and start them:

;; 1. Install state charts on the app. Should be done once at startup, but this is an idempotent operation.
(scf/install-fulcro-statecharts! app)

;; 2. Define your charts
(def chart (chart/statechart {}
         ...))

;; 3. Register your chart under a well-known name. NOTE: The state charts have to be installed *before* calling register!
(scf/register-statechart! app ::chart chart)

...

;; 4. Start some state chart. The session-id can be a unique uuid, or a well known thing like a keyword. Be careful, though,
;; because starting a machine using an existing ID will overwrite the existing one.
(scf/start! app {:machine ::chart        ; registered chart name
                 :session-id :some-id})  ; globally unique session id

7.2. The Data Model

The Fulcro state charts data model has a number of features to help you work with Fulcro applications.

Two special concepts were take from Fulcro’s own UI state machines: aliases and actors. These are implemented purely on the data model by simply adding entries to a state chart’s local data under the special keys:

  • :fulcro/aliases - A map from a keyword to a path. The path itself can be any legal DataModel path (see later) except for another alias.

  • :fulcro/actors - A map from a keyword to an scf/actor, which tracks the class and ident of a UI component. Can be used to find the UI component (for normalization/loads) and in data paths.

Notes:

  • Actors MUST be identified by keywords with an actor namespace: e.g. :actor/thing.

  • Actor keywords may only appear as the first element of a path.

  • Aliases are NOT used within paths. They define a path. Therefore, arguments that would normally take a vector to describe a data path will usually accept an alias keyword instead.

7.2.1. Initializing the Data Model

You can use the initial data in sp/start! or a top-level data-model element to put data into the local storage of your state chart. This is particularly useful for specifying things like aliases on the chart itself, but defining actors at runtime:

(def c (chart/statechart {}
         (data-model {:expr {:fulcro/aliases {:a [:actor/thing :thing/field]}}})
         ...))
(scf/register-statechart! app ::c c)

...

(scf/start! app {:machine ::c
                 :session-id :some-id
                 :data {:fulcro/actors {:actor/this (scf/actor Thing [:thing/id 1])}}})

The above code defines a chart that will have :fulcro/aliases on the local data model because of the state chart definition, and will have a runtime value for the :fulcro/actors based on data that was passed during start. Anything initialized this way will go into the local data store (which is a path based on the session id in the app database).

Changing aliases and actors on the fly is therefore a simple matter of doing an op/assign operation on the data model.

7.2.2. Data Locations

There are four primary ways to address data in the data model, and the standard state chart operations such as op/assign already support these abstract paths:

A keyword (not in a vector)

IF this keyword exists in the :fulcro/aliases map, then the value of that alias (which can be a path that contains any of the other things in this list) is used to find the location; otherwise the keyword is relative in the root of the LOCAL data for the state chart.

A vector starting with :ROOT (or a keyword that doesn’t match the other cases)

A path in the local data of the state chart. Same as using a path without :ROOT. Included to be compatible with the standard location support.

A vector starting with :fulco/state or :fulcro/state-map

Indicates an absolute path in the Fulcro app database.

A vector starting with an actor name

If the first element of the vector matches an entry in the local state charts :fulcro/actors then :fulcro/state and the ident of that actor are spliced together in place of that keyword and the resulting path is treated as above.

7.3. Executable Content

The executable content nodes (predicates and other expressions) in the state chart can be functions of two arguments: env (the processing environment) and data.

You can get the current state chart session ID using the processing environment, and you can also pull the various components of the state chart system from there (e.g. (::sc/event-queue env)). The data argument includes ALL the state chart local data (including the special :fulcro/aliases and :fulcro/actors, which have special meaning but are really just normal local data). The data will also include the standard :_event (which is a map that has things like :target) and an extended key for :fulcro/state-map which has the current value of the Fulcro state database.

7.3.1. Operations

Non-predicate executable content (e.g. script) functions can return a vector of operations to run. The standard set (assign and delete) are supported, and use the extended path support described for the DataModel.

There are some additional operations for doing I/O:

(fop/invoke-remote txn options)

Run a single-mutation txn (e.g. [(f {:x 1})]) on a remote. The options allow you to specify events to trigger on the results. See scf/mutation-result. You can, of course use data :target and :returning to auto-merge graph data return values. The :target option can use an actor keyword as a convenience. :target Can be a normal Fulcro state-map path, a defined alias, or a path that can include actors (which will splice the actor’s ident into the target path).

(fop/load query-root component-or-actor options)

Issue a Fulcro load with an EQL query. options supposed the normal data fetch arguments, and additionally let’s you indicate what events to send when done/failed.

When using invoke-remote you will often not have a local Fulcro CLJS mutation. This means that you’d normally need to syntax-quote the transaction; however, remember that the Fulcro mutations namespace includes a declare-mutation helper that will make a "callable" function-like object that just returns itself as data.

(m/declare-mutation login app.authentication.session/login)

...

(def statechart
...
   (script {:expr [(fop/invoke-remote [(login {...})] {:ok-event :event/success :error-event :event/failed)]}))

7.3.2. Async Operations

When using the async execution engine (:async? true), you can issue Fulcro loads and remote mutations that resolve as promises within the algorithm. The chart transitions atomically — it never observably rests in a "loading" state.

The point is to make async operations "park" (effectively block) the statechart execution until the promise is fulfilled or rejected. This allows you to write statecharts that do not need so many intermediate states for tracking if a promise is fulfilled.

To enable async operations, pass :async? true when installing statecharts:

(scf/install-fulcro-statecharts! app {:async? true})

This swaps in the async processor and execution model from the Async Execution Engine section.

The com.fulcrologic.statecharts.integration.fulcro.async-operations namespace (aliased as afop) provides two layers of async support.

afop/load and afop/invoke-remote return operation maps that can be mixed into the same result vector as synchronous operations like ops/assign. The async execution engine detects these maps and awaits the underlying promise automatically:

;; Load data and set a flag — both in one expression result
(state {:id :loading-user}
  (on-entry {}
    (script {:expr (fn [env data]
                     [(ops/assign :loading? true)
                      (afop/load :user User {::sc/ok-event    :event/user-loaded
                                             ::sc/error-event :event/load-failed})])}))
  (transition {:event :event/user-loaded :target :viewing-user})
  (transition {:event :event/load-failed :target :error}))

afop/load parameters:

  • query-root — A keyword or ident for the root of the remote query

  • component-or-actor — A Fulcro component class, or a keyword naming a known actor

  • options:

    • ::sc/ok-event / ::sc/error-event — Events to raise on completion/failure

    • ::sc/ok-data / ::sc/error-data — Extra data to merge into the event

    • ::sc/target-alias — Target the load result at a statechart alias

    • Other df/load! options (:marker, :remote, etc.)

afop/invoke-remote parameters:

  • txn — A Fulcro transaction vector containing a single mutation

  • options:

    • :ok-event / :error-event — Events to raise on success/failure

    • :ok-data / :error-data — Extra data for the events

    • :target — Data-targeting path (vector, alias keyword, or actor-prefixed path)

    • :returning — Component class or actor keyword for normalization

    • :mutation-remote — Remote name (defaults to :remote)

    • :tx-options — Options passed to rc/transact!

;; Remote mutation with optimistic update
(state {:id :saving}
  (on-entry {}
    (script {:expr (fn [env data]
                     [(ops/assign :saving? true)
                      (afop/invoke-remote [(save-user (:form-data data))]
                        {:ok-event    :event/saved
                         :error-event :event/save-failed
                         :returning   User})])}))
  (transition {:event :event/saved :target :success})
  (transition {:event :event/save-failed :target :error}))
Promise Helpers (Advanced)

For complex custom expressions, afop/await-load and afop/await-mutation are imperative functions that return promesa promises directly. These are used internally by the operation-map handlers above, but are also available when you need full control.

Importantly, the async execution engine is not limited to Fulcro I/O — any function that returns a promise works. This makes it straightforward to integrate with the broader async JS ecosystem (fetch, IndexedDB, Web APIs, third-party SDKs) without needing extra intermediate states in your chart:

;; Using await-load for a Fulcro load
(script {:expr (fn [env data]
                 (afop/await-load env :user User
                   {::sc/ok-event    :event/user-loaded
                    ::sc/error-event :event/load-failed}))})

;; Using a plain promise for a fetch call
(script {:expr (fn [env data]
                 (p/let [response (js/fetch "/api/data")
                         json     (.json response)]
                   [(ops/assign :result (js->clj json :keywordize-keys true))]))})

await-load and await-mutation accept the same parameters as the operation-map constructors, plus an env argument (the statechart environment) as the first parameter.

Comparison: Send-based vs Async

With standard operations (fop/load), intermediate states are visible:

;; Using fop/load — chart rests in :loading until external event arrives
(state {:id :loading}
  (on-entry {}
    (script {:expr (fn [env data]
                     [(fop/load :user User {::sc/ok-event :event/loaded})])}))
  (transition {:event :event/loaded :target :viewing}))

With async operations (afop/load), the transition is atomic:

;; Using afop/load — atomic transition, never observably in :loading
(state {:id :loading}
  (on-entry {}
    (script {:expr (fn [env data]
                     [(afop/load :user User {::sc/ok-event :event/loaded})])}))
  (transition {:event :event/loaded :target :viewing}))
Note
The existing fop/load and fop/invoke-remote operations remain unchanged and continue to work with both sync and async execution engines.

7.4. Useful Helpers

7.4.1. Functions

(scf/local-data-path session-id)

Get the path of the local data for a given session. This is useful for adding a lookup ref to a UI component whose rendering depends on changes to this local state.

(scf/statechart-session-ident session-id)

Get the ident of the state chart session itself. This is useful for adding a lookup ref to a UI component whose rendering depends on changes to the state chart’s configuration.

(resolve-aliases data)

Used in executable content to return a map for all aliases. It looks up every alias from :fulcro/aliases and returns a map with them as keys, and their extracted data as values.

(resolve-actors data :actor/thing :actor/other …​)

Resolves the UI props of multiple named actors. The return value is a map from actor name to the UI props (tree).

(resolve-actors data :actor/thing)

Resolves the UI props of a single actor, and returns them.

(resolve-actor-class data actor-key)

Returns the Fulcro component that is currently acting as the UI counterpart of the named actor, if known.

(scf/send! app-ish session-id event optional-data)

Send an event to a running state chart.

(scf/current-configuration app-ish session-id)

Returns the current configuration (active states) of the given state chart instance. Useful in the UI when you need to render content based on state, but remember to add (scf/statechart-session-ident session-id) to any component query where that is necessary (to ensure render updates).

(scf/mutation-result data)

Extracts the raw return value of a remote mutation when the event being processed is the result of a mutation result that was originally triggered by a fops/invoke-remote.

(m/declare-mutation)

Makes a function-like object that can be used to generate remote mutation calls in transactions for invoke-remote.

7.4.2. Content of data in Executable Content

The data parameter of runtime content (e.g. script nodes) contains:

  • The local data of the state chart (at the top level).

  • The special standard (from SCXML) :_event that is the event that is being processed, which in turn has:

    • :data that contains any data sent with the event.

    • :target The session ID of the state chart

  • A special :fulcro/state-map key that is the current value of the Fulcro application state.

7.4.3. Runtime env of Executable Content

The runtime env in executable elements includes:

  • Any data passed via the extra-env argument to install-fulcro-statecharts!

  • :fulcro/app - The Fucro app itself.

  • ::sc/statechart-registry - The state chart Registry instance

  • ::sc/data-model - The state chart DataModel instance

  • ::sc/event-queue - The state chart EventQueue instance

  • ::sc/working-memory-store - The state chart working memory store

  • ::sc/processor - The state chart processing algorithm

  • ::sc/invocation-processors - The supported invocation processors

  • ::sc/execution-model - The CLJC state chart ExecutionModel

7.5. React Hooks

There is support for using a state chart as a co-located element of a hooks-based component.

The basic idea is that the state chart will be started when the component uses it, and when the component leaves the screen the chart is sent an :event/unmounted. If the chart reaches a top-level final state, then it will be GC’d from state.

The session ID of the chart is auto-assigned a random UUID, but you can specify a known session ID to allow for a state chart to survive the component mount/unmount cycle.

Here is an example of using this support to create a simple traffic light that can regulate (red/yellow/green) or blink red:

(defsc TrafficLight [this {:ui/keys [color]}]
  {:query         [:ui/color]
   :initial-state {:ui/color "green"}
   :ident         (fn [] [:component/id ::TrafficLight])
   :statechart    (statechart {}
                    (state {:id :state/running}
                      (on :event/unmount :state/exit)
                      (transition {:event :event/toggle}
                        (script {:expr (fn [_ {:keys [blink-mode?]}]
                                         [(ops/assign :blink-mode? (not blink-mode?))])}))

                      (state {:id :state/green}
                        (on-entry {} (script {:expr (fn [_ _] [(fops/assoc-alias :color "green")])}))
                        (send-after {:delay 2000
                                     :id    :gty
                                     :event :timeout})
                        (transition {:event  :timeout
                                     :target :state/yellow}))
                      (state {:id :state/yellow}
                        (on-entry {} (script {:expr (fn [_ _] [(fops/assoc-alias :color "yellow")])}))
                        (send-after {:delay 500
                                     :id    :ytr
                                     :event :timeout})
                        (transition {:event  :timeout
                                     :target :state/red}))
                      (state {:id :state/red}
                        (on-entry {} (script {:expr (fn [_ _] [(fops/assoc-alias :color "red")])}))
                        (send-after {:delay 2000
                                     :id    :rtg
                                     :event :timeout})
                        (transition {:cond   (fn [_ {:keys [blink-mode?]}]
                                               (boolean blink-mode?))
                                     :event  :timeout
                                     :target :state/black})
                        (transition {:event  :timeout
                                     :target :state/green}))
                      (state {:id :state/black}
                        (on-entry {} (script {:expr (fn [_ _] [(fops/assoc-alias :color "black")])}))
                        (send-after {:delay 500
                                     :id    :otr
                                     :event :timeout})
                        (transition {:event  :timeout
                                     :target :state/red})))
                    (final {:id :state/exit}))
   :use-hooks?    true}
  (let [{:keys [send! local-data]} (sch/use-statechart this {:data {:fulcro/aliases {:color [:actor/component :ui/color]}}})]
    (dom/div {}
      (dom/div {:style {:backgroundColor color
                        :width           "20px"
                        :height          "20px"}})
      (dom/button {:onClick (fn [] (send! :event/toggle))}
        (if (:blink-mode? local-data) "Blink" "Regulate")))))

7.6. Hierarchical Routing

Important
The routing system with URL synchronization, cross-chart routing (:route/reachable), deep busy-checking, a pluggable URL codec, and route configuration validation is now a separate library: com.fulcrologic/fulcro-statechart-routing. It shipped inside this library during 1.4.0-RC1 through RC20 and keeps the same namespaces, so migrating only requires adding that dependency. The legacy ui-routes support described below is deprecated and kept only for backward compatibility.

STATUS: DEPRECATED (see above).

The intention of this system is to make it possible to completely compose a webapp as a statechart, including the concern of UI routing, URL tracking/restore, etc. Routing actually caused the motivation for statecharts async support.

The routing system supports hierarchical path composition and parameterized URL segments. Nested route states can each contribute a piece of the URL path, and keyword placeholders in path segments are matched against URL parts to extract parameters.

7.6.1. Path Composition

Each route state can declare a :route/path — a vector of strings and keyword placeholders. When route states are nested, the paths compose hierarchically. For example:

(routes {:routing/root Root :id :routes}
  (rstate {:route/target UserList :route/path ["users"]}
    (rstate {:route/target UserDetail :route/path [:id]}
      (rstate {:route/target UserEdit :route/path ["edit"]}))))

The full URL path for UserEdit would be /users/42/edit — each ancestor’s :route/path segments are prepended automatically.

7.6.2. Parameterized Path Segments

Keyword segments (like :id above) act as parameter placeholders. When a URL is matched, the corresponding path segment is extracted into a parameter map:

;; URL: /users/42/edit
;; Matched pattern: ["users" :id "edit"]
;; Extracted params: {:id "42"}

Parameters are made available via [:routing/parameters <state-id>] in the data model, and are also persisted to the URL when navigating programmatically.

7.6.3. Key Functions

The com.fulcrologic.statecharts.integration.fulcro.route-url namespace provides the pure functions for path operations:

(resolve-full-path statechart state-id)

Walk the parent chain collecting :route/path segments from each ancestor. Returns a flat vector like ["users" :id "edit"].

(match-path path pattern)

Match a URL path (vector of strings) against a pattern (vector of strings and keyword placeholders). Returns nil on mismatch, or a map of extracted params.

(build-route-table statechart)

Scan all states with :route/target, compute full paths, and return a sorted vector of route entries ordered by specificity (more literal segments first).

(find-route-for-url route-table path)

Find the first matching route entry for a given URL path, returning the match with extracted :route/path-params.

The start-routing! function in ui-routes automatically builds the route table and uses it for URL-to-state matching, including on browser back/forward navigation.

8. Testing

The main interface to this library is pure and functional, which makes the general job of testing easier in some cases, but the fact is that you often need to walk a state chart through several steps in order to get it into the starting configuration to test.

The fact that nodes can execute (possibly side-effecting) code also means that when testing it is usually desirable to eliminate these side effects through some kind of stubbing mechanism.

Fortunately the design of the library makes it trivial to plug in a mock execution model, mock event queue, and a test data model, which allows you to easily exercise a state chart in tests in ways that do not side effect in an uncontrolled fashion.

The com.fulcrologic.statecharts.testing namespace includes mocks for the necessary protocols, allows for a pluggable data model (defaults to flat working memory), and has pre-written helpers and predicates.

The mock execution model allows you to easily set up specific results for expressions and conditions that would normally be run.

Here is an example test (written with fulcro-spec):

(ns com.fulcrologic.statecharts.testing-spec
  (:require
    [com.fulcrologic.statecharts.chart :as chart]
    [com.fulcrologic.statecharts.elements :refer [state transition]]
    [com.fulcrologic.statecharts.testing :as testing]
    [fulcro-spec.core :refer [=> assertions component specification]]))

(defn is-tuesday? [env data] false)

(def some-statechart
  (chart/statechart {}
    (state {:id :state/start}
      (transition {:cond   is-tuesday?
                   :event  :event/trigger
                   :target :state/next}))
    (state {:id :state/next})))

(defn config [] {:statechart some-statechart})

(specification "My Machine"
  (component "When it is tuesday"
    (let [env (testing/new-testing-env (config) {is-tuesday? true})]

      (testing/start! env)
      (testing/run-events! env :event/trigger)

      (assertions
        "Checks to see that it is tuesday"
        (testing/ran? env is-tuesday?) => true
        "Goes to the next state"
        (testing/in? env :state/next) => true)

      (testing/goto-configuration! env [] #{:state/start})

      (assertions
        "Can be forced into a state"
        (testing/in? env :state/start) => true))))

8.1. Mocking

The mocking (set when creating the testing env) is a simple map (e.g. {is-tuesday? true}). The keys of the map must exactly match the expression in question (e.g. use defn to make them (as shown above), and then use those as the cond/expr so you can match on it). The values in the mocking map can be literal values OR functions. If they are functions then they will be passed the env, which will include the special key :ncalls that will have the count (inclusive) of the number of times that expression has run since the test env was created.

8.2. Event Sends/Cancels

The sends and cancels will also be auto-recorded. See the docstrings in the testing namespace for more information.

8.3. Starting in a Specific Configuration

Most of your tests will need the chart to be in some particular state as part of your setup. You could get there by triggering a sequence of events while having the mocks in perfect condition, but this creates a fragile test where changes to the structure of the chart break a bunch of tests. The testing helpers include (testing/goto-configuration! env data-ops config) that allows you to set up the data model and configuration.

The data-ops is a vector of Data Model operations (e.g. ops/assign) to run on the data model. and config is a valid configuration (set of active states) for the chart. Unfortunately, the configuration of a state chart is non-trivial (it must include all active states in a complex hierarchy) and will change when you refactor the chart. So, another helper testing/configuration-for-states allows you to get a list of all of the states that would be active given the deepest desired leaf state(s).

In a chart with no parallel states, there will only ever be one leaf, but when parallel states are active you must list a valid leaf from each region.

Thus, a common test setup will look like this:

(defn config [] {:statechart some-statechart})

(specification "Starting in Some State"
  (let [env (testing/new-testing-env (config) {})]

    ;; assume a top-level parallel node, with two sub-regions. An internal call to `configuration-for-states`
    ;; will populate all of the necessary ancestor states from these leaves.
    (testing/goto-configuration! env [] #{:state.region1/leaf :state.region2/leaf})
    (testing/run-events! env :event/expired)

    ;; assertions
    ))

9. Visualization and Simulation

The com.fulcrologic.statecharts.visualization namespace provides tools for visualizing and interactively simulating statecharts. The visualizer renders your chart as a UML-style state diagram and, when connected to a running application, lets you observe live session state in real time.

There are two main components:

  • Simulator — A pure CLJ/CLJS API for stepping through a statechart interactively at the REPL or in a browser UI, using the real processor but with a mock execution model.

  • Visualization Server — A standalone Ring server (or embeddable Pathom resolvers) that exposes chart definitions and live session state to the browser visualizer.

9.1. The Simulator API

The simulator (com.fulcrologic.statecharts.visualization.simulator) runs your chart using the real processor but with a custom execution model: guard predicates become user-toggleable booleans, and all other executable content (scripts, assigns, sends) is a noop. This lets you step through the chart’s control flow without any real side-effects.

Key functions:

  • start-simulation! — Registers the chart, starts a session, and returns a simulator state map.

  • send-event! — Sends a named event through the processor and returns the new active configuration.

  • toggle-guard! — Flips a guard predicate’s boolean value in the simulator’s guard atom.

  • reset-simulation! — Restarts from the initial configuration.

  • extract-guards — Returns all guard fns found in the chart, keyed by function reference.

  • available-events — Returns the set of event keywords reachable from the current configuration.

(require '[com.fulcrologic.statecharts.visualization.simulator :as sim])

;; Start a simulation — returns a simulator state map
(def s (sim/start-simulation! my-chart))

;; Check which states are active
(sim/current-configuration s)
;; => #{:idle}

;; Send an event
(sim/send-event! s :submit)
;; => #{:validating}

;; Toggle a guard off (guards default to true)
(sim/toggle-guard! s valid-form? false)

;; Send the event again — a different path is taken
(sim/send-event! s :submit)
;; => #{:error}

;; Reset to the beginning
(sim/reset-simulation! s)
;; => #{:idle}

The simulator state map returned by start-simulation! contains:

  • :env — the full statechart environment (registry, data model, event queue, etc.)

  • :session-id — the unique session identifier

  • :chart — the statechart definition

  • :chart-key — the registry key used to register the chart

  • :guard-values — an atom mapping guard fn references to their current boolean values

9.2. Diagram Labels

By default the visualizer uses element IDs and transition event names as labels. You can override these with two metadata keys on your chart elements:

  • :diagram/label on a script element — displayed in the state’s entry/exit activity compartment

  • :diagram/condition on a transition — used as the guard label on the transition arrow

(require '[com.fulcrologic.statecharts.elements :refer [state script on-entry on-exit transition final]]
         '[com.fulcrologic.statecharts.chart :refer [statechart]]
         '[com.fulcrologic.statecharts.convenience :refer [on]])

(defn valid-form? [_ _] true)
(defn has-errors? [_ _] false)

(def my-chart
  (statechart {:initial :idle}
    (state {:id :idle}
      (on-entry {}
        (script {:expr (fn [_ _] nil) :diagram/label "reset-form"}))
      (on :submit :validating))

    (state {:id :processing}
      (on-entry {}
        (script {:expr (fn [_ _] nil) :diagram/label "load-data"})
        (script {:expr (fn [_ _] nil) :diagram/label "start-spinner"}))
      (on-exit {}
        (script {:expr (fn [_ _] nil) :diagram/label "stop-spinner"}))
      (transition {:event :success :target :done
                   :diagram/condition "all-ok?"}))

    (final {:id :done})))

When this chart is rendered, the :processing state shows load-data and start-spinner as entry activities, stop-spinner as an exit activity, and the transition to :done displays [all-ok?] as its guard label.

9.3. Standalone Visualization Server

The easiest way to visualize a chart is to run the standalone server. It serves the browser UI and exposes the Pathom API in one step.

The server supports three modes:

  1. Static mode — renders a chart definition passed on the command line; no live session data.

  2. Connected/REPL mode — connects to a running nREPL server and pulls chart definitions and session state from your live application.

  3. Proxy mode — forwards Pathom queries to a remote server that already has the resolvers installed.

A typical deps.edn alias for the standalone server:

:viz {:extra-deps {com.fulcrologic/statecharts-visualizer {:mvn/version "LATEST"}}
      :main-opts  ["-m" "com.fulcrologic.statecharts.visualization.standalone"]}

Then run it:

# Static mode — point at a namespace-qualified var that holds your chart
clojure -M:viz --chart my.app/my-chart

# Connected mode — connect to a running nREPL on port 7000
clojure -M:viz --nrepl-port 7000

# Proxy mode — forward Pathom queries to an existing server
clojure -M:viz --proxy-url http://localhost:3000/api

The browser UI will open (or print its URL) once the server is ready.

9.4. Embedding in Your Own Server

If you already have a Ring + Pathom server you can add the visualization resolvers directly, giving the browser UI access to your live chart registry and working memory store.

(require '[com.fulcrologic.statecharts.visualization.server.resolvers :as viz-resolvers]
         '[com.wsscode.pathom.connect :as pc]
         '[com.wsscode.pathom.core :as p])

(def pathom-parser
  (p/parser
    {::p/env     {::p/reader               [p/map-reader
                                            pc/reader2
                                            pc/open-ident-reader]
                  ;; Inject your registry and working memory store
                  ::sc/statechart-registry  my-registry
                  ::sc/working-memory-store my-wmem-store
                  ::sc/processor            my-processor}
     ::p/mutate  pc/mutate
     ::p/plugins [(pc/connect-plugin
                    {::pc/register viz-resolvers/resolvers})
                  p/error-handler-plugin]}))

The four resolvers in viz-resolvers/resolvers cover:

  • registered-charts-resolver — lists all charts in the registry (::sc/all-charts)

  • chart-definition-resolver — returns a chart’s full element map (functions replaced with :fn)

  • session-state-resolver — returns ::sc/configuration and ::sc/working-memory for a session

  • search-for-sessions-resolver — delegates to the search-for-sessions multimethod

9.5. Live Session Monitoring

When the server has a working memory store available, the browser UI can display which states are currently active in any running session. The search-for-sessions multimethod lets you plug in your own session-discovery logic.

(require '[com.fulcrologic.statecharts.visualization.server.resolvers :as viz-resolvers])

;; Implement the multimethod for each chart you want to make discoverable.
;; The dispatch value is the chart's registry key.
(defmethod viz-resolvers/search-for-sessions :my.app/auth-chart
  [env chart-registry-key search-string]
  ;; Return a vector of session descriptor maps.
  ;; Filter by `search-string` however makes sense for your application.
  [{::sc/session-id "session-abc-123"
    :session/label  "user@example.com"}
   {::sc/session-id "session-def-456"
    :session/label  "admin@example.com"}])

The search-string argument comes from the browser’s session search box. You can filter by user name, session ID prefix, or any application-specific criterion. The default implementation logs a warning and returns an empty vector.

9.6. POST API for External Tools

The resolvers expose a send-event Pathom mutation that lets external tools trigger state transitions without a UI. This is useful for scripted testing or integration from non-Clojure environments.

# Send an event to a running session via curl (Transit+JSON)
curl -X POST http://localhost:8080/api \
  -H 'Content-Type: application/transit+json' \
  -d '[(com.fulcrologic.statecharts/session-id "my-session-uuid") \
       {:com.fulcrologic.statecharts/session-id "my-session-uuid" \
        :event {:name :submit}}]'

From a Babashka script you can use babashka.http-client:

#!/usr/bin/env bb
(require '[babashka.http-client :as http])

(defn send-sc-event! [url session-id event-name]
  (http/post url
    {:headers {"Content-Type" "application/json"}
     :body    (str "[{\"com.fulcrologic.statecharts/session-id\" \""
                   session-id
                   "\", \"event\" {\"name\" \""
                   (name event-name)
                   "\"}}]")}))

(send-sc-event! "http://localhost:8080/api" "my-session-uuid" :submit)
Note
The send-event mutation requires the Pathom environment to have ::sc/working-memory-store and ::sc/processor available. Static-mode standalone servers do not support this mutation.

10. Relationship to SCXML

This library’s internal implementation follows (as closely as possible) the official State Chart XML Algorithm. In fact, much of the implementation uses internal volatiles in order to match the imperative style of that doc for easier comparison and avoidance of bugs.

The actual structure of the live CLJC data used to represent charts also closely mimics the structure described there, but with some differences for convenient use in CLJC.

Specifically, executable content is still treated as data. The flow control XML nodes from the standard (if, elseif, else, foreach) have native Clojure function equivalents (see Flow Control Elements). Some other XML nodes are abbreviated or handled differently, since a conformant XML reader (which would need to be aware of the target execution model) can easily translate such nodes into the target data representation (even if that target representation is script strings).

Some of the data model elements are also abbreviated in a similar manner. See the docstrings for details.

Thus, if you are trying to read SCXML documents you will need to write (or find) an XML reader that can do this interpretation.

For example, an XML reader that targets sci (the Clojure interpreter) might convert the XML (where a and do-something are implied values in the data and excution model):

<if cond="(= 1 a)">
  (let [b (inc a)]
    (do-something b))
</if>

into (scope and args still determined by the execution model selected):

;; String-based interpretation
(script {:expr
  "(if (= 1 a)
     (let [b (inc a)]
       (do-something b)))"})

;; OR eval-based
(script {:expr
  '(if (= 1 a)
     (let [b (inc a)]
       (do-something b)))})

;; OR functional
(script {:expr (fn [env {:keys [a]}]
                  (if (= 1 a)
                    (let [b (inc a)]
                      (do-something b))))})

If you’re using XML tools to generate your charts, though, it’s probably easiest to use script tags to begin with.

The primary alternative to this library is clj-statecharts, which is a fine library modelled after xstate.

This library exists for the following reasons:

  • At the time this library was created, clj-statecharts was missing features. In particular history nodes, which we needed. I looked at clj-statecharts in order to try to add history, but some of the internal decisions made it more difficult to add (with correct semantics) and the Eclipse license made it less appealing for internal customization as a base in commercial software (see https://www.juxt.pro/blog/prefer-mit).

  • To create an SCXML-like implementation that uses the algorithm defined in the W3C Recommended document, and can (grow to) run (with minor transformations) SCXML docs that are targeted to Clojure with the semantics defined there (such as they are).

  • To define more refined abstract mechanisms such that the state charts can be associated to long-lived things (such as a monetary transaction that happens over time) and be customized to interface with things like durable queues for events (e.g. AWS SQS) and reliable timers.

  • MIT licensing instead of Eclipse.

Other related libraries and implementations:

  • XState : Javascript. Could be used from CLJS.

  • Apache SCXML : Stateful and imperative. Requires writing classes. Requires you use XML.

  • Fulcro UI State Machines : A finite state machine namespace (part of Fulcro) that is tightly coupled to Fulcro’s needs (full stack operation in the context of Fulcro UI and I/O).

10.2. Conformance

This library was written using the reference implementation described in the SCXML standard, but without the requirement that the chart be written in XML.

Any deviation from the standard (as far as general operation of state transitions, order of execution of entry/exit, etc.) should be considered a bug. Note that it is possible for a bugfix in this library to change the behavior of your code (if you wrote it in a way that depends on the misbehavior); therefore, even though this library does not intend to make breaking changes, it is possible that a bugfix could affect your code’s operation.

If future versions of the standard are released that cause incompatible changes, then this library will add a new namespace for that new standard (not break versioning).