Statecharts as actors

Control flow you can test.

Write your program's lifecycles as statecharts: orders, connections, retries, even your test users. A statechart is formal, so you can simulate it on a fake clock, check invariants after every run, and search for the run that breaks them. tinyactors runs statecharts as actors, from a handful to millions, inside Node.js, Bun, Python, the browser or C.

Node.js and Bun
npm install @tinyactors/node
Python
pip install tinyactors
Browsers
npm install @tinyactors/wasm

Get startedBuild a team chat

The problem

Control flow hides in flags and timers.

Much of a program is a lifecycle. An order is open, then paying, then paid or timed out. A connection is dialing, up, or backing off. Written as flags, callbacks and timers, a lifecycle spreads over a codebase, and the states it can be in are written down nowhere.

A statechart writes them down: the states, the events that move between them, and what happens on the way. This payment asks a service to charge a card, retries twice when no answer comes within 30 seconds, and then gives up.

payment.scxmlscxml
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="payment" initial="charging">
  <datamodel><data id="attempts" expr="0"/></datamodel>
  <state id="charging">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="urn:payments" event="charge" target="card"/>
      <send event="timeout" delay="30s" id="timer"/>
    </onentry>
    <transition event="charged" target="paid"><cancel sendid="timer"/></transition>
    <transition event="timeout" cond="attempts &lt; 3" target="charging"/>
    <transition event="timeout" target="failed"/>
  </state>
  <final id="paid"><donedata><param name="outcome" expr="'paid'"/></donedata></final>
  <final id="failed"><donedata><param name="outcome" expr="'failed'"/></donedata></final>
</scxml>

Simulate

A thousand runs, no waiting.

The chart talks to the world only through events, so a test can play the world. A SimulatedClock moves only when the test moves it, so a 30-second timeout costs nothing, and a seeded generator decides when the payment service answers and when it stays silent. This program runs a thousand seeds and checks two invariants in each.

simulate.mjsjavascript
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'payment.scxml', text: readFileSync('payment.scxml', 'utf8') }]);

for (let seed = 1; seed <= 1000; seed++) {
  const random = mulberry32(seed);
  const clock = new SimulatedClock();
  const charges = [];
  let outcome;
  const host = new Host(compiled, {
    system: 'simulation',
    clock,
    ioProcessors: {
      'urn:payments': {
        receive(send) {
          charges.push(clock.now);
          if (random() < 0.4) send.answer('charged'); // the service answers, or it never does
        },
      },
    },
    onDone: (actor, donedata) => { outcome = donedata.outcome; },
  });
  host.spawn('payment');
  await host.idle();
  while (outcome === undefined) {
    clock.increment(host.nextDeadline); // jump to the next timeout: no waiting
    await host.idle();
  }
  assert.ok(charges.length <= 3, `seed ${seed}: charged ${charges.length} times`);
  assert.ok(outcome === 'paid' || charges.length === 3, `seed ${seed}: gave up early`);
  host.close();
}
console.log('1000 seeds: never more than three charges, never giving up early');

function mulberry32(seed) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
output
1000 seeds: never more than three charges, never giving up early

Change attempts < 3 to attempts < 4 and seed 10 fails: charged 4 times. The seed reproduces the run that found it.

Why it works

Formal enough to check.

The semantics are a W3C standard.

Charts are written in SCXML, and the core passes all 191 automatic tests of the W3C's SCXML test suite. What a chart does is defined, not whatever the runtime happens to do.

Sourcetinyactors-core, docs/architecture.md

Logic in charts, I/O in your handlers.

The host does no I/O of its own. Everything an actor sends out goes to a handler you give it, which does the I/O and answers with an event. The same chart runs against the network in production and against a simulation in a test.

SourceTesting your charts

Every transition is a fact you can assert on.

Each step an actor takes is an OpenTelemetry span: the event it took, the transitions that fired, the states it left and entered. A test can wait for an actor to reach a state, and a dashboard can show why it did.

SourceTelemetry

One actor per thing, even for millions of things.

With a store and a bound on resident actors, idle actors are hibernated and woken by their next event. A benchmark runs two million actors with a thousand in memory and checks every actor's count after 200,000 events.

Sourcetinyactors for Python, Performance

Build

A team chat in five steps.

Workspaces, rooms and people who come and go: a team chat is a system of lifecycles, and each one is a chart. The tutorial builds it one idea at a time, and every step is a program you can run.

  1. A roomOne actor, events from your program, an I/O processor for the screens.
  2. PresenceAn actor per person: offline, active or away, with a timer that costs nothing in a test.
  3. The workspaceA collection actor that decides which rooms exist and alone makes them.
  4. The rosterEveryone online sees who else is, and each change as it happens.
  5. HibernationA thousand users with fifty in memory, the rest in a store.

Build a team chat

Run it

The same charts, in production.

A host runs your actors on your program's event loop and gives the operator what a long-lived system needs.

  • HibernationActors past a resident bound go to your store and come back on their next event.
  • MigrationAdd a new version of a chart, and running actors move to it while events keep coming.
  • SnapshotsThe whole host as one blob, restored with its clock, its timers and its actors.
  • TelemetryTraces, logs and metrics as OpenTelemetry, with a trace that follows an event across actors and systems.

Where it runs

One core, every runtime.

  • Node.js and Bun@tinyactors/node: Node.js 22.3 or later and Bun, on macOS and Linux. Charts in JavaScript, or in the QuickJS sandbox for charts you do not trust.
  • Pythontinyactors: CPython 3.13 or later. Charts in Python, synchronous or under asyncio.
  • Browsers@tinyactors/wasm: the same API as WebAssembly, for browsers and for platforms with no native addon.
  • CThe core embeds anywhere: no C library, no I/O, no threads, and memory only from an allocator you give it.