<!-- https://tinyactors.dev/compare/xstate/ -->
# tinyactors compared with XState

Kind: pitch. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).

> Where a statechart runs, what format it is written in, what keeps a population of actors, how a running actor takes new logic, and when XState is the better choice.

XState gives you a machine and an actor in JavaScript, and leaves storing them to your code. tinyactors runs W3C SCXML charts as actors that hibernate, move to new versions and snapshot, in Node.js, Python, C and browsers. Choose XState for state in a JavaScript user interface.

[Upgrade running sessions](https://tinyactors.dev/compare/xstate/index.md#changes) · [See when XState fits](https://tinyactors.dev/compare/xstate/index.md#choose-xstate)

<a id="format"></a>

## XState machines are JavaScript; SCXML is a standard

Both describe behavior as states, events and transitions, so a reviewer, a test or an agent can read the whole flow. The difference is the material.

- **XState machines are JavaScript objects**: Stately calls XState a state management and orchestration solution for JavaScript and TypeScript apps. A machine is made with `createMachine`. XState v6, in beta, reads SCXML through an experimental `@xstate/scxml`. Its tests are "regression coverage, not a claim of full SCXML conformance". Source: [Stately, "XState"](https://stately.ai/docs/xstate) · [Stately, "Actors"](https://stately.ai/docs/actors) · [Stately, "SCXML" (XState v6)](https://stately.ai/docs/xstate/v6/scxml)
- **tinyactors runs SCXML documents themselves**: Each chart is a W3C SCXML document, and the C core passes all 191 automatic tests of the W3C conformance suite. Every package runs the same suite. The core decides what each state and transition does. A chart's ECMAScript runs in your own engine in Node.js, Bun and browsers, or in the bundled QuickJS sandbox; Python and C run it in QuickJS. Source: [Memory, capacity and performance, "Correct by the standard"](https://tinyactors.dev/performance/index.md#correctness) · [W3C, "State Chart XML (SCXML)"](https://www.w3.org/TR/scxml/) · [@tinyactors/node, "Before you use it"](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-napi/README.md#before-you-use-it) · [tinyactors for Python, README](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-cpython/README.md)

A document is data, so tools other than your program read it. The [command line](https://tinyactors.dev/cli/index.md) checks, lints and diffs a chart in CI, and draws it.

<a id="where-it-runs"></a>

## One chart in four languages

XState runs, in Stately's words, "in the frontend, backend, or wherever JavaScript runs" ([Stately, "XState"](https://stately.ai/docs/xstate)). tinyactors runs one C core behind each package.

This order retries a failed charge on its own. The same `order.scxml` runs in Node.js, a browser, Python and C, and each prints the same lines:

Node.js and Bun:

```javascript title="main.mjs"
import { readFileSync } from 'node:fs';
import { compileCharts, Host } from '@tinyactors/node';

let charges = 0;
const payments = {
  receive(send) {                   // the chart's <send type="payments">
    console.log('charge', JSON.stringify(send.data));
    if (++charges === 1) send.fail(); // down for the first charge: the order gets error.communication
    else send.answer('charged');    // an event back to the order
  },
};
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);
const host = new Host(compiled, {
  system: 'shop',
  ioProcessors: { payments },
  log: (entry) => console.log('log', entry.text),
});
compiled.close();

const order = host.spawn('order');
order.send('add', { item: 'notebook', price: 30 });
order.send('add', { item: 'pen', price: 12 });
order.send('checkout');
console.log('paid', await order.done); // the order retried on its own
host.close();
```

```scxml title="order.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="cart">
  <datamodel>
    <data id="lines" expr="[]"/>
    <data id="total" expr="0"/>
    <data id="attempts" expr="0"/>
    <data id="problem" expr="null"/>
  </datamodel>

  <!-- The customer fills the cart: each add is a line with its item and price.
       Checkout needs at least one line. -->
  <state id="cart">
    <transition event="add">
      <assign location="lines" expr="lines.concat([{item: _event.data.item, price: _event.data.price}])"/>
      <assign location="total" expr="total + _event.data.price"/>
    </transition>
    <transition event="checkout" cond="lines.length &gt; 0" target="paying">
      <assign location="attempts" expr="0"/>
      <assign location="problem" expr="null"/>
    </transition>
  </state>

  <!-- The order asks the payment service to charge the total, and waits.
       A declined card sends it back to the cart; a service that cannot be
       reached is tried again, three times in all. -->
  <state id="paying">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="payments" event="charge">
        <param name="amount" expr="total"/>
        <param name="items" expr="lines.map((line) => line.item)"/>
      </send>
    </onentry>
    <transition event="charged" target="paid"/>
    <transition event="declined" target="cart">
      <assign location="problem" expr="_event.data.reason"/>
    </transition>
    <transition event="error.communication" cond="attempts &lt; 3" target="retrying"/>
    <transition event="error.communication" target="cart">
      <assign location="problem" expr="'the payment service could not be reached'"/>
    </transition>
  </state>

  <!-- The payment service could not be reached: the order waits a second,
       then charges again, on its own. -->
  <state id="retrying">
    <onentry>
      <log label="order" expr="'payment service unreachable, attempt ' + attempts + ': retrying in 1 s'"/>
      <send event="retry" delay="1s"/>
    </onentry>
    <transition event="retry" target="paying"/>
  </state>

  <!-- The order is paid: its total is what it hands back as it ends. -->
  <final id="paid">
    <donedata><content expr="total"/></donedata>
  </final>
</scxml>
```

Browsers:

```javascript title="browser.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';

let charges = 0;
const payments = {
  receive(send) {                   // the chart's <send type="payments">
    console.log('charge', JSON.stringify(send.data));
    if (++charges === 1) send.fail(); // down for the first charge: the order gets error.communication
    else send.answer('charged');    // an event back to the order
  },
};
const chart = await fetch(new URL('order.scxml', import.meta.url)).then((response) => response.text());
const compiled = compileCharts([{ name: 'order.scxml', text: chart }]);
const host = new Host(compiled, {
  system: 'shop',
  ioProcessors: { payments },
  log: (entry) => console.log('log', entry.text),
});
compiled.close();

const order = host.spawn('order');
order.send('add', { item: 'notebook', price: 30 });
order.send('add', { item: 'pen', price: 12 });
order.send('checkout');
console.log('paid', await order.done); // the order retried on its own
host.close();
```

```scxml title="order.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="cart">
  <datamodel>
    <data id="lines" expr="[]"/>
    <data id="total" expr="0"/>
    <data id="attempts" expr="0"/>
    <data id="problem" expr="null"/>
  </datamodel>

  <!-- The customer fills the cart: each add is a line with its item and price.
       Checkout needs at least one line. -->
  <state id="cart">
    <transition event="add">
      <assign location="lines" expr="lines.concat([{item: _event.data.item, price: _event.data.price}])"/>
      <assign location="total" expr="total + _event.data.price"/>
    </transition>
    <transition event="checkout" cond="lines.length &gt; 0" target="paying">
      <assign location="attempts" expr="0"/>
      <assign location="problem" expr="null"/>
    </transition>
  </state>

  <!-- The order asks the payment service to charge the total, and waits.
       A declined card sends it back to the cart; a service that cannot be
       reached is tried again, three times in all. -->
  <state id="paying">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="payments" event="charge">
        <param name="amount" expr="total"/>
        <param name="items" expr="lines.map((line) => line.item)"/>
      </send>
    </onentry>
    <transition event="charged" target="paid"/>
    <transition event="declined" target="cart">
      <assign location="problem" expr="_event.data.reason"/>
    </transition>
    <transition event="error.communication" cond="attempts &lt; 3" target="retrying"/>
    <transition event="error.communication" target="cart">
      <assign location="problem" expr="'the payment service could not be reached'"/>
    </transition>
  </state>

  <!-- The payment service could not be reached: the order waits a second,
       then charges again, on its own. -->
  <state id="retrying">
    <onentry>
      <log label="order" expr="'payment service unreachable, attempt ' + attempts + ': retrying in 1 s'"/>
      <send event="retry" delay="1s"/>
    </onentry>
    <transition event="retry" target="paying"/>
  </state>

  <!-- The order is paid: its total is what it hands back as it ends. -->
  <final id="paid">
    <donedata><content expr="total"/></donedata>
  </final>
</scxml>
```

Python:

```python title="main.py"
import asyncio
import json

import tinyactors


class Payments:
    charges = 0

    def receive(self, send):        # the chart's <send type="payments">
        print("charge", json.dumps(send.data, separators=(",", ":")))
        self.charges += 1
        if self.charges == 1:
            send.fail()             # down for the first charge: the order gets error.communication
        else:
            send.answer("charged")  # an event back to the order


async def main():
    with open("order.scxml") as file:
        chart = file.read()
    with tinyactors.compile_charts([("order.scxml", chart)]) as compiled:
        host = tinyactors.Host(compiled, system="shop",
                               io_processors={"payments": Payments()},
                               log=lambda entry: print("log", entry.text))
    async with host:
        order = host.spawn("order")
        order.send("add", {"item": "notebook", "price": 30})
        order.send("add", {"item": "pen", "price": 12})
        order.send("checkout")
        print("paid", await order.done)  # the order retried on its own


asyncio.run(main())
```

```scxml title="order.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="cart">
  <datamodel>
    <data id="lines" expr="[]"/>
    <data id="total" expr="0"/>
    <data id="attempts" expr="0"/>
    <data id="problem" expr="null"/>
  </datamodel>

  <!-- The customer fills the cart: each add is a line with its item and price.
       Checkout needs at least one line. -->
  <state id="cart">
    <transition event="add">
      <assign location="lines" expr="lines.concat([{item: _event.data.item, price: _event.data.price}])"/>
      <assign location="total" expr="total + _event.data.price"/>
    </transition>
    <transition event="checkout" cond="lines.length &gt; 0" target="paying">
      <assign location="attempts" expr="0"/>
      <assign location="problem" expr="null"/>
    </transition>
  </state>

  <!-- The order asks the payment service to charge the total, and waits.
       A declined card sends it back to the cart; a service that cannot be
       reached is tried again, three times in all. -->
  <state id="paying">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="payments" event="charge">
        <param name="amount" expr="total"/>
        <param name="items" expr="lines.map((line) => line.item)"/>
      </send>
    </onentry>
    <transition event="charged" target="paid"/>
    <transition event="declined" target="cart">
      <assign location="problem" expr="_event.data.reason"/>
    </transition>
    <transition event="error.communication" cond="attempts &lt; 3" target="retrying"/>
    <transition event="error.communication" target="cart">
      <assign location="problem" expr="'the payment service could not be reached'"/>
    </transition>
  </state>

  <!-- The payment service could not be reached: the order waits a second,
       then charges again, on its own. -->
  <state id="retrying">
    <onentry>
      <log label="order" expr="'payment service unreachable, attempt ' + attempts + ': retrying in 1 s'"/>
      <send event="retry" delay="1s"/>
    </onentry>
    <transition event="retry" target="paying"/>
  </state>

  <!-- The order is paid: its total is what it hands back as it ends. -->
  <final id="paid">
    <donedata><content expr="total"/></donedata>
  </final>
</scxml>
```

C:

```c title="main.c"
/* cc main.c host.c -ltinyactors_datamodel_ecmascript -ltinyactors_runtime -ltinyactors -lm */
#include <stdio.h>
#include "host.h"

typedef struct payments {
    int charges;
} payments;

/* What the order sends out, and how this program answers. */
static void handle(host *h, uint32_t effect) {
    payments *service = h->application;
    switch (ta_host_effect_number(h->host, effect, TA_EFFECT_FIELD_KIND)) {
    case TA_EFFECT_SEND: /* the chart's <send type="payments"> */
        host_print(h, "charge", effect);
        if (++service->charges == 1) host_fail(h, effect); /* down: the order gets error.communication */
        else host_answer(h, effect, "charged"); /* an event back to the order */
        break;
    case TA_EFFECT_LOG: { /* the chart's <log> */
        ta_string_view text = ta_host_effect_text(h->host, effect, TA_EFFECT_FIELD_EVENT);
        printf("log %.*s\n", (int)text.length, text.pointer);
        break;
    }
    case TA_EFFECT_DONE: /* the order reached <final id="paid">: its total */
        host_print(h, "paid", effect);
        break;
    default:
        break;
    }
}

int main(void) {
    payments service = {0};
    host h = {.application = &service};
    if (host_open(&h, &(host_options){"order.scxml", "shop", "payments"}) != TA_OK) return 1;
    uint64_t order = host_spawn(&h, "order");
    host_send(&h, (host_event){order, "add", "({item: 'notebook', price: 30})"});
    host_send(&h, (host_event){order, "add", "({item: 'pen', price: 12})"});
    host_send(&h, (host_event){order, "checkout", NULL});
    host_run(&h, handle); /* until the order is paid: it retries on its own */
    host_close(&h);
    return 0;
}
```

```c title="host.h"
/* A host for one chart, its loop and its payloads: what main.c uses. */
#ifndef HOST_H
#define HOST_H

#include <tinyactors.h>
#include <tinyactors_datamodel_ecmascript.h>
#include <tinyactors_runtime.h>

typedef struct host {
    ta_host *host;
    ta_datamodel_ecmascript *ecmascript;
    ta_datamodel_binding datamodel;
    void *application; /* the program's own state, for its handler */
} host;

typedef struct host_options {
    const char *chart;        /* the chart's file */
    const char *system;       /* the system id */
    const char *io_processor; /* the one I/O processor type the chart sends to */
} host_options;

/* An event: its data an ECMAScript expression, or NULL for none. */
typedef struct host_event {
    uint64_t session;
    const char *name;
    const char *data;
} host_event;

/* Called for each effect of a batch, before the batch is acknowledged. */
typedef void host_handler(host *h, uint32_t effect);

ta_status host_open(host *h, const host_options *options);
uint64_t host_spawn(host *h, const char *chart);
ta_status host_send(host *h, host_event event);
/* Runs until nothing is left to do, timers included, handing each effect to `handle`. */
void host_run(host *h, host_handler *handle);
/* Answers the send `effect` with the event `name`, as its I/O processor. */
ta_status host_answer(host *h, uint32_t effect, const char *name);
/* Fails the send `effect`: its sender gets error.communication. */
ta_status host_fail(host *h, uint32_t effect);
/* Prints `label` and the effect's payload as JSON. */
void host_print(host *h, const char *label, uint32_t effect);
void host_close(host *h);

#endif
```

```c title="host.c"
#define _POSIX_C_SOURCE 200809L /* nanosleep */
#include "host.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* The config, as CBOR: {"systemID": system, "ioProcessors": [{"type": io_processor}]} */
static ta_status open_host(host *h, const host_options *options, ta_allocator *allocator) {
    unsigned char room[128];
    ta_cbor_writer writer;
    ta_cbor_writer_init(&writer, (ta_buffer){room, sizeof room, 0}, allocator);
    ta_cbor_write_map(&writer, 2);
    ta_cbor_write_text(&writer, ta_string("systemID"));
    ta_cbor_write_text(&writer, ta_string(options->system));
    ta_cbor_write_text(&writer, ta_string("ioProcessors"));
    ta_cbor_write_array(&writer, 1);
    ta_cbor_write_map(&writer, 1);
    ta_cbor_write_text(&writer, ta_string("type"));
    ta_cbor_write_text(&writer, ta_string(options->io_processor));
    ta_bytes config;
    ta_status status = ta_cbor_writer_bytes(&writer, &config);
    ta_host_environment environment = {.size = sizeof environment, .datamodel_count = 1,
                                       .datamodels = &h->datamodel, .allocator = *allocator};
    if (status == TA_OK) status = ta_host_create(config, &environment, &h->host);
    ta_cbor_writer_free(&writer); /* read during the call */
    return status;
}

/* The chart's file, compiled into an image the host copies. */
static ta_status add_chart(host *h, const char *path, ta_allocator allocator) {
    ta_bytes text;
    ta_status status = ta_runtime_load_file(path, &text);
    if (status != TA_OK) return status;
    ta_compile_options options = {.size = sizeof options, .alloc = allocator};
    ta_source source = {ta_string(path), {(const char *)text.pointer, (uint32_t)text.length}};
    ta_compile_result *compiled = NULL;
    status = ta_compile_charts(&options, (ta_source_list){&source, 1}, &compiled);
    if (status == TA_OK) {
        ta_string_view image = ta_compile_image(compiled);
        uint32_t segment = 0;
        status = ta_host_add_image(h->host, (ta_bytes){(const unsigned char *)image.pointer, image.length}, &segment);
    }
    ta_compile_free(compiled);
    ta_runtime_free_file(text);
    return status;
}

ta_status host_open(host *h, const host_options *options) {
    ta_allocator allocator = ta_runtime_malloc();
    h->ecmascript = ta_datamodel_ecmascript_new(NULL);
    h->datamodel = ta_datamodel_ecmascript_binding(h->ecmascript);
    ta_status status = open_host(h, options, &allocator);
    return status == TA_OK ? add_chart(h, options->chart, allocator) : status;
}

uint64_t host_spawn(host *h, const char *chart) {
    ta_host_chart_ref ref;
    if (ta_host_chart(h->host, ta_string(chart), &ref) != TA_OK) return 0;
    ta_spawn spawn = {.segment = ref.segment, .chart = ref.chart};
    uint64_t session = 0;
    return ta_host_spawn(h->host, &spawn, &session) == TA_OK ? session : 0;
}

ta_status host_send(host *h, host_event e) {
    ta_event_in event = {.size = sizeof event, .session = e.session, .name = ta_string(e.name)};
    if (e.data) event.data = ta_datamodel_ecmascript_payload_eval(h->ecmascript, 0, ta_string(e.data));
    ta_status status = ta_host_send(h->host, &event);
    if (status != TA_OK && event.data) /* a refused event's data is still ours */
        h->datamodel.vtable->release(h->datamodel.datamodel, event.data);
    return status;
}

/* Every effect handed out, each batch acknowledged after its handler saw it. */
static void drain(host *h, host_handler *handle) {
    const ta_host_effect *effects;
    uint32_t count;
    while ((count = ta_host_effects(h->host, &effects)) > 0) {
        for (uint32_t i = 0; i < count; i++) handle(h, i);
        ta_host_effects_ack(h->host); /* what the batch handed out ends here */
    }
}

/* Sleeps until the host's clock, in nanoseconds (ta_runtime_now_ns), reads `deadline`. */
static void sleep_until(ta_time deadline) {
    ta_time now = ta_runtime_now_ns();
    if (deadline <= now) return;
    ta_time wait = deadline - now;
    struct timespec duration = {(time_t)(wait / 1000000000u), (long)(wait % 1000000000u)};
    nanosleep(&duration, NULL);
}

void host_run(host *h, host_handler *handle) {
    for (;;) {
        drain(h, handle);
        ta_host_advance_time(h->host, (ta_system_time){ta_runtime_now_ns(), 0}); /* timers fire as it passes */
        ta_run run = ta_host_run(h->host, 10000);
        drain(h, handle);
        if (run.status == TA_RUN_FAULT) return;
        if (run.status != TA_RUN_IDLE) continue; /* more to run now */
        if (run.next_deadline == UINT64_MAX) return; /* nothing left, not even a timer */
        sleep_until(run.next_deadline); /* a program with an event loop arms a timer instead */
    }
}

ta_status host_answer(host *h, uint32_t effect, const char *name) {
    ta_event_in event = {.size = sizeof event, .name = ta_string(name)};
    event.session = ta_host_effect_number(h->host, effect, TA_EFFECT_FIELD_SESSION);
    event.sendid = ta_host_effect_text(h->host, effect, TA_EFFECT_FIELD_SENDID);
    return ta_host_send(h->host, &event);
}

ta_status host_fail(host *h, uint32_t effect) {
    ta_event_in event = {.size = sizeof event, .flags = TA_EVENT_IN_ERROR_COMMUNICATION};
    event.session = ta_host_effect_number(h->host, effect, TA_EFFECT_FIELD_SESSION);
    event.sendid = ta_host_effect_text(h->host, effect, TA_EFFECT_FIELD_SENDID);
    return ta_host_send(h->host, &event);
}

void host_print(host *h, const char *label, uint32_t effect) {
    ta_payload payload = ta_host_effect_number(h->host, effect, TA_EFFECT_FIELD_PAYLOAD);
    ta_bytes cbor;
    if (ta_datamodel_ecmascript_payload_to_cbor(h->ecmascript, payload, &cbor) != TA_OK) return;
    char room[256];
    ta_buffer json = {room, sizeof room, 0};
    ta_status status = ta_cbor_diagnostic(cbor, &json); /* CBOR as text: JSON for these values */
    if (status == TA_ERROR_NO_MEMORY) { /* json.length is the room it needs */
        json = (ta_buffer){malloc(json.length), json.length, 0};
        status = json.pointer ? ta_cbor_diagnostic(cbor, &json) : TA_ERROR_NO_MEMORY;
    }
    if (status == TA_OK) printf("%s %.*s\n", label, (int)json.length, (const char *)json.pointer);
    if (json.pointer != room) free(json.pointer);
}

void host_close(host *h) {
    ta_host_free(h->host);
    ta_datamodel_ecmascript_free(h->ecmascript); /* after every host that uses it */
}
```

```scxml title="order.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="cart">
  <datamodel>
    <data id="lines" expr="[]"/>
    <data id="total" expr="0"/>
    <data id="attempts" expr="0"/>
    <data id="problem" expr="null"/>
  </datamodel>

  <!-- The customer fills the cart: each add is a line with its item and price.
       Checkout needs at least one line. -->
  <state id="cart">
    <transition event="add">
      <assign location="lines" expr="lines.concat([{item: _event.data.item, price: _event.data.price}])"/>
      <assign location="total" expr="total + _event.data.price"/>
    </transition>
    <transition event="checkout" cond="lines.length &gt; 0" target="paying">
      <assign location="attempts" expr="0"/>
      <assign location="problem" expr="null"/>
    </transition>
  </state>

  <!-- The order asks the payment service to charge the total, and waits.
       A declined card sends it back to the cart; a service that cannot be
       reached is tried again, three times in all. -->
  <state id="paying">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="payments" event="charge">
        <param name="amount" expr="total"/>
        <param name="items" expr="lines.map((line) => line.item)"/>
      </send>
    </onentry>
    <transition event="charged" target="paid"/>
    <transition event="declined" target="cart">
      <assign location="problem" expr="_event.data.reason"/>
    </transition>
    <transition event="error.communication" cond="attempts &lt; 3" target="retrying"/>
    <transition event="error.communication" target="cart">
      <assign location="problem" expr="'the payment service could not be reached'"/>
    </transition>
  </state>

  <!-- The payment service could not be reached: the order waits a second,
       then charges again, on its own. -->
  <state id="retrying">
    <onentry>
      <log label="order" expr="'payment service unreachable, attempt ' + attempts + ': retrying in 1 s'"/>
      <send event="retry" delay="1s"/>
    </onentry>
    <transition event="retry" target="paying"/>
  </state>

  <!-- The order is paid: its total is what it hands back as it ends. -->
  <final id="paid">
    <donedata><content expr="total"/></donedata>
  </final>
</scxml>
```

```text title="output"
charge {"amount":42,"items":["notebook","pen"]}
log payment service unreachable, attempt 1: retrying in 1 s
charge {"amount":42,"items":["notebook","pen"]}
paid 42
```

<a id="state"></a>

## XState persists one actor; the host, thousands

Ten thousand chat sessions, most of them idle, must survive until their users return. Something must pick which stay in memory.

- **XState hands you a snapshot to store**: `actor.getPersistedSnapshot()` returns an actor's state, with its children, and `createActor(logic, {snapshot})` restores it. Storing it is your application's work, in localStorage or a database, and it must be JSON-serializable. Source: [Stately, "Persistence"](https://stately.ai/docs/persistence)
- **The host hibernates the actors past a bound**: Give the host a store and a bound, and it writes the coldest actors into the store, then wakes each one at its next event. Two million actors ran with at most 1000 in memory. One snapshot of two million takes 165 MB. Source: [Hibernation, "Run two million actors with 1000 in memory"](https://tinyactors.dev/guides/hibernation/index.md#at-scale) · [Snapshots, "Copy a running application, and run the copy"](https://tinyactors.dev/guides/snapshots/index.md)

An actor in memory takes about 530 bytes of a Node.js process holding a million, measured with a counter chart of one variable ([Capacity and memory](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs)).

<a id="tests"></a>

## Both test the chart without the world

XState is stronger in one place. It generates test paths from a machine, where tinyactors leaves generated runs to your test.

- **XState mocks effects and generates paths**: Stately's docs say to mock a machine's effects, through `setup()`, to keep tests deterministic. `getShortestPaths` returns a path to every reachable state, and Stately Studio generates tests from them for Playwright and Vitest. Delays need no real time either: XState v6's testing guide passes a `SimulatedClock` to `createActor` and moves it with `clock.increment()`. Source: [Stately, "Testing"](https://stately.ai/docs/testing) · [Stately, "Graph and paths"](https://stately.ai/docs/graph) · [Stately, "Test XState logic" (XState v6)](https://stately.ai/docs/xstate/v6/testing)
- **A tinyactors chart's effects are events**: A chart reaches the world only through sends to objects you give the host, so a test gives it stand-ins. A simulated clock jumps to each timeout. Properties over generated runs are a pattern your test writes, not a library call. Source: [Testing, "Replace the chart's services and its clock"](https://tinyactors.dev/guides/testing-recipes/index.md#three-tools) · [Property testing](https://tinyactors.dev/property-testing/index.md)

<a id="crash"></a>

## A crash keeps what was written down

A process dies with sessions in flight. Neither library writes anything down on its own; the difference is how much your program has to write.

- **XState restores state, not the actions**: A restored actor does not run again the actions it already executed. For those, Stately's docs recommend event sourcing. Source: [Stately, "Persistence"](https://stately.ai/docs/persistence)
- **A crash keeps what your program saved**: Hibernated actors in your store and the last snapshot come back, with each actor's queued events and pending timers. Inputs after that snapshot return when your program journaled them: replaying a journal is one loop. Source: [When to use tinyactors, "A crash stops memory and keeps saved state"](https://tinyactors.dev/when-to-use/index.md#crash) · [Journal and replay](https://tinyactors.dev/guides/journal/index.md)

<a id="changes"></a>

## Ship new rules to running sessions

You add a turn limit while thousands of sessions are mid-conversation. Each one must keep the turns it already counted.

- **XState's restored state may not fit new logic**: Stately's docs warn that if the machine changes, a restored state may be incompatible with the new logic. Source: [Stately, "Persistence"](https://stately.ai/docs/persistence)
- **A migration moves running actors to a version**: `host.addImage()` adds the new chart to the running host, and `host.migrate()` moves actors to it. Each keeps its active states, queue and delayed sends. The new chart reads the old variables from one event. Source: [Migration, "Move the actors and carry their variables"](https://tinyactors.dev/guides/migration/index.md#moving-running-actors)

Ten thousand agent sessions answer three prompts each, with at most 100 in memory. Version 2 adds a limit of three turns, and one migration moves every session, hibernated ones included:

Node.js and Bun:

```javascript title="main.mjs"
import { readFileSync } from 'node:fs';
import { compileCharts, Host, MemoryStore } from '@tinyactors/node';

const image = (file) => {
  const compiled = compileCharts([{ name: file, text: readFileSync(file, 'utf8') }]);
  const bytes = compiled.image;
  compiled.close();
  return bytes;
};

let completions = 0;
const model = { receive(send) { completions++; send.answer('reply'); } }; // a stand-in for the model's API
const store = new MemoryStore(); // a real program passes its database: SQLiteStore, or its own
const limited = []; // the turns of each session that ended at the limit
let migrationDone;
const migrated = new Promise((resolve) => { migrationDone = resolve; });
const host = new Host(image('session-v1.scxml'), {
  system: 'agents',
  ioProcessors: { model },
  store,
  resident: 100, // at most 100 sessions in memory, the rest in the store
  migrationDone, // called with the migration's result when it ends
  onDone: (actor, donedata) => { limited.push(donedata.turns); },
});

const sessions = Array.from({ length: 10_000 }, () => host.spawn('session'));
for (let turn = 0; turn < 3; turn++) {
  for (const session of sessions) session.send('prompt', { text: 'Summarize my inbox' });
  await host.idle();
}
console.log(`version 1: ${completions} completions, ${store.blobs.size} sessions in the store`);

host.addImage(image('session-v2.scxml')); // the new rules, added while the host runs
host.migrate({ chart: 'session', wake: true });
const result = await migrated;
console.log(`migration: ${result.migrated} sessions moved, ${result.failed.length} failed`);

completions = 0;
for (const session of sessions) session.send('prompt', { text: 'One more' });
await host.idle();
const afterThree = limited.filter((turns) => turns === 3).length;
console.log(`version 2: ${completions} completions, ${afterThree} sessions ended at the limit of 3 turns`);
host.close();
```

```scxml title="session-v1.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="session" initial="waiting">
  <datamodel><data id="turns" expr="0"/></datamodel>

  <!-- An agent session waits for the user's prompt, asks the model and
       counts the turns it answered. -->
  <state id="waiting">
    <transition event="prompt" target="thinking"/>
  </state>
  <state id="thinking">
    <onentry>
      <send type="model" event="complete"><param name="text" expr="_event.data.text"/></send>
    </onentry>
    <transition event="reply" target="waiting">
      <assign location="turns" expr="turns + 1"/>
    </transition>
  </state>
</scxml>
```

```scxml title="session-v2.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="session" initial="waiting">
  <datamodel><data id="turns" expr="0"/></datamodel>

  <!-- Version 2 adds a plan limit: after three turns the session ends
       instead of asking the model. A moved session takes its turns from
       version 1. -->
  <state id="waiting">
    <transition event="error.platform.upgrade">
      <assign location="turns" expr="_event.data.turns"/>
    </transition>
    <transition event="prompt" cond="turns &gt;= 3" target="limited"/>
    <transition event="prompt" target="thinking"/>
  </state>
  <state id="thinking">
    <onentry>
      <send type="model" event="complete"><param name="text" expr="_event.data.text"/></send>
    </onentry>
    <transition event="reply" target="waiting">
      <assign location="turns" expr="turns + 1"/>
    </transition>
  </state>
  <final id="limited">
    <donedata><param name="turns" expr="turns"/></donedata>
  </final>
</scxml>
```

```text title="output"
version 1: 30000 completions, 9900 sessions in the store
migration: 10000 sessions moved, 0 failed
version 2: 0 completions, 10000 sessions ended at the limit of 3 turns
```

A moved session's first event is `error.platform.upgrade`, and its data holds version 1's variables, so `_event.data.turns` is the count the session reached. SCXML reserves names starting `error.platform` for events the platform raises: this one reports the move, not a failure ([Migration](https://tinyactors.dev/guides/migration/index.md#moving-running-actors)).

So every session ended at the limit instead of asking the model again.

<a id="choose-tinyactors"></a>

## Choose tinyactors for actors on a server

- **Many long-lived actors, most of them waiting**: The host [hibernates](https://tinyactors.dev/guides/hibernation/index.md) them into your store, [migrates](https://tinyactors.dev/guides/migration/index.md) them and [snapshots](https://tinyactors.dev/guides/snapshots/index.md) them all.
- **One chart in every language**: One C core runs the same chart in Node.js, Python, C and [browsers](https://tinyactors.dev/guides/browser/index.md).
- **A standard format**: A W3C SCXML document, checked by the core against the W3C suite, outlives any one library.
- **Charts you did not write**: An uploaded chart runs in [the QuickJS sandbox](https://tinyactors.dev/guides/quickjs/index.md), where a runaway loop ends in an error.

<a id="choose-xstate"></a>

## Choose XState for logic in a JavaScript app

- **State in a React component**: [`@xstate/react`](https://stately.ai/docs/xstate-react) gives hooks such as `useMachine`, which runs an actor for the component's lifetime.
- **A visual editor**: [Stately Studio](https://stately.ai/docs/studio) models machines visually, simulates them and exports the code into your codebase.
- **Test paths from the machine**: The graph utilities and Studio [generate test paths](https://stately.ai/docs/graph) from a machine; in tinyactors a generated run is code you write.
- **Typed context and events**: [`setup({ types })`](https://stately.ai/docs/typescript) types a machine's context and events. A tinyactors chart has no TypeScript types: [`index.d.ts`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-napi/index.d.ts) types an event as a string and its data as any value.
- **Actors that aren't machines**: XState's actors can be [promises, callbacks or observables](https://stately.ai/docs/actors) too. A tinyactors actor always runs a chart.
- **A released major version**: XState v5 is current, and v6 is [in beta](https://stately.ai/docs/xstate/v6/scxml). tinyactors is at 0.x and makes [frequent breaking changes](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#status).

[Write a first chart](https://tinyactors.dev/guides/charts/index.md#first-chart) · [Upgrade running actors](https://tinyactors.dev/guides/migration/index.md) · [See when to use tinyactors](https://tinyactors.dev/when-to-use/index.md)
