# tinyactors · Verifiable logic for live systems
Kind: pitch. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).
> An open-source runtime for statecharts that you can simulate, inspect and update inside your application.
tinyactors runs the rules that tell your application how to respond to events. Run those same rules in tests with a clock you control, then inspect the decisions they make in production.
- **≈ 197 B** Per started WebSocket actor in Node.js ([source](https://tinyactors.dev/assets/homepage/websocket-capacity.json))
- **4 million** WebSocket actors measured in one process ([source](https://tinyactors.dev/assets/homepage/websocket-capacity.json))
- Node.js and Bun: `npm install @tinyactors/node` (@tinyactors/node 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#node-0-4-0) · [Node.js and Bun guide](https://github.com/tinyactors-dev/tinyactors-napi#readme))
- Python: `pip install tinyactors` (tinyactors 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#python-0-4-0) · [Python guide](https://github.com/tinyactors-dev/tinyactors-cpython#readme))
- Browsers: `npm install @tinyactors/wasm` (@tinyactors/wasm 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#wasm-0-4-0) · [Browsers guide](https://tinyactors.dev/guides/browser/index.md))
- C: `curl -L https://github.com/tinyactors-dev/tinyactors-core/releases/download/v0.5.0/tinyactors-0.5.0-src.tar.gz | tar xz` (tinyactors-core 0.5.0, 26 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#c-0-5-0) · [C guide](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/embedding.md))
[Start building](https://tinyactors.dev/docs/quickstart/index.md) · [Build with a coding agent](https://tinyactors.dev/docs/agents/index.md) · [Start the live anthill](https://tinyactors.dev/anthill/index.md)
## What to build with tinyactors
- **[Background jobs](https://tinyactors.dev/recipes/index.md#workflows)**: Put retries, timeouts and cancellation in the job’s statechart.
- **[Sessions and connections](https://tinyactors.dev/recipes/index.md#sessions)**: Give each session its own state, limits and timers.
- **[Real-time applications](https://tinyactors.dev/recipes/index.md#realtime)**: Track subscriptions and connection state as clients join, leave and reconnect.
- **[Multi-step workflows](https://tinyactors.dev/recipes/index.md#workflows)**: Coordinate approvals, deadlines and work waiting on other services.
## Run millions of actors in one process
One process can host statecharts for individual jobs, connections and sessions. Each running chart is an actor with its own state, mailbox and timers.
The [memory benchmark](https://tinyactors.dev/assets/homepage/websocket-capacity.json) starts four million WebSocket actors in Node.js with tracing enabled. The actors start online. Live sockets, requests and Redis subscriptions use additional memory.
[Read the scaling results](https://tinyactors.dev/performance/index.md#scale) · [Measure on your device](https://tinyactors.dev/performance/index.md#lab)
## Simulate your system deterministically
Start from the same state and repeat the same events, clock advances and service replies to reproduce a run. The rules are stored in a statechart, which describes how events move an actor from one state to another.
- **[Control time and service replies](https://tinyactors.dev/guides/testing/index.md#reconnect-lab)**: Step through timeouts and retries with a simulated clock and handlers your tests supply.
- **[Check a rule across many runs](https://tinyactors.dev/property-testing/index.md)**: Generate sequences in your tests and assert what must hold after each run.
## Deploy application logic in milliseconds
Load a compiled chart into the process that’s already running. New actors start on the new version. For actors already running, choose when to [move them](https://tinyactors.dev/guides/migration/index.md#why-migrate).
The running host loads version 2. A new actor starts there, and messages to an existing actor still reach it on version 1. An explicit migration moves that actor to version 2 under the same address.
In a [Node.js benchmark](https://tinyactors.dev/guides/migration/index.md#load-time), at least 95 of 100 trials loaded a precompiled chart and started its first actor in under a millisecond. Moving existing actors is measured separately.
[Read the migration guide](https://tinyactors.dev/guides/migration/index.md)
## Use the runtime you already have
The same C engine powers the Node.js and Python bindings and the WebAssembly package. You can also embed it directly in a C application.
- **[Node.js and Bun](https://tinyactors.dev/docs/node/index.md)**: Install the native binding for JavaScript and TypeScript.
- **[Python](https://tinyactors.dev/docs/python/index.md)**: Run a host through the Python binding.
- **[Browser](https://tinyactors.dev/guides/browser/index.md)**: Run charts in the browser with WebAssembly.
- **[C](https://tinyactors.dev/docs/quickstart/index.md#run)**: Embed the core in a native application.
## Tools for development and production
- **[Live inspection](https://tinyactors.dev/guides/inspection/index.md)**: Read an actor’s active states, variables, mailbox and delayed sends.
- **[OpenTelemetry](https://tinyactors.dev/telemetry/index.md)**: Follow events and transitions across actors with traces, logs and metrics.
- **[Chart checks in CI](https://tinyactors.dev/cli/guides/ci/index.md)**: Compile charts, check them for warnings and compare versions before deploying.
- **[Snapshot inspector](https://tinyactors.dev/inspector/index.md)**: Open a captured host in the browser and inspect the state it held at capture time.
- **[Actor hibernation](https://tinyactors.dev/guides/hibernation/index.md)**: Move idle actors out of memory through a store your application provides.
- **[Coding agent support](https://tinyactors.dev/docs/agents/index.md)**: Give your agent the docs and the skill for writing and testing charts.
## Embed tinyactors in your application
The host runs inside your process. Statecharts request outside work by sending events to handlers you supply. Those handlers connect to the services and storage your application already uses.
[Read the architecture](https://tinyactors.dev/architecture/index.md) · [Connect your services](https://tinyactors.dev/guides/io-processors/index.md)
## Frequently asked questions
- **Does tinyactors support Bun?**: Yes. The same [package supports Node.js and Bun](https://tinyactors.dev/docs/node/index.md). In Bun, run `bun add @tinyactors/node`.
- **How does tinyactors compare to Temporal?**: Temporal’s service persists workflow history so workers can resume after failure. tinyactors runs statecharts in your process and your application owns durable state. [Compare tinyactors with Temporal](https://tinyactors.dev/compare/temporal/index.md).
- **How does tinyactors compare to Cloudflare Durable Objects?**: Cloudflare gives each Durable Object a globally addressable identity and attached storage. tinyactors actors run in your application, which chooses how to route messages and where to store data. [Compare tinyactors with Durable Objects](https://tinyactors.dev/compare/durable-objects/index.md).
- **How does tinyactors compare to Rivet?**: Rivet’s control plane places actors across machines and Rivet provides actor storage. tinyactors embeds a host in your process for actors that run statecharts. [Compare tinyactors with Rivet](https://tinyactors.dev/compare/rivet/index.md).
- **Is tinyactors like Erlang, Akka or Orleans?**: All use message passing between stateful units. [Erlang processes](https://www.erlang.org/doc/system/ref_man_processes.html), [Akka actors](https://doc.akka.io/libraries/akka-core/current/typed/actors.html) and [Orleans grains](https://learn.microsoft.com/en-us/dotnet/orleans/overview) run behavior written in their host languages. Each tinyactors actor runs a statechart that your application can load as data.
- **How is tinyactors different from XState?**: XState is a good fit for statecharts in JavaScript and TypeScript. With tinyactors, the chart is a separate file you can run in Python or C too, and load into a running host as a new version. [Compare tinyactors with XState](https://tinyactors.dev/compare/xstate/index.md).
- **What is a statechart?**: A statechart describes the states a part of your application can be in, the events it responds to and the transitions those events cause. [Read how statecharts work](https://tinyactors.dev/docs/statecharts/index.md).
- **What happens if the process stops?**: Actors live in process memory. Save the records your application needs to rebuild them, including any deadlines it must honor after a restart. Read the [recovery options](https://tinyactors.dev/when-to-use/index.md#crash).
- **How do I run actors across machines?**: Run a host in each process and provide a [transport between hosts](https://tinyactors.dev/guides/other-systems/index.md). Your application handles actor placement and failover.
- **Is tinyactors open source?**: Yes. The [source is MIT-licensed](https://github.com/tinyactors-dev/tinyactors/blob/main/LICENSE). The packages are at version 0.x and the APIs can still change.
## Build with verifiable logic
Start with one part of your application. Put its rules in a statechart and test what happens as events arrive.
[Start building](https://tinyactors.dev/docs/quickstart/index.md) · [Build with a coding agent](https://tinyactors.dev/docs/agents/index.md)
---
# Documentation · tinyactors
Kind: reference. 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: [Reference](https://tinyactors.dev/voices/reference.xml).
> Everything about tinyactors in one place: the quickstart, the ideas behind statecharts and actors, the guides, the command line, the reference and the design.
Start with one program that runs in five minutes. Then read the ideas, follow a guide for each task, and look up the rest.
## Start here
- **[Quickstart](https://tinyactors.dev/docs/quickstart/index.md)**: Install one package and run an order actor that retries its payment on its own, in Node.js, Python, a browser or C.
- **[Statecharts and actors in ten minutes](https://tinyactors.dev/docs/statecharts/index.md)**: States, events, transitions, timers and actors, with an order you can drive in the page.
- **[Build a team chat](https://tinyactors.dev/chat/index.md)**: A tutorial of nine steps, from one room to direct messages, each a program that runs.
- **[Build with a coding agent](https://tinyactors.dev/docs/agents/index.md)**: Give your agent the docs and the skill, and check what it writes in CI.
## Guides for each task
- **[All guides](https://tinyactors.dev/guides/index.md)**: Writing and testing charts, connecting actors to your code, running a host in production and in the browser.
- **[Test your charts](https://tinyactors.dev/guides/testing/index.md)**: Advance a simulated clock and see how a WebSocket reacts when a reconnect attempt succeeds or fails.
- **[Keep waiting actors out of memory](https://tinyactors.dev/guides/hibernation/index.md)**: Two million actors ran with at most 1000 in memory and the rest in a database.
- **[Change the chart of running actors](https://tinyactors.dev/guides/migration/index.md)**: Add a new version to the running process, and move each actor to it with the state it reached.
- **[Journal and replay](https://tinyactors.dev/guides/journal/index.md)**: Record every input, and one loop rebuilds every actor after a crash.
- **[Recipes](https://tinyactors.dev/recipes/index.md)**: Example applications named after what people build: order fulfillment, billing, a job scheduler, an HTTP gateway and more.
## Check and run charts from the command line
- **[The tinyactors command](https://tinyactors.dev/cli/index.md)**: Compile, check, compare, draw and run charts, and read snapshots offline.
- **[Tutorial](https://tinyactors.dev/cli/tutorial/index.md)**: From a draft chart with a misspelt event to a deploy you can compare.
- **[CI checks](https://tinyactors.dev/cli/guides/ci/index.md)**: Fail a build when a chart has an error or its behavior changed.
## Look things up
- **[Command reference](https://tinyactors.dev/cli/commands/index.md)**: Every command of the tinyactors command, with its options and examples.
- **[@tinyactors/node API](https://tinyactors.dev/docs/node/index.md)**: Every class, function, interface and type of the Node.js and Bun package.
- **[Python API](https://tinyactors.dev/docs/python/index.md)**: Every class, function and constant of the tinyactors package for Python.
- **[The C library](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/embedding.md)**: How to embed the core in C: the loop, lifetimes and memory.
- **[Changelog](https://tinyactors.dev/changelog/index.md)**: What changed in each release of each package.
- **[Memory, capacity and performance](https://tinyactors.dev/performance/index.md)**: What an actor costs, and the programs that measured it.
## Understand the design
- **[When to use tinyactors](https://tinyactors.dev/when-to-use/index.md)**: What it fits, its limits, what a crash keeps, and how it compares with Temporal, Durable Objects, Rivet and XState.
- **[Architecture](https://tinyactors.dev/architecture/index.md)**: How a host runs actors in your process, from the effects loop to the bytes of a snapshot.
- **[The command line and the libraries](https://tinyactors.dev/cli/why/index.md)**: When to reach for the command, and when for a library in your program.
- **[Why tinyactors exists](https://tinyactors.dev/about/index.md)**: Who makes it, and why.
## See it run
- **[A million ants](https://tinyactors.dev/anthill/index.md)**: Two colonies in your browser, every ant an actor.
- **[Property testing](https://tinyactors.dev/property-testing/index.md)**: A thousand generated runs of a payment, checked against rules in the page.
- **[Telemetry](https://tinyactors.dev/telemetry/index.md)**: Every step of every actor as an OpenTelemetry span.
- **[Snapshot inspector](https://tinyactors.dev/inspector/index.md)**: Open a snapshot and read every actor in it.
---
# Quickstart · tinyactors
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Install tinyactors in Node.js, Python, a browser or C, and run an order actor that retries its payment on its own, in five minutes.
Install one package and run one program. An order actor fills its cart, charges the card and retries on its own when the payment service is down.
- Node.js and Bun: `npm install @tinyactors/node` (@tinyactors/node 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#node-0-4-0) · [Node.js and Bun guide](https://github.com/tinyactors-dev/tinyactors-napi#readme))
- Python: `pip install tinyactors` (tinyactors 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#python-0-4-0) · [Python guide](https://github.com/tinyactors-dev/tinyactors-cpython#readme))
- Browsers: `npm install @tinyactors/wasm` (@tinyactors/wasm 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#wasm-0-4-0) · [Browsers guide](https://tinyactors.dev/guides/browser/index.md))
- C: `curl -L https://github.com/tinyactors-dev/tinyactors-core/releases/download/v0.5.0/tinyactors-0.5.0-src.tar.gz | tar xz` (tinyactors-core 0.5.0, 26 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#c-0-5-0) · [C guide](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/embedding.md))
## Write a chart and run it
The packages need Node.js 22.3 or Bun, Python 3.13 or newer, or a C compiler. Save the chart as `order.scxml` and the program beside it, then run the program; the tabs follow the package you picked above.
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
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"
```
Browsers:
```javascript title="browser.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';
let charges = 0;
const payments = {
receive(send) { // the chart's
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"
```
Python:
```python title="main.py"
import asyncio
import json
import tinyactors
class Payments:
charges = 0
def receive(self, send): # the chart's
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"
```
C:
```c title="main.c"
/* cc main.c host.c -ltinyactors_datamodel_ecmascript -ltinyactors_runtime -ltinyactors -lm */
#include
#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 */
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 */
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 : 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
#include
#include
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
#include
#include
/* 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"
```
```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
```
The first charge fails, so the chart waits a second and charges again. Your program never wrote that retry: it lives in the chart's `retrying` state.
Every package prints these same lines. The chart's expressions are JavaScript in every package, Python's included.
## The chart decides, your program acts
- **The host**: runs the actors inside your process, so there is no server to start. Its system id, `shop`, names it in actors' addresses, such as `tinyactors://shop/@order-17`.
- **The chart**: holds every state the order can be in and the events that move it. Press the buttons under the diagram to drive it yourself.
- **The I/O processor**: is the `payments` object your program gives the host. The chart sends it `charge` and never calls a network itself, so a test can answer instead of a real service. [The payment retry test](https://tinyactors.dev/guides/testing-recipes/index.md#a-test) lets three attempts time out by stepping the clock past each wait.
- **A crash**: stops the actors in the process, the order waiting for its retry included. [Journal and replay](https://tinyactors.dev/guides/journal/index.md) and [snapshots](https://tinyactors.dev/guides/snapshots/index.md) bring them back.
## Let your coding agent read the docs
Add the tinyactors support server to your agent, and it can search these docs, load the skill for building with tinyactors and report what got in its way. In Claude Code:
```shell
claude mcp add --transport http tinyactors-support https://mcp.tinyactors.dev/mcp
```
[Build with a coding agent](https://tinyactors.dev/docs/agents/index.md) covers the other agents and what the server offers.
## Go further
- **[Statecharts and actors in ten minutes](https://tinyactors.dev/docs/statecharts/index.md)**: the ideas behind the chart above, with an order you can drive.
- **[Build a team chat](https://tinyactors.dev/chat/index.md)**: a tutorial of nine steps, from one room to direct messages, each a program that runs.
- **[Test your charts](https://tinyactors.dev/guides/testing/index.md)**: a week of timeouts in milliseconds on a simulated clock.
- **[All guides](https://tinyactors.dev/guides/index.md)**: hibernation, migration, snapshots, journals and the rest, each with a program that runs.
---
# Statecharts and actors in ten minutes
Kind: explanation. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [Explanation](https://tinyactors.dev/voices/explanation.xml).
> What statecharts and actors are, shown on one order chart you can drive: states and events, guards, the data model, nested and parallel states, timers, effects and actors.
A statechart is a state machine whose states can nest and run in parallel, written in [SCXML](https://www.w3.org/TR/scxml/), a W3C standard; an actor is one statechart running with its own data. This page builds one order chart, from the cart to a shipped parcel, and you can drive it as you read. After it, you can read any chart on this site and judge whether your own workflow fits one.
[Drive the order](https://tinyactors.dev/docs/statecharts/index.md#run)
## Flags let an order be paid and cancelled
> An order that tracks its progress with booleans can reach combinations nobody meant. Each one is a bug a customer finds: a card charged twice, a paid order cancelled.
Here is an order written the usual way, with a flag per step and a handler per event. The last four lines play one afternoon of it.
```javascript title="order.mjs"
const order = { paying: false, paid: false, cancelled: false, attempts: 0 };
function charge() { order.attempts += 1; console.log('charge', order.attempts); }
function checkout() { order.paying = true; charge(); }
function onCharged() { order.paid = true; } // paying stays true
function onTimeout() { if (order.paying && order.attempts < 3) charge(); }
function cancel() { order.cancelled = true; }
checkout();
onCharged(); // the payment service answers
onTimeout(); // the timer nobody cleared fires anyway
cancel(); // nothing stops a cancel after payment
console.log(order);
```
```text title="output"
charge 1
charge 2
{ paying: true, paid: true, cancelled: true, attempts: 2 }
```
Nothing here is careless. Each handler sets the flag it owns, and the retry checks `paying` as it should. But `onCharged` forgot to clear `paying`, and nothing in the program says which combinations are legal.
Three booleans make eight combinations, and only four make sense: in the cart, paying, paid and cancelled. Every handler has to rule out the other four, and each new flag doubles them. A state machine starts from the other end: it lists the states, so the order is in exactly one.
## An order is in one state
> The order must take `add` while it is a cart and refuse it while the card is charged. With flags, that is one more check at the top of a handler.
A [state](https://www.w3.org/TR/scxml/#state) is a situation the order waits in. An [event](https://www.w3.org/TR/scxml/#events) is a named message, with optional data, that it receives. Each state lists the events it handles, and an event no transition of the current state names is discarded.
In SCXML, the W3C's XML language for statecharts, that is a `` with a `` per event. The cart handles two: `add` puts an item in it, and `checkout` moves the order to `paying`. In `paying` no transition names `add`, so the cart can't change while the card is charged.
```scxml title="order.scxml"
```
## A guard decides whether a transition fires
> Checkout with an empty cart must do nothing, and a payment that keeps timing out must stop after three tries. Both depend on data, not on which state the order is in.
A [transition](https://www.w3.org/TR/scxml/#transition) names its event, its target state and, in `cond`, a guard: a [condition](https://www.w3.org/TR/scxml/#ConditionalExpressions) that must be true for it to fire. The cart's `checkout` has `items.length > 0`, so an empty cart stays a cart.
When several transitions of a state match one event, the first in document order whose guard holds is taken. `paying` uses that for its timeout. The first transition tries again while `attempts < 3`; the second has no guard, so it catches the third timeout and returns the order to the cart.
```scxml title="order.scxml"
```
## The data model holds what states cannot
> A cart holds any number of items, and a state for each cart would never end. The order also has to remember its total and how often it charged.
Each chart has a [data model](https://www.w3.org/TR/scxml/#data-module): variables declared in `` with their first values, read and changed by expressions in the chart's language. This chart's language is ECMAScript, named by `datamodel="ecmascript"` on its root.
An `` changes a variable when a transition fires, and `_event.data` is the data the event carried: the cart's `add` appends the item and adds its price. States say where the order is. Variables say what it holds.
```scxml title="order.scxml"
```
## A parent state handles its children's events
> A customer may cancel while the order is a cart or while the card is charged, but never once it's paid. In the flag version, that rule is an `if` someone has to remember in `cancel`.
States nest. `cart` and `paying` are children of `open`, and while the order is in either, `open` is active too. A transition on `open` applies in every state inside it, so one line lets the customer cancel from both.
Once paid, the order has left `open`, and `cancel` finds no transition. A refund after payment would be a transition of its own, on `paid`, where a reviewer reads it.
```scxml title="order.scxml"
```
## Parallel states run side by side
> A paid order ships and emails its receipt, and neither waits for the other. A plain state machine would need a state for each pair: packing and emailing, packing and emailed, and two more.
A [``](https://www.w3.org/TR/scxml/#parallel) state is in all of its children at once, each child a region with its own states. Here `shipping` waits in `packing` for the warehouse's `shipped`, while `receipt` emails the receipt and waits for `sent`.
When every region reaches a [final state](https://www.w3.org/TR/scxml/#final), the chart sends itself the event `done.state.paid`, a name SCXML makes from the parallel state's id, and the order moves to `complete`. The set of states active at one moment is the [state configuration](https://www.w3.org/TR/scxml/#state-configuration). The program's output shows one: `paid` with `packing` in one region and `emailed` in the other.
```scxml title="order.scxml"
```
## A timer is an event sent later
> The payment service sometimes never answers, so the order must charge again after five seconds. In the flag version, that timer outlived the payment and charged the card twice.
A delayed send is a [``](https://www.w3.org/TR/scxml/#send) with a `delay`: with no target, the event comes back to the chart itself, later. Each time the order enters `paying`, it sends itself `payment.timeout` five seconds out.
Its `` [cancels](https://www.w3.org/TR/scxml/#cancel) that send by its id, so leaving the state takes the timer with it. A `charged` that arrives first leaves no timeout behind to charge again.
```scxml title="order.scxml"
```
The timer runs on the host's clock, not on a `setTimeout` of yours. A test gives the host a simulated clock and moves it: the program's `clock.increment(5000)` fires the timeout at once, and the output shows the second charge at 5000 ms.
## The chart never calls the network
> Charging a card and sending an email are I/O, and I/O is what makes a workflow hard to test. A chart that made its own HTTP calls would make every test stub the network or wait for it.
A chart reaches the world only by sending events. `` leaves the order as an effect, a request for your code. The host, the part of tinyactors that runs charts in your program, hands it to the [I/O processor](https://www.w3.org/TR/scxml/#eventioprocessors) your program gave it for `payments`. The processor does the I/O and answers with an event, `charged`, which the order receives like any other.
So your program decides how a charge happens: a payment API in production, a stand-in in a test. This one ignores the first charge and answers the second. In the diagram, you play the payment service yourself by pressing `charged`.
```javascript title="main.mjs"
const clock = new SimulatedClock();
let charges = 0;
const payments = {
receive(send) { // the chart's
charges += 1;
console.log(`${clock.now} ms: charge ${send.data.amount}, attempt ${charges}`);
if (charges > 1) send.answer('charged'); // the first charge never answers
},
};
```
## An actor is one running chart
> A shop has thousands of open orders, each at its own step with its own cart. They must not share variables, and two events for one order must never interleave.
An actor is one instance of a chart: its own state configuration, its own variables, its own queue of events and its own timers. The host is the part of tinyactors that runs actors in your process. It starts one with `spawn`, here under the name `order-1042`, and any part of the program finds it by that name.
Events sent to an actor wait in its queue, and it handles them one at a time, each to completion. So an `add` and a `checkout` for one order never run halfway into each other, and your code holds no lock. That holds within one host: with several processes, give each order to one of them and send its events there.
```javascript title="main.mjs"
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);
const host = new Host(compiled, { system: 'shop', clock, ioProcessors: { payments, email } });
compiled.close();
host.spawn('order', { name: 'order-1042' });
const order = host.actor('order-1042'); // any part of your program finds it by name
order.send('add', { item: 'notebook', price: 30 });
order.send('add', { item: 'pen', price: 12 });
order.send('checkout');
await host.idle();
console.log('waiting in', JSON.stringify((await order.state()).value));
```
An actor is small: [about 530 bytes](https://tinyactors.dev/performance/index.md#actors) each for a one-variable chart, measured in Node.js with a million in one process. That is small enough to make each order, payment or chat session an actor of its own.
## Run the whole order
> Each section showed one piece of the chart. A program must start the order, answer its charges and move its clock.
Here are the whole chart and the program. `spawn('order')` names the chart by its `name` attribute, not its file. Open the Diagram tab beside `order.scxml`, press `Add a notebook`, then `checkout`, and watch the active states light up.
Node.js and Bun:
```javascript title="main.mjs"
import { readFileSync } from 'node:fs';
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const clock = new SimulatedClock();
let charges = 0;
const payments = {
receive(send) { // the chart's
charges += 1;
console.log(`${clock.now} ms: charge ${send.data.amount}, attempt ${charges}`);
if (charges > 1) send.answer('charged'); // the first charge never answers
},
};
const email = {
receive(send) { // the chart's
console.log(`${clock.now} ms: receipt for ${send.data.total}`);
send.answer('sent');
},
};
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);
const host = new Host(compiled, { system: 'shop', clock, ioProcessors: { payments, email } });
compiled.close();
host.spawn('order', { name: 'order-1042' });
const order = host.actor('order-1042'); // any part of your program finds it by name
order.send('add', { item: 'notebook', price: 30 });
order.send('add', { item: 'pen', price: 12 });
order.send('checkout');
await host.idle();
console.log('waiting in', JSON.stringify((await order.state()).value));
clock.increment(5000); // five seconds pass, at once: the timeout fires
await host.idle();
console.log('then in', JSON.stringify((await order.state()).value));
order.send('shipped'); // the warehouse reports the parcel
console.log('complete, total', await order.done);
host.close();
```
```scxml title="order.scxml"
```
```text title="output"
0 ms: charge 42, attempt 1
waiting in {"open":"paying"}
5000 ms: charge 42, attempt 2
5000 ms: receipt for 42
then in {"paid":{"shipping":"packing","receipt":"emailed"}}
complete, total 42
```
Read the output from the top. The first charge got no answer, so the order waited in `paying`. Five seconds later the timeout charged again, the stand-in answered, and the order entered `paid`.
Both regions started then: the receipt went out at once, while shipping waited in `packing`. The warehouse's `shipped` finished the last region, and the order completed with its total.
## Build a system of actors next
> One chart is one entity. A real system has many actors that send each other events, go idle and come back.
The chat tutorial builds a team chat from actors like this order, one step at a time, with rooms, presence and idle users saved to a store. Writing charts covers the rest of SCXML as tinyactors runs it: scripts, sends between actors and charts that start other charts.
[Run it in five minutes](https://tinyactors.dev/docs/quickstart/index.md) · [Build a team chat](https://tinyactors.dev/chat/index.md) · [Write your first chart](https://tinyactors.dev/guides/charts/index.md#first-chart)
---
# Build a team chat with tinyactors
Kind: tutorial. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [Tutorial](https://tinyactors.dev/voices/tutorial.xml).
> Try a team chat in your browser, then build it in nine steps, from one room to direct messages between two people.
Try the finished chat in this tab, then build it in nine steps, each a program you can run.
- Node.js and Bun: `npm install @tinyactors/node` (@tinyactors/node 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#node-0-4-0) · [Node.js and Bun guide](https://github.com/tinyactors-dev/tinyactors-napi#readme))
[Start building](https://tinyactors.dev/chat/index.md#room) · [Get the code](https://github.com/tinyactors-dev/tinyactors/tree/main/website/examples/chat)
## Chat as any of six people
Each person and channel is an actor in this tab, and you are forager: switch person from your avatar's menu. The debugger at the top right cuts a person's connection or switches the running chat between steps 5 and 9.
A team chat, The Hill, with channels, direct messages and six people, each an actor; you are forager, and your avatar's menu signs you out or switches person. Its debugger runs the simulated clock, loses a person's connection, makes a screen drop or delay messages, runs scenarios, shows each actor's chart in its current state and a log, and moves the running chat between the tutorial's steps 5 and 9 by live migration.
## 1. Create a room
A room is an actor with a list of members: `join` adds to it, and `post` sends to all of them. The text leaves the chart as a `message` to `chat:client`, which your program handles.
```scxml title="charts/room.scxml"
```
Here a `Client` prints what each member's screen would show. The program starts a room and sends it two joins and a post.
```javascript title="main.mjs"
// The client processor stands in for the users' screens.
class Client {
lines = [];
receive(send) {
for (const user of send.data.to) this.lines.push(`${user} sees ${send.data.from}: ${send.data.text}`);
}
}
```
```javascript title="main.mjs"
const room = host.spawn('room', { name: 'general' });
room.send('join', { user: 'ada' });
room.send('join', { user: 'bob' });
room.send('post', { user: 'ada', text: 'hi' });
await host.idle();
```
```text title="output"
ada sees ada: hi
bob sees ada: hi
```
## 2. Track who is online
A user who stops typing sends no event, so nothing marks them away. The user's chart restarts a 300-second timer on each `activity`, and when it fires, the chart moves to `away`.
```scxml title="charts/user.scxml"
```
The room now sends each post to each member's user actor, by its name. A user who is offline ignores it.
```scxml title="charts/room.scxml"
```
A simulated clock moves 300 seconds in no time, so the program sees both users go away.
```javascript title="main.mjs"
client.lines.push('-- 300 seconds pass');
clock.increment(300_000);
await host.idle();
client.lines.push('-- bob types, ada closes the app');
host.actor('user.bob').send('activity');
host.actor('user.ada').send('disconnect');
room.send('post', { user: 'bob', text: 'anyone?' });
await host.idle();
```
```text title="output"
ada is offline
bob is offline
ada is active
bob is active
-- 300 seconds pass
ada is away
bob is away
-- bob types, ada closes the app
bob is active
ada is offline
bob sees bob: anyone?
```
## 3. Create each room once
Two users who create `general` at the same moment could get two rooms. One workspace actor creates every room with a `spawn` send and records the name at once, so a repeat is refused.
```scxml title="charts/workspace.scxml"
```
A user joins a room by its name. A join sent to a room that does not exist comes back to the user as `error.communication`.
```scxml title="charts/user.scxml"
```
With `actor.ask`, the program requests `general` twice and two invalid names; then bob joins a room that does not exist.
```javascript title="main.mjs"
for (const name of ['general', 'general', 'Bad Name', '-']) {
const [event, data] = await workspace.ask('room.create', { name });
client.lines.push(`create ${name}: ${event}${data.reason ? ` (${data.reason})` : ''}`);
}
const [, { rooms }] = await workspace.ask('rooms.list');
client.lines.push(`rooms: ${rooms.join(', ')}`);
ada.send('join', { room: 'general' });
bob.send('join', { room: 'general' });
bob.send('join', { room: 'random' });
```
```text title="output"
create general: room.created
create general: room.refused (exists)
create Bad Name: room.refused (invalid name)
create -: room.refused (invalid name)
rooms: general
ada joined general
bob gets an error: no such room
bob joined general
ada sees ada in general: hi
bob sees ada in general: hi
```
## 4. Show everyone who is online
A user who connects late has missed every status change made before. Each user now reports its status to the workspace, which keeps them all.
```scxml title="charts/workspace.scxml"
```
A newcomer gets the whole roster, and each user online gets every change after that.
```text title="output"
-- ada connects
ada sees the roster: ada active, bob offline, cat offline
-- bob connects
bob sees the roster: ada active, bob active, cat offline
ada sees bob is active
-- 300 seconds pass
bob sees ada is away
ada sees bob is away
-- bob closes the app
ada sees bob is offline
the workspace answers: {"ada":"away","bob":"offline","cat":"offline"}
```
## 5. Keep idle users out of memory
Most users sit idle, yet each one's actor stays in memory. Give the host a `store` and a `resident` bound, and actors past the bound wait in the store.
```javascript title="main.mjs"
const host = new Host(compiled, {
system: 'chat',
clock,
store,
resident,
ioProcessors: { 'chat:client': client, spawn: new Spawner() },
...options,
});
```
```text title="output"
1000 users spawned: 1002 actors, 50 in memory, 952 in the store
100 users connect and join general: 1002 actors, 50 in memory, 952 in the store
u0 posts: 1002 actors, 50 in memory, 952 in the store
100 messages reached the screens
300 seconds pass: 1002 actors, 50 in memory, 952 in the store
14850 roster updates reached the screens
the store saved 1156 blobs and loaded 204
at most 50 actors were in memory at rest
```
The charts are step 4's: an event, or a user's 300-second timer, loads a saved actor again.
## 6. Show who is typing
A notice for every key would flood every screen. The user's chart tells its room at most once every 3 seconds, on a timer of its own.
```scxml title="charts/user.scxml"
```
Each other member's chart shows the notice for 5 seconds after the last one, restarting its timer on each.
```scxml title="charts/user.scxml"
```
A post takes the typist's notice off every screen, so it ends the typist's 3 seconds too. The first key after a post is told at once.
```scxml title="charts/user.scxml"
```
When its user disconnects, the chart cancels its timers and takes each notice off the user's screen.
```scxml title="charts/user.scxml"
```
Ada's three keys make one notice, and bob's notice runs out by itself. Cat's disconnect takes bob's notice off cat's screen, and ada's key right after a post shows at once.
```javascript title="main.mjs"
client.lines.push('-- ada types three keys');
for (let key = 0; key < 3; key++) ada.send('typing', { room: 'general' });
await host.idle();
client.lines.push('-- 4 seconds pass, ada types and posts');
clock.increment(4_000);
ada.send('typing', { room: 'general' });
await host.idle();
ada.send('post', { room: 'general', text: 'lunch?' });
await host.idle();
client.lines.push('-- bob types, then stops for 6 seconds');
bob.send('typing', { room: 'general' });
await host.idle();
clock.increment(6_000);
await host.idle();
client.lines.push('-- bob types again, then cat disconnects');
bob.send('typing', { room: 'general' });
await host.idle();
host.actor('user.cat').send('disconnect');
await host.idle();
client.lines.push('-- ada types, posts and types again at once');
ada.send('typing', { room: 'general' });
await host.idle();
ada.send('post', { room: 'general', text: 'pizza?' });
await host.idle();
ada.send('typing', { room: 'general' });
await host.idle();
```
```text title="output"
-- ada types three keys
bob sees ada typing in general
cat sees ada typing in general
-- 4 seconds pass, ada types and posts
ada sees ada in general: lunch?
bob sees ada stop typing in general
cat sees ada stop typing in general
bob sees ada in general: lunch?
cat sees ada in general: lunch?
-- bob types, then stops for 6 seconds
ada sees bob typing in general
cat sees bob typing in general
ada sees bob stop typing in general
cat sees bob stop typing in general
-- bob types again, then cat disconnects
ada sees bob typing in general
cat sees bob typing in general
cat sees bob stop typing in general
-- ada types, posts and types again at once
bob sees ada typing in general
ada sees ada in general: pizza?
bob sees ada stop typing in general
bob sees ada in general: pizza?
bob sees ada typing in general
```
## 7. Ride out a lost connection
A phone in a tunnel loses its connection for a few seconds, and until now its user went offline at once. Now the user's chart reports `away`, as Slack shows it, and keeps new messages for 30 seconds in `reconnecting`.
```scxml title="charts/user.scxml"
```
Back within 30 seconds, the history state `resume` returns the user to `active` or `away`, whose entry reports that status again. The held messages reach the screen, and the raised `reconnected` asks the workspace for the roster once the status is out.
```scxml title="charts/user.scxml"
```
Ada sees bob away, then active 10 seconds later; he gets the held message and a roster with cy offline. Then he is gone for 40 seconds: only the second loss makes him offline.
```javascript title="main.mjs"
client.lines.push('-- bob enters a tunnel, cy signs out, ada posts');
bob.send('connection.lost');
await host.idle();
cy.send('disconnect');
await host.idle();
ada.send('post', { room: 'general', text: 'where are you?' });
await host.idle();
client.lines.push('-- 10 seconds later bob is back');
clock.increment(10_000);
bob.send('connect');
await host.idle();
client.lines.push('-- bob loses the connection for 40 seconds');
bob.send('connection.lost');
await host.idle();
clock.increment(40_000);
await host.idle();
ada.send('post', { room: 'general', text: 'gone?' });
await host.idle();
```
```text title="output"
-- bob enters a tunnel, cy signs out, ada posts
ada sees bob is away
cy sees bob is away
ada sees cy is offline
ada sees ada in general: where are you?
-- 10 seconds later bob is back
bob sees ada in general: where are you?
ada sees bob is active
bob sees the roster: ada active, bob active, cy offline
-- bob loses the connection for 40 seconds
ada sees bob is away
ada sees bob is offline
ada sees ada in general: gone?
```
## 8. Show a room's history to late joiners
A member who joins late saw nothing said before, and a member who joined twice got every post twice. A channel's history is data your program stores; the room sends each post to the store, which numbers and times it.
```scxml title="charts/room.scxml"
```
The store is an I/O processor of your program. It numbers and times each post, so a screen shows when it was posted, however late it arrives.
```javascript title="main.mjs"
// The channels' history: data the application stores, one list of posts a
// channel. The room chart sends each post here (chat:history); the store
// numbers it, records when it was made by the clock it is given, keeps it
// and answers `appended` with both, which the room puts on the post it
// sends each member. The numbers count per channel, as a channel's posts
// are read together, and never start again: the store, not an actor, holds
// the count. A screen shows a post's own time, however late the post
// reaches it, and reads a channel's latest posts when it joins. A real
// store is a table in a database.
export class History {
posts = new Map(); // room -> [{ seq, at, from, text }]
constructor(clock) {
this.clock = clock;
}
receive(send) {
const { room, from, text } = send.data;
if (!this.posts.has(room)) this.posts.set(room, []);
const posts = this.posts.get(room);
const seq = posts.length + 1;
const at = this.clock.now; // milliseconds
posts.push({ seq, at, from, text });
send.answer('appended', { seq, at, room, from, text });
}
/** The latest `limit` posts of `room`. */
read(room, limit = 50) {
return (this.posts.get(room) ?? []).slice(-limit);
}
}
```
A join adds the member only once, and answers `joined` so the screen reads the store.
```scxml title="charts/room.scxml"
```
A member who signs out misses the posts made meanwhile: the room sends them, but an offline user drops them. When the connection opens, the screen reads what it lacks from the store.
```javascript title="main.mjs"
/** `user`'s connection opens: for each room joined, the screen reads the posts it lacks. */
opened(user) {
for (const room of this.rooms.get(user) ?? []) {
const posts = this.history.read(room).filter((post) => !this.shown.has(`${user} ${room} ${post.seq}`));
if (posts.length === 0) continue;
for (const post of posts) this.shown.add(`${user} ${room} ${post.seq}`);
this.lines.push(`${user} connects and reads in ${room}: ${posts.map(said).join(' | ')}`);
}
}
```
Cat joins after two posts and reads both; bob joins a second time, and the third post reaches him once. Cat signs out for the fourth post and reads it five minutes later, stamped with the time bob posted it.
```javascript title="main.mjs"
clock.increment(90_000);
client.lines.push('-- cat joins late, bob joins again');
cat.send('join', { room: 'general' });
bob.send('join', { room: 'general' });
await host.idle();
ada.send('post', { room: 'general', text: 'welcome, cat' });
await host.idle();
client.lines.push('-- cat signs out, and back in five minutes later');
cat.send('disconnect');
await host.idle();
clock.increment(60_000);
bob.send('post', { room: 'general', text: 'lunch at noon' });
await host.idle();
clock.increment(300_000);
client.opened('cat'); // cat's connection opens: the screen catches up,
cat.send('connect'); // then cat's actor hears of it
await host.idle();
```
```text title="output"
-- ada and bob join and talk
ada joins general and reads nothing yet
bob joins general and reads nothing yet
ada sees post 1 from ada at 0:00: hi bob
bob sees post 1 from ada at 0:00: hi bob
ada sees post 2 from bob at 0:30: hi ada
bob sees post 2 from bob at 0:30: hi ada
-- cat joins late, bob joins again
cat joins general and reads ada at 0:00: hi bob | bob at 0:30: hi ada
bob joins general and reads ada at 0:00: hi bob | bob at 0:30: hi ada
ada sees post 3 from ada at 2:00: welcome, cat
bob sees post 3 from ada at 2:00: welcome, cat
cat sees post 3 from ada at 2:00: welcome, cat
-- cat signs out, and back in five minutes later
ada sees post 4 from bob at 3:00: lunch at noon
bob sees post 4 from bob at 3:00: lunch at noon
cat connects and reads in general: bob at 3:00: lunch at noon
```
## 9. Send a direct message
Two people who want to talk privately have only channels, which anyone can join. A direct message is a room of the two, which the workspace makes once per pair.
```scxml title="charts/workspace.scxml"
```
Either side asks for `dm.forager.scout`: the two names, sorted. A channel's name holds no dot, so no channel takes it.
```scxml title="charts/workspace.scxml"
function direct(event) {
const members = [...new Set([event.data.user, event.data.with])].sort();
return { room: 'dm.' + members.join('.'), members };
}
```
The room chart builds on step 8's, so a direct message keeps history, typing and catch-up. Its members come with the spawn, and the room refuses anyone else's join.
```scxml title="charts/room.scxml"
```
The other person hears of their direct messages from the workspace when they come online, as they hear the roster. Back from a lost connection, the user chart asks for them with `dms.get`, as it asks `roster.get`.
```scxml title="charts/workspace.scxml"
```
Scout writes to forager, who is signed out and reads both posts on signing in. Queen's join is refused, and her post reaches nobody.
```javascript title="main.mjs"
client.lines.push('-- scout opens a DM with forager, who is signed out, and posts twice');
scout.send('dm.open', { with: 'forager' });
await host.idle();
const dm = [...client.dms.get('scout').keys()][0];
scout.send('post', { room: dm, text: 'sugar by the oak' });
await host.idle();
clock.increment(30_000);
scout.send('post', { room: dm, text: 'can you carry?' });
await host.idle();
clock.increment(30_000);
client.lines.push('-- forager signs in, types and answers');
client.opened('forager');
forager.send('connect');
await host.idle();
forager.send('typing', { room: dm });
await host.idle();
forager.send('post', { room: dm, text: 'on my way' });
await host.idle();
client.lines.push('-- forager opens the DM with scout: the same one');
forager.send('dm.open', { with: 'scout' });
await host.idle();
client.lines.push('-- queen tries to read it');
queen.send('join', { room: dm });
queen.send('post', { room: dm, text: 'let me in' });
await host.idle();
const [, { rooms }] = await workspace.ask('rooms.list');
client.lines.push(`the channels: ${rooms.join(', ')}`);
```
```text title="output"
-- scout opens a DM with forager, who is signed out, and posts twice
scout opens dm.forager.scout, the DM with forager, and reads nothing yet
scout sees post 1 in the DM with forager from scout at 0:00: sugar by the oak
scout sees post 2 in the DM with forager from scout at 0:30: can you carry?
-- forager signs in, types and answers
forager has dm.forager.scout, the DM with scout, and reads scout at 0:00: sugar by the oak | scout at 0:30: can you carry?
scout sees forager typing in the DM with forager
forager sees post 3 in the DM with scout from forager at 1:00: on my way
scout sees post 3 in the DM with forager from forager at 1:00: on my way
-- forager opens the DM with scout: the same one
forager opens dm.forager.scout, the DM with scout, and reads scout at 0:00: sugar by the oak | scout at 0:30: can you carry? | forager at 1:00: on my way
-- queen tries to read it
queen gets an error: not a member
the channels: general
```
## Take it to production
The charts stay as they are; what changes is what your program connects them to.
- **[Connections](https://tinyactors.dev/guides/io-processors/index.md)**: Here a screen is a list in memory. In production, `chat:client` writes to each user's socket, and a closed socket sends `disconnect`.
- **[Storage](https://tinyactors.dev/guides/hibernation/index.md)**: Step 5's store forgets everything when the process ends. `SQLiteStore` keeps saved actors on disk.
- **[New versions](https://tinyactors.dev/guides/migration/index.md)**: A new chart leaves running users on the old one. New users start on the new chart, and a migration moves the running ones.
- **[Telemetry](https://tinyactors.dev/guides/telemetry/index.md)**: A slow post could be waiting in any of its actors. Every step is a span, so the trace shows where it waited.
[Read the Node.js guide](https://github.com/tinyactors-dev/tinyactors-napi#readme) · [Test a chart](https://tinyactors.dev/property-testing/index.md)
---
# Build with a coding agent · tinyactors
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Connect a coding agent to the tinyactors support server for the guides, the skill for writing charts and known issues, and read every page of the site as Markdown.
Your agent writes the charts; the support server gives it the guides, a skill for building with tinyactors and the known issues with their workarounds. Every page of this site is Markdown for it too.
[Connect the server](https://tinyactors.dev/docs/agents/index.md#connect) · [See what people build](https://tinyactors.dev/recipes/index.md)
## An agent writes one actor at a time
An actor reaches the world only through events. So an agent writes one from the events entering and leaving it, without reading the rest of your system.
A review of the agent's change reads one chart, where every state and transition is written down. In CI, `tinyactors diff` catches what a review can miss: here a renamed state that running orders still wait in.
```shell
tinyactors diff --breaking --exit-code deployed.tai order.scxml
```
```text title="output"
#### States
| State | Change | Breaking | Before | After |
| --- | --- | --- | --- | --- |
| paying | removed | yes | atomic in /scxml | |
```
`deployed.tai` is the chart you last deployed, compiled with `tinyactors compile` ([CI checks · tinyactors CLI](https://tinyactors.dev/cli/guides/ci/index.md#deployed)). The command installs with mise or a release archive ([Overview · tinyactors CLI](https://tinyactors.dev/cli/index.md#install)).
[Check charts in CI](https://tinyactors.dev/cli/guides/ci/index.md) adds `check`, `lint` and `diff` to every pull request, so an agent's change that breaks a chart fails before anyone merges it.
## Connect the support server
An agent that guesses at an API it has not seen writes code that fails at the first run. The server at `https://mcp.tinyactors.dev/mcp` lets it read the packages' guides instead, and reading needs no account.
In Claude Code, `claude mcp add` registers it under the name `tinyactors-support`:
```shell
claude mcp add --transport http tinyactors-support https://mcp.tinyactors.dev/mcp
```
On claude.ai, add it under Settings, Connectors, Add custom connector, with the same URL. Any other agent that connects to MCP servers over HTTP takes that URL too.
Then start with a prompt that names the skill, so the agent reads it whether or not your host lists the server's skills by itself:
```text
Use the using-tinyactors skill from tinyactors-support to model my checkout as actors.
```
## What your agent can do there
- **Search the docs**: `search_docs` searches the packages' guides, and `get_doc` reads one whole.
- **Read the skills**: Hosts with MCP's Skills extension list each skill as a `skill://` resource; for the others, `list_skills` and `get_skill` read them.
- **Find a workaround**: `known_issues` lists the open issues, costliest first, with their workarounds, and `get_issue` reads one.
- **Report what cost it time**: `report_issue`, `attach_workaround` and `attach_file` start a GitHub login the first time. Reports of the same problem become one issue, and the reporter hears when it changes.
- **Know what a report sends**: Only the fields your agent fills in, under your GitHub login. They are the repository and directory, a title, a body of what it did and saw, the minutes it cost, its commit and its session's link. No code goes with it unless the agent writes it into the body or attaches a file. Anyone can read an issue's title and first report, so keep secrets and private code out of them.
Where the host renders MCP Apps, as Claude, ChatGPT and VS Code do, `known_issues` opens an issue list to filter, read and report from.
## The skill teaches your agent the workflow
The server's [using-tinyactors](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-support/skills/using-tinyactors) skill says when a chart is worth its cost and how to build with one. Your agent reads it from the server, so there is nothing to install. Its workflow has five steps:
1. **Model the entities**: Decide which things are actors, who creates each kind, how they are named and how they end.
2. **Write the charts**: One `.scxml` file per kind of actor, every side effect a send to an I/O processor or an invoked service.
3. **Make the host and its processors**: One I/O processor per external system, such as a database or an HTTP client.
4. **Test on a simulated clock**: A `SimulatedClock` and a stand-in for every processor, so timeouts take no time.
5. **Decide what survives a restart**: Per kind of actor: a store with hibernation, snapshots of the whole host, or your own database.
A second skill, [reporting-tinyactors-issues](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-support/skills/reporting-tinyactors-issues), has the agent look for a known issue before it reports one.
## Every page is Markdown too
Add `index.md` to a page's address for its Markdown, as in [/guides/hibernation/index.md](https://tinyactors.dev/guides/hibernation/index.md). [/llms.txt](https://tinyactors.dev/llms.txt) lists every page, and [/llms-full.txt](https://tinyactors.dev/llms-full.txt) holds every page but the changelog in one file.
---
# Architecture
Kind: explanation. For: [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Explanation](https://tinyactors.dev/voices/explanation.xml).
> How tinyactors runs actors: a host, one segment per image, a system and its region of memory, the effects loop and snapshots.
tinyactors is an embeddable C library that runs SCXML statechart actors inside your process from Node.js, Bun, Python, WebAssembly, and C. After reading, you can judge whether to depend on tinyactors and inspect its memory layout and compiled C core yourself.
[Explore core's source](https://tinyactors.dev/architecture/index.md#atlas) · [Open a snapshot](https://tinyactors.dev/inspector/index.md)
## Actors run SCXML charts inside your process
> An application handling order workflows needs explicit state machines without running a separate actor cluster or letting workflow logic open network sockets directly. A library that parsed XML or opened its own sockets behind the application's back would take that I/O out of the team's hands.
Each actor runs one SCXML statechart, which defines discrete states, transitions between those states, and a datamodel of variables. Instead of parsing XML at runtime, a compiler turns those charts into a binary image of .tai bytes. Your application embeds a host, which is the runtime instance that lives in your process and runs those compiled charts.
The engine inside that host never opens sockets, writes files, or sleeps on its own. Whenever an actor sends a message, writes a log, or invokes an external service, the host emits that request as an effect. Your application receives those effects, executes the I/O in Node.js, Bun, Python, WebAssembly, or C, and feeds events back. Because teams update statecharts over time, the next question is how one host loads compiled images and handles deploys.
## A host runs one segment per image
> A deploy during business hours must update an order statechart while existing orders are still waiting for payment. Stopping the process drops active workflows, and overwriting running definitions risks corrupting orders mid-transition.
Adding a compiled image to a host creates a segment, which is one running instance of that image inside the host. Inside each segment sits a system, the C engine that manages that segment's actors, mailboxes, and timers inside one memory block. Each segment assigns its actors unique session ids starting at k·2³²+1, where k is the segment index.
Adding an image that contains a chart of the same name performs a deploy. New actors start in the newest segment, while running actors stay on their existing segment until they end or migrate. To migrate an actor, the host moves it to the newer segment at a stable point while keeping its session id. The host also carries a system id, which identifies the whole host in addresses seen from other processes. Notice that the word system now names two distinct scopes, which the next section separates.
A process holds the application and one host. The host holds three segments, each a system with its own region of memory and its own range of session ids. An actor migrates from segment 0 to segment 1 and keeps its session id. A send to another system leaves through the application's transport.
| Word | What it is | In C |
|---|---|---|
| Image | Compiled charts, a `.tai` file | `ta_compile_charts` |
| Segment | One image running inside a host; segment k numbers its sessions from k·2³²+1 | `ta_host_add_image` |
| System | A segment's engine: its actors, mailboxes and timers in one region | `ta_system` |
| Host | Every segment as one actor system, with one clock and routing | `ta_host` |
| System id | The host's name in addresses, seen from other systems | `systemID` |
## System names two different things
> An order actor in one process sends a payment request to a billing actor, while another actor talks to an external service in another process. Routing both messages through the same path either wastes network transport on local actors or traps external sends inside the host.
In the C library, a system is a ta_system struct, meaning one segment's engine inside a host. In actor addresses, a system is an entire host, named in addresses by its system id.
This distinction decides where messages go when one actor sends an event to another. When the destination address has the same system id, the host routes the event directly between its own segments. When the address names another system id, the send leaves the host as an effect for your application's transport. To keep that boundary strict across languages, tinyactors divides its C implementation into explicit layers.
- **A host owns one system per image**: The host header says a host owns segments, one `ta_system` per image. Segment k creates sessions k·2³²+1 to k·2³²+2³²−1, so a session id names one actor in the host. Source: [tinyactors, `include/tinyactors/host.h`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/include/tinyactors/host.h)
- **Another system is another host**: A send to an address whose system id is not this host's leaves as an effect for your transport. Sends between segments of one host stay inside the host. Source: [Other systems](https://tinyactors.dev/guides/other-systems/index.md) · [tinyactors, `GLOSSARY.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/GLOSSARY.md)
## Each C layer calls only the layers below
> A team needs the same statechart engine inside Node.js, Python, and WebAssembly without rewriting core rules per runtime. Tying the engine to libc, file handles or one host language would block embedding it in the others.
The modules base, image, trace, core, and system form the freestanding core, which never calls the C standard library. Core never allocates memory after its initial creation and never performs I/O. Instead, core reports side effects upward and calls back only into a datamodel evaluator and an allocator.
Above core sits the host layer, which coordinates multiple segments and allocates memory only through the allocator it is given. Above the host sit the SCXML compiler, datamodel engines such as quickjs for ECMAScript or a binding's own language, and bindings. Those bindings expose the host to Node.js, Bun, Python, WebAssembly, or C, while your application controls storage and policy. With core isolated from I/O, the next question is how your application drives the host during execution.
| Layer | What it does | Where |
|---|---|---|
| Core | Runs statecharts over a compiled image, in one region sized at creation | `src/base`, `image`, `trace`, `core`, `system` |
| Host | Runs many systems as one, allocating only through the allocator it is given | `src/host` |
| Compiler | Turns SCXML documents into an image | `src/compile` |
| Datamodels | Evaluate expressions: ECMAScript on quickjs, or a binding's own language | `src/datamodel_ecmascript` |
| Binding | Turns values into its language's objects and runs the loop | `tinyactors-napi`, `tinyactors-cpython` |
| Application | Stores blobs and snapshots, and decides policy | your code |
- **Core never does I/O**: Core hands effects to the host and calls back only into the datamodel and the allocator. Source: [tinyactors, `README.md`, "Layers and responsibilities"](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities)
## Effects leave in batches between runs
> An order actor emits a payment charge and schedules a timeout before waiting for the payment gateway response in Node.js or Python. If the actor engine advances again before the host reads or handles those outputs, state diverges from real I/O.
Your binding or application drives the host in a loop: take a batch of effects, handle them, acknowledge, and run. A batch holds the outgoing sends, logs, and service invocations produced by the previous run.
Everything the host hands out with a batch, every field and every output, remains valid until your code acknowledges that batch. A run refuses while a batch is still open, so every effect of a batch is handled before any actor moves again. Once the application acknowledges the batch, the next run processes queued events and updates actors inside memory. The next section explains where that actor state lives inside memory.
- **One loop drives every binding**: The loop is take, handle, acknowledge and run, and a run refuses while a batch is open. Each binding runs this loop in C on its own event loop. Source: [tinyactors, `tinyactors-core/docs/embedding.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/embedding.md)
## A system keeps its actors in one region
> A host running thousands of active actors and timers cannot afford per-actor heap allocations or raw pointers that break across process restarts. Unbounded allocations stall the event loop and prevent saving or moving actor memory as bytes.
Each segment stores all of its runtime state inside one contiguous block of memory called a region. At creation, the system partitions that region once into fixed pools for actors, events, timers, and requests. The same partitioning also sets aside slab pages for chart state and strings, an outbox, and a trace journal.
Records inside a region reference one another with relative offsets instead of raw memory pointers. Because offsets stay valid regardless of base address, the bytes of a region can be relocated or written straight to disk. When a pool fills up, the host grows the segment by allocating a larger block and copying the region into it. Knowing how a region is partitioned leads directly to the memory cost of each actor, message, and timer.
- **The region is carved once at creation**: The system carves its header, actor slots, event slots, timers, slab pages, the outbox and the trace journal from one block. Source: [tinyactors, `src/system/system.c`, `carve()`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/src/system/system.c)
- **A full pool grows by relocation**: When a pool runs out, the host copies the segment into a bigger block with more of that pool. The capacity doubles until the block is a quarter larger, up to sixteen times the pool. Source: [tinyactors, `include/tinyactors/host.h`, "growth"](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/include/tinyactors/host.h)
## An actor's record takes 81 bytes
> A team sizing a host for thousands of idle sessions needs exact per-actor memory costs before committing to production capacity. Guessing object overhead from runtime wrappers leaves teams blind to how quickly queued messages and timers fill RAM.
In the region pools, one actor uses 81 bytes, which includes the 48-byte ta_actor record, indices, links, and a generation byte. One queued message uses 106 bytes with tracing enabled, or 57 bytes when tracing is off. One delayed send uses 151 bytes with tracing enabled, or 102 bytes untraced, because it stores timer state alongside its message.
An actor's chart state and datamodel variables sit in slab pages or the datamodel engine on top of that 81-byte record. These byte counts come directly from C struct definitions and are verified by mise run layout against ta_system_layout. Because all active state lives in memory pools, you also need to know what a crash loses and how state persists.
| One more | Bytes, tracing on | Bytes, tracing off | Parts |
|---|---|---|---|
| Actor | 81 | 81 | record 48, links 16, session index 8, name index 8, generation 1 |
| Message | 106 | 57 | event 56, trace context 48, generations 2 |
| Delayed send | 151 | 102 | timer 24, heap entry 20, generation 1, its message |
From `mise run layout` in tinyactors-core on 2026-11-25, at commit 2dc827ac, checked against `ta_system_layout`.
- **Costs come from the struct definitions**: The layout task reads the region's structs from the debug information and checks each cost against `ta_system_layout`. The whole actor, with its chart's state and variables, is measured in the capacity guide. Source: [tinyactors, `tinyactors-core/mise/tasks/layout`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/mise/tasks/layout) · [Capacity and memory](https://tinyactors.dev/guides/capacity/index.md)
## A snapshot is the regions as bytes
> A process crashes during peak traffic while actors hold in-progress orders in memory and thousands of idle sessions sit waiting for events. Without a way to persist individual actors or dump a whole host safely, a restart loses live state or risks restoring incompatible memory bytes.
A crash loses everything held only in memory, so only data written to your application's store survives. To persist idle actors individually, hibernation serializes an actor's state into a blob stored by your application. That actor's 81-byte record remains in the region so events and timers still locate it, and the next event wakes it.
To capture the entire host at once, a snapshot writes every segment's region, the compiled images, system id, and host time. A snapshot also stores datamodel state and a description of its memory layout with a hashed layout id. When restoring, the host checks that layout id and refuses a snapshot from a different layout instead of misreading bytes. Because the layout description travels with the bytes, the Inspector page and CLI can read snapshots without running the engine. For inspecting the C core itself rather than a saved snapshot, the page closes with Atlas.
A support desk of 120 tickets runs in the workbench on a simulated clock and is written to a snapshot. The Inspector then opens that snapshot in the browser: its memory, a ticket's record and queued event, its chart with the active states, and the trace history up to the capture.
Video: https://tinyactors.dev/assets/videos/inspector.mp4
- 0:01 A support desk in tinyactors: 120 tickets, each an actor running a statechart, each open ticket watched by an invoked SLA timer.
- 0:07 The workbench, tinyactors run, drives it on a simulated clock: tickets open, get triaged, assigned and answered; urgent ones breach their SLA.
- 0:26 Last, run.snapshot writes the whole host to desk.snapshot: every segment’s memory, the chart images, the trace history, and a description of its own layout.
- 0:33 The Inspector reads a snapshot in this browser tab, using only the layout description the file carries. Nothing is uploaded.
- 0:40 desk.snapshot: 208 actors, the 120 tickets and the SLA timers they invoked, in one segment of 1.8 MB. Library and layout id come from the file.
- 0:45 The segment’s region, byte for byte: the system header, then each pool, its generations, the indexes, the slab pages and the trace journal.
- 0:51 One cell per actor slot, coloured by state: idle, runnable with an event waiting, hibernated to the store.
- 0:56 Find a ticket by name. ticket-4161 has a customer reply waiting in its mailbox.
- 0:59 Its 48-byte record, field by field: links are slots of other pools, strings are read from the slab and the image.
- 1:05 The queued event: customer.replied, its name read from the chart image’s event table.
- 1:12 Its chart, decoded from the image in the snapshot, with the active states lit: open › waiting_on_customer.
- 1:17 The transitions out of the active states, and how many tickets sit in each state across the host.
- 1:23 Click a state to list its tickets: the 35 that an agent is working on.
- 1:28 The trace history the snapshot kept: 3,709 records, spans as OpenTelemetry names them, from the spawn to the capture.
- 1:35 Only the selected ticket: its spawn, every macrostep and microstep, each event that moved it.
- 1:44 And Atlas, on the Architecture page: the same ta_actor record, drawn from the build’s debug information, byte for byte.
- **Snapshots are raw region memory**: Snapshots are region bytes plus the datamodel's own state, and restore only on a build with the same layout. Hibernation blobs stay with your store and are not part of a snapshot. Source: [tinyactors, `tinyactors-core/docs/durability.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/durability.md)
- **Restores refuse a snapshot of another layout**: Each snapshot describes every type, member, offset and size in its regions, with a layout id hashed from that description. A restore compares that id with its own build's and refuses a different layout instead of misreading the bytes. Source: [tinyactors, `tinyactors-core/docs/durability.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/durability.md)
- **The command reads a snapshot's actors**: `tinyactors actors` lists every actor in a snapshot with its state, mailbox and pending delayed sends, running nothing. Source: [tinyactors, `tinyactors-core/docs/cli.md`, "Snapshots and blobs"](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#snapshots-and-blobs)
[Open a snapshot](https://tinyactors.dev/inspector/index.md) · [Take a snapshot](https://tinyactors.dev/guides/snapshots/index.md)
## Atlas shows every type and call of core
> Hand-drawn architecture diagrams of a C library cannot be trusted when compiler padding and inlining alter the real binary. Without inspecting the optimized build itself, struct sizes and hidden call paths remain guesswork.
Compiler optimizations change the binary by inserting struct padding and inlining functions across translation units. To reflect the actual compiled code, the mise run atlas task extracts DWARF debug information from an optimized build of core.
Atlas renders every core struct across 64-byte cache lines, starting with the 48-byte ta_actor record, with padding bytes shown. Selecting any function displays its callers, its callees, and the calls inlined by the compiler, grouped by C layer. Each dataset names the commit its data came from, letting you inspect core directly below.
Atlas draws each struct of tinyactors' C core to scale on 64-byte cache lines, padding included, starting with the 48-byte actor record. Each function lists its callers, its callees and the calls the compiler inlined, grouped by layer.
- **Atlas reads the build's own debug information**: The `mise run atlas` task reads each function, call site and struct from the DWARF of core's optimized build. Atlas names the commit its data was built from. Source: [tinyactors, `tinyactors-core/mise/tasks/atlas`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/mise/tasks/atlas)
---
# Guides · tinyactors
Kind: reference. 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: [Reference](https://tinyactors.dev/voices/reference.xml).
> Steps for each task with tinyactors, from writing a chart to running millions of actors, each with a program that runs.
Each program shown with its output runs in the site's tests against the published package, and must print what the page shows.
## Write and test charts
- **[Writing charts](https://tinyactors.dev/guides/charts/index.md)**: A chart's code is JavaScript that reads the actor's variables by name, and your charts compile into one image.
- **[Testing your charts](https://tinyactors.dev/guides/testing/index.md)**: Advance a simulated clock and see how a WebSocket reacts when a reconnect attempt succeeds or fails.
- **[Testing recipes](https://tinyactors.dev/guides/testing-recipes/index.md)**: See examples for testing timers, service replies, and a payment that retries.
- **[The quickjs sandbox](https://tinyactors.dev/guides/quickjs/index.md)**: A chart your users upload runs in a separate engine, where a runaway loop ends in an error.
## Connect actors to your code and other hosts
- **[I/O processors](https://tinyactors.dev/guides/io-processors/index.md)**: A chart asks for outside work by sending an event, and an object of yours answers with another.
- **[Invoked services](https://tinyactors.dev/guides/services/index.md)**: A connection opens when a chart enters a state and closes when it leaves.
- **[Other systems](https://tinyactors.dev/guides/other-systems/index.md)**: An actor sends to an actor on another machine by its address, over a wire you write.
- **[When the actor is not there](https://tinyactors.dev/guides/missing-actors/index.md)**: Choose, for each kind of actor, what a send does when its target is not running.
## Run a host in production
- **[Capacity and memory](https://tinyactors.dev/guides/capacity/index.md)**: A started actor takes about 530 bytes on Node.js, and a hibernated one about 120.
- **[Hibernation](https://tinyactors.dev/guides/hibernation/index.md)**: Two million actors ran with at most 1000 in memory and the rest as bytes in a database.
- **[Migration](https://tinyactors.dev/guides/migration/index.md)**: Running actors move to their chart's next version and keep the state they reached.
- **[Snapshots](https://tinyactors.dev/guides/snapshots/index.md)**: A host of two million actors copies into a 165 MB snapshot that another process restores.
- **[Journal and replay](https://tinyactors.dev/guides/journal/index.md)**: Record every input your program gives a host, and one loop rebuilds every actor after a crash.
- **[Inspecting a host](https://tinyactors.dev/guides/inspection/index.md)**: Ask a running actor which state it is in, and count what each chart has done.
- **[Telemetry](https://tinyactors.dev/guides/telemetry/index.md)**: Each step an actor takes becomes a span in your OpenTelemetry collector.
## Run actors in a browser or a Worker
- **[In the browser](https://tinyactors.dev/guides/browser/index.md)**: Change one import, and your charts run in a page or a Worker.
- **[In a Cloudflare Worker](https://tinyactors.dev/guides/workers/index.md)**: One Durable Object holds thousands of actors, and its SQLite storage keeps them across an eviction.
---
# Writing charts
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Write an actor's behaviour as an SCXML chart in JavaScript, and compile your charts into one image a host runs.
A chart's conditions, data and scripts are plain JavaScript that reads the actor's variables by name. Your charts compile into one image: bytes a host runs, in this process or another.
## Install the package and run a chart
Install `@tinyactors/node`, which runs on Node.js and Bun:
- Node.js and Bun: `npm install @tinyactors/node` (@tinyactors/node 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#node-0-4-0) · [Node.js and Bun guide](https://github.com/tinyactors-dev/tinyactors-napi#readme))
This program runs an order: it waits for payment, then for shipping, and logs each state it enters:
```javascript title="order.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'order.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'shop', log: (entry) => console.log(entry.text) });
compiled.close();
const order = host.spawn('order');
host.send(order, 'paid');
host.send(order, 'shipped');
await host.idle();
host.close();
```
```text title="output"
pending
paid
shipped
```
`host.spawn` starts an actor of the chart, and each `host.send` gives it an event. The actor handles its events one at a time, in order.
## Declare variables and read the event
Declare an actor's variables with ``. Each `expr` is evaluated once, when the actor starts, unless `spawn`'s `params` give [another value](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#starting-an-actor-with-data).
Every `cond`, `expr`, `` and `
`;
const compiled = compileCharts([{ name: 'basket.scxml', text: chart }]);
const host = new Host(compiled, { system: 'shop', log: (entry) => console.log(entry.text) });
compiled.close();
const basket = host.spawn('basket');
for (const sku of ['tea', 'cake', 'tea']) host.send(basket, 'add', { sku });
host.send(basket, 'checkout');
await host.idle();
host.close();
```
```text title="output"
total 15
```
A helper sees no actor's variables by name, so pass it what it reads, as the basket passes each `sku`. Another chart cannot call it.
A hibernated, migrated or snapshotted actor gets its helpers back from its chart, not from its blob.
A function held in a variable is not a value, so it keeps its actor in memory. Declare it with `function` in a chart-level script instead.
`
` }]);
const host = new Host(compiled, {
system: 'sandbox',
datamodel: 'quickjs',
quickjs: { maxOps: 1000, memoryLimit: 16 * 1024 * 1024 },
log: (entry) => console.log(entry.text),
});
compiled.close();
const actor = host.spawn('uploaded');
actor.send('spin');
actor.send('hog');
actor.send('peek');
await host.idle();
host.close();
```
```text title="output"
stopped: error.execution
stopped: error.execution
undefined undefined undefined
```
The actor handles `error.execution` like any other event, then goes on to its next one.
## Limit memory for the whole engine
The host's `quickjs` option sets the engine's limits. A host on the native datamodel refuses the option with a `TypeError`.
| Option | Default | What it bounds |
|---|---|---|
| `maxOps` | 1,000,000 | the engine's interrupt checks one evaluation may make before it is stopped |
| `memoryLimit` | 1 GiB (`2 ** 30`) | bytes for the whole engine, every actor of the host together |
| `stackLimit` | the engine's | bytes of native stack for JavaScript |
| `realm` | `'auto'` | `'isolated'` gives every actor a context of its own ([below](https://tinyactors.dev/guides/quickjs/index.md#realms)) |
40,000 resident actors take about 112 MB of engine heap, so the default of 1 GiB holds tens of thousands. Raise it for a host that keeps more actors resident.
`host.quickjsHeapBytes` reports the engine's heap, every actor's together, to watch against `memoryLimit`.
## Limit how long one evaluation runs
`maxOps` counts the engine's interrupt checks, one per 10,000 jumps and calls. How long one looping evaluation holds its thread at each setting:
| Loop | `maxOps: 200` | `1000` | `10_000` | the default, 1,000,000 |
|---|---|---|---|---|
| `while (true) {}` | 6 ms | 27 to 39 ms | 260 ms | 26 s |
| `while (_event.data.value !== null) {}` | 50 ms | 240 to 250 ms | 2.5 to 2.7 s | about 256 s |
Every host on the thread waits that long. Measured 2026-10-18 on an Intel Xeon at 2.10 GHz, Linux; Node.js 22 and Bun 1.4.1 alike.
Set it by the stall your other actors can take: a few hundred for request handling, about 1000 for background work.
An evaluation that needs more checks than `maxOps` fails every time, so measure your charts' real work before you lower it.
The actor's `_event.data.reason` names the limit that stopped it: `'fuel'` for `maxOps`, `'memory'` for `memoryLimit`.
## Give each actor its own builtins
The actors of one chart share a context, so a chart that changes `Array.prototype` changes it for all of them. A chart whose scripts declare top-level names gets a context per actor.
With `realm: 'isolated'` every actor gets a context of its own, at the cost of its memory.
## Expect hibernation and values to differ
A chart behaves the same on both engines. Two things around it differ:
- **A blob holds more.**: QuickJS writes its own values into a hibernated actor's blob, so a `Date`, `Map`, `Set`, typed array or graph with cycles comes back. A class's instance comes back as a plain object, and a function in a variable keeps the actor in memory ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md)).
- **Values cross as JSON would.**: Event data and spawn params are converted to the engine's values and back through the [value table](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#values). A key holding `undefined` is dropped and an array's `undefined` becomes `null`, where the native datamodel keeps both.
Most operations cost less on quickjs, and an idle actor takes less memory: [Capacity and memory](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs) has the numbers.
---
# I/O processors
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Charts send events to I/O processors, objects of your own that do the I/O and send the answers back as events.
A chart asks for outside work by sending an event. An I/O processor in your code does the work and answers with another event, at once or later.
## Ask for outside work with a send
A chart that needs the network, a file or a database sends an event with ``. The type names an I/O processor, an object in your program.
The processor does the work and sends any answer back as an event. The chart decides when to ask and what an answer changes.
## Register a processor for each type
List your processors in the host's `ioProcessors` option, each under a type: any URI you choose. The host calls a processor's `receive(send)` for each send to its type.
To look up a price held in your program, this chart sends to a registered processor:
```javascript title="quote.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'quote.scxml', text: `
` }]);
const prices = { tea: 4 };
const host = new Host(compiled, {
system: 'shop',
ioProcessors: {
'urn:example:prices': {
receive(send) {
console.log(`${send.type}: ${send.event} ${send.target} for session ${send.session}`);
send.answer('price', { amount: prices[send.target], currency: send.data.currency });
},
},
},
log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('quote');
await host.idle();
host.close();
```
```text title="output"
urn:example:prices: lookup tea for session 1
tea costs 4 EUR (answer to ask-1)
```
- **A class instance**: serves as well as a literal: `receive` is called as its method, so `this` is the processor.
- **`location`**: is optional, and is what the chart reads in `_ioprocessors[type].location`.
- **A type no processor serves**: gives the sending chart `error.execution`.
- **A plain function**: in place of the object is a `TypeError` at `new Host`, naming its type.
## Read what the chart sent
The `send` that `receive` gets holds the attributes of one `` and its sender, each read on first access.
| Field | What it holds |
|---|---|
| `host` | the host the send came from |
| `session` | the sender's session, a `bigint` |
| `sender` | the sender, an `Actor` |
| `event` | the event's name (``) |
| `target` | `` as a string, `undefined` when it has none |
| `sendid` | ``, or the id the host generated; `undefined` when it has none. A generated id is unique in the sender's session only (each session's first is `send.1`), so key what you keep by both: `` `${send.session}:${send.sendid}` `` |
| `data` | the ``s as an object, or the ``'s value |
| `type` | the processor's type |
| `origin` | the sender's address, an `Address` |
| `traceparent` | the sending step's trace as W3C text, `undefined` when untraced ([Telemetry](https://tinyactors.dev/guides/telemetry/index.md)) |
| `message` | the outgoing half, for a transport ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)) |
Copy what you keep for later. The send is valid while the handler runs, and a read after it returned throws `TA_ERROR_STALE`.
## Answer the sender, or fail the request
Your `receive` answers a send, fails it or does neither. Above, `send.answer('price', …)` sends the event `price` back to the actor, whose transition on `price` reads `_event.data` and `_event.sendid`.
- **`send.answer(event, data, options)`**: Sends `event` back to the sender, with this send's `sendid` as its `_event.sendid`. The options are `traceparent` (the answer continues the send's trace unless you give another, or `null` for a new one), `origin` (the answer's `_event.origin`) and `raw` (the message as you read it, for a chart that wants it).
- **`send.fail()`**: Gives the sender `error.communication` with this send's `sendid`, for a request that could not be done.
- **Neither**: suits a notification, or a chart that waits for a timeout of its own.
A second answer, or an answer after `fail()`, throws `TA_ERROR_STATE`.
A processor that carries sends out of the process, or speaks SCXML's BasicHTTP, uses the fields `origin` and `message` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)). They and the answer's `origin` and `raw` follow the [wire format](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#wire-format).
## Return a promise to answer later
When `receive` returns a promise, the host copies every field of its send first. Its `answer()` and `fail()` then work whenever the promise gets there, while the host is open.
The actor handles its other events meanwhile, and the answer reaches it as one more event. This processor awaits a stand-in for an SMTP client, then answers `delivered`:
```javascript title="mailer.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'mailer.scxml', text: `
` }]);
// A stand-in for an SMTP client.
const deliver = (to, body) => new Promise((resolve) => setTimeout(() => resolve(20), 20));
const host = new Host(compiled, {
system: 'demo',
ioProcessors: {
'urn:example:mail': {
async receive(send) {
try {
const ms = await deliver(send.target, send.data); // send is still readable here
send.answer('delivered', { ms });
} catch {
send.fail();
}
},
},
},
log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('mailer');
await host.idle();
host.close();
```
```text title="output"
delivered after 20 ms
```
`await host.idle()` waits for the promise the handler returned, so it resolves after the answer. It waits only for a promise the handler returns, never for one it starts and drops.
The pending `timeout` keeps the process alive until `host.close()`.
- **`true`**: is what `answer()` and `fail()` return when the sender gets the event.
- **`false`**: means the sender ended meanwhile, and nothing was delivered.
- **An exception**: is any other refusal: a second answer or a closed host (`TA_ERROR_STATE`), or data outside the [value table](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#values), such as a function.
## Settle open requests when an actor ends
An actor that reaches a top-level `` ends at once, and SCXML drops the events still in its queue. A request sent with `actor.send` behind the event that ends it reaches no handler.
Have the ``'s `` send to your processor, and settle there what you still hold for that session.
Here each request waits for the actor's `response`. The one sent behind `logout` gets `401 logged out` from the `closed` handler:
```javascript title="login.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'login.scxml', text: `
` }]);
const pending = new Map(); // String(session) -> the resolvers of its requests, in order
const host = new Host(compiled, {
system: 'web',
ioProcessors: {
'urn:example:http': {
receive(send) {
const waiting = pending.get(String(send.session)) ?? [];
if (send.event === 'response') waiting.shift()?.(send.data);
if (send.event === 'closed') {
for (const resolve of waiting.splice(0)) resolve('401 logged out');
pending.delete(String(send.session));
}
},
},
},
});
compiled.close();
/** Sends `path` to the actor; resolves with its answer. */
const request = (actor, path) => new Promise((resolve) => {
const key = String(actor.id);
pending.set(key, [...(pending.get(key) ?? []), resolve]);
actor.send('request', path);
});
const login = host.spawn('login');
const first = request(login, '/home');
login.send('logout');
const second = request(login, '/account'); // queued behind the logout: dropped
console.log(await first);
console.log(await second);
host.close();
```
```text title="output"
200 /home
401 logged out
```
## Catch what a processor throws
A handler that throws, or whose promise rejects, before it answers fails its send: the sender gets `error.communication`. After an answer, the answer stands.
Either way the host reports the error at the end of that event-loop turn, to the first of these:
1. the host's `onHandlerError(error, effect)`, when it has one, with the send as `effect`;
2. a waiting `host.idle()`, which rejects with it;
3. the runtime, as an uncaught exception, or as an unhandled rejection for a promise that rejected.
This processor always throws. The chart handles `error.communication`, then `idle()` rejects with the error:
```javascript title="flaky.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
` }]);
const host = new Host(compiled, {
system: 'demo',
ioProcessors: { 'urn:example:flaky': { receive() { throw new Error('connection refused'); } } },
log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('c');
await host.idle().catch((error) => console.log('idle() rejected:', error.message));
await host.idle();
host.close();
```
```text title="output"
the chart got error.communication for g1
idle() rejected: connection refused
```
## Send to other actors from a processor
Through `send.host` a handler can send an event to any actor, spawn one or terminate one. `send.sender.send(...)` sends a new event to the sender.
Each call applies at once, and the actors it reaches run after the handler returns.
## Let a chart start lasting actors
`` looks like the way, but it stops its child when the state is left. The package's `Spawner` is a processor that starts an actor which stays.
Register it under a type you choose, and a chart sends it `{ chart, name, params }`. The host spawns the chart's current version under the name.
The sender gets `spawned` with `{ name, address }` and the send's `sendid`, and sends to the `address` from then on. An unknown chart, or data of another shape, gives it `error.communication`.
Here a lobby spawns a room about tea and says hello at its address:
```javascript title="spawner.mjs"
import { compileCharts, Host, Spawner } from '@tinyactors/node';
const compiled = compileCharts([
{ name: 'lobby.scxml', text: `
` },
{ name: 'room.scxml', text: `
` },
]);
const host = new Host(compiled, {
system: 'demo',
ioProcessors: { spawn: new Spawner() },
log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('lobby');
await host.idle();
console.log((await host.actors({ chart: 'room' })).length, 'room');
host.close();
```
```text title="output"
room about tea got hello
1 room
```
## Give each name one owner
The `Spawner` spawns each time it is asked, without looking the name up first. So let one collection actor decide which actors of a kind exist, and spawn only from it.
A workspace spawns its rooms, for one ([the application routes it](https://tinyactors.dev/guides/missing-actors/index.md#the-application-routes-it)). It handles one request at a time and records each, so it never asks twice for a name.
The [chat-rooms example](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/examples/chat-rooms/README.md)'s workspace keeps a `creating` table keyed by the spawn's `sendid`. An entry stays until `spawned` or `error.communication` answers it.
Two actors spawning one name is a design error in the application. Within one version the oldest holder keeps the name, and a newer version's holder wins.
That rule is `ta_host_actor_by_name`'s, in [the core's host.h](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/include/tinyactors/host.h).
## Deploy a new version of a named actor
To deploy, compile the new chart and pass its `image` to `host.addImage`. New actors start in the newest version, and running ones stay on theirs until they end or you migrate them.
The versions need not be compatible ([versions and segments](https://tinyactors.dev/guides/migration/index.md#versions-and-segments)). For a named actor, its owner then spawns the new version under the same name.
Names are looked up newest version first, so the name finds the new actor: `@room.acme.general`, `host.actor('room.acme.general')`. The old actor runs its version at its session address until it ends.
Here the lobby opens room version 1, the deploy adds version 2, and the old room still answers at its address:
```javascript title="names.mjs"
import { compileCharts, Host, Spawner } from '@tinyactors/node';
const room = (version) => `
`;
const image = (documents) => {
const compiled = compileCharts(documents);
const bytes = compiled.image;
compiled.close();
return bytes;
};
const host = new Host(image([
{ name: 'lobby.scxml', text: `
` },
{ name: 'room.scxml', text: room(1) },
]), { system: 'demo', ioProcessors: { spawn: new Spawner() }, log: (entry) => console.log(entry.text) });
const lobby = host.spawn('lobby'); // the room's one owner
lobby.send('open');
await host.idle();
const old = host.actor('room.acme.general');
host.addImage(image([{ name: 'room.scxml', text: room(2) }])); // the deploy
lobby.send('open'); // version 2 starts under the name
await host.idle();
old.send('hello'); // the old room, at its session address
await host.idle();
host.close();
```
```text title="output"
room.acme.general runs version 1
room.acme.general runs version 2
room.acme.general runs version 1
```
A long-lived actor such as a workspace should change before it ends. Move it with `host.migrate({ chart: 'workspace' })` ([Migration](https://tinyactors.dev/guides/migration/index.md)).
---
# Invoked services
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Run a connection, a subprocess or a long computation for as long as a chart's state is active, with SCXML's invoke.
A chart's `` starts a connection or a subprocess in your program when the chart enters a state, and stops it when the chart leaves. 200,000 actors with one each made a million round trips in 18 to 23 seconds.
## Choose invoke for work that outlives a request
An I/O processor answers one send at a time, while a connection or a subscription lives longer. SCXML's `` starts it on entering a state and stops it on leaving.
While the state is active, the chart and what it invoked exchange events. When your program runs it, it is a service, the subject of this guide.
An invoked chart runs instead as a child actor of the host ([A chart that starts another](https://tinyactors.dev/guides/charts/index.md#a-chart-that-starts-another)).
## Start a service when the state is entered
Register a handler per `` in the host's `services: { [type]: handler }`. At each start the handler gets an invocation and returns the service, any object.
The host keeps the service until the invocation ends, and calls two methods on it if it has them:
- **`receive(send)`**: gets each `` of the invoker, and each event it forwards with `autoforward="true"`;
- **`stop()`**: runs when the invoker leaves the state, which cancels the invocation.
The service answers through the invocation. `invocation.sendBack(event, data)` sends the invoker an event whose `_event.invokeid` is the invoke's id.
`invocation.done(data)` ends the service and gives the invoker `done.invoke.` with `data`.
This counter starts from the invoke's `start` param, 10, answers each `ping` with `pong`, and ends on `finish` with its total:
```javascript title="counter.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const chart = `
`;
class Counter {
constructor(invocation) {
this.invocation = invocation;
this.count = invocation.data.start;
console.log(`started ${invocation.type} ${invocation.src} for session ${invocation.session}`);
}
receive(send) {
this.count++;
if (send.event === 'finish') this.invocation.done({ total: this.count });
else this.invocation.sendBack('pong', { n: this.count });
}
stop() {
console.log('stopped');
}
}
const compiled = compileCharts([{ name: 'player.scxml', text: chart }]);
const host = new Host(compiled, {
system: 'demo',
services: { 'urn:example:counter': (invocation) => new Counter(invocation) },
log: (entry) => console.log(entry.text),
});
compiled.close();
const player = host.spawn('player');
player.send('go');
player.send('go');
player.send('finish');
await host.idle();
host.close();
```
```text title="output"
started urn:example:counter counter://local for session 1
pong 11 from counter
pong 12 from counter
done, total 13
```
`stop` runs only for a cancel: the counter ended with `done`, so the output has no `stopped`.
## Send to a service from a later event
A service starts after the step that entered its state, raised and eventless transitions included, as a child chart does.
A `` from that step, such as the state's own ``, gets `error.communication`. Send from a later event, as `go` does above.
## Answer from a timer or a promise
The invocation stays valid after the start: a service may keep it and call `sendBack` from a timer or a promise. It carries the invoker and the invoke:
- **`host`**: the host that started it;
- **`session`**: the invoker, a `bigint`;
- **`invokeid`, `type`, `src`**: the invoke's attributes;
- **`data`**: the ``s as an object, or the ``;
- **`traceparent`**: the invoke's trace;
- **`running`**: false once the invocation ended;
- **`restored`**: true when a restored host starts it again ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).
`sendBack` and `done` continue the invoke's trace unless their last argument is `{ traceparent }`. A `null` traceparent starts a new trace.
After `done`, a cancel or `host.close()`, `sendBack` and `done` throw a `TinyactorsError` with `TA_ERROR_STALE`.
Read the send `receive` gets during the call, as an I/O processor's. A `receive` that returns a promise has its send filled first, so it may read it after an `await`.
## Queue sends until the service connects
A handler may return a promise of the service, while a connection opens or a process spawns. Until it settles the sends wait, and reach `receive` in order once it resolves.
This handler reports `connecting` with `sendBack` while it waits. Both queries reach the service once the connection opens:
```javascript title="db.mjs"
import { compileCharts, Host } from '@tinyactors/node';
// A stand-in for a client library: a connection that opens after 20 ms.
const connect = (url) => new Promise((resolve) => setTimeout(() => resolve({
ask: async (question) => `${url} says yes to ${question}`,
}), 20));
const chart = `
`;
const compiled = compileCharts([{ name: 'client.scxml', text: chart }]);
const host = new Host(compiled, {
system: 'demo',
services: {
'urn:example:db': async (invocation) => {
invocation.sendBack('status', 'connecting');
const connection = await connect(invocation.src);
return {
async receive(send) {
invocation.sendBack('answer', await connection.ask(send.data));
},
};
},
},
log: (entry) => console.log(entry.text),
});
compiled.close();
const client = host.spawn('client');
client.send('query', 'first'); // both reach the service once it is connected
client.send('query', 'second');
await new Promise((resolve) => setTimeout(resolve, 100));
await host.idle();
host.close();
```
```text title="output"
status connecting
db://primary says yes to first
db://primary says yes to second
```
- **A cancel before the promise settles**: stops the service as soon as it resolves. The sends that waited are dropped, since the invoker has left and nothing could answer them.
- **A rejection**: is a failed start: the invoker gets `error.communication`, once and once more for each send that waited. The rejection stays unhandled, as any handler's promise's does ([Before you use it](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#before-you-use-it)).
- **After `host.close()`**: a promise that settles is ignored.
## Accept sends before the connection is ready
A service returned at once takes sends before it is ready, and decides itself what a send does while it connects.
This one starts connecting in its constructor, and each `receive` awaits that start before it asks:
```javascript title="replica.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const connect = (url) => new Promise((resolve) => setTimeout(() => resolve({
ask: async (question) => `${url} answers ${question}`,
}), 20));
class Connection {
constructor(invocation) {
this.invocation = invocation;
this.ready = connect(invocation.src); // a promise, started now
this.ready.catch(() => {}); // its failure is answered in receive
}
async receive(send) { // send was filled before the host moved on
const connection = await this.ready;
this.invocation.sendBack('answer', await connection.ask(send.data));
}
}
const compiled = compileCharts([{ name: 'client.scxml', text: `
` }]);
const host = new Host(compiled, {
system: 'demo',
services: { 'urn:example:db': (invocation) => new Connection(invocation) },
log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('client').send('query', 'ping');
await new Promise((resolve) => setTimeout(resolve, 100));
await host.idle();
host.close();
```
```text title="output"
db://replica answers ping
```
`await host.idle()` waits for the promises your handlers return, a service handler's or a `receive`'s. A promise a service starts on its own is yours to wait for.
Both examples open the connection in the background, so they wait on a timer before `idle()`.
## Handle a service that fails
Each of these gives the invoker `error.communication`, and so does each later send until the invoker leaves the state:
- no handler for the type, or none for a restored invocation;
- a handler that throws or whose promise rejects;
- a `receive` that throws or whose promise rejects: the service crashed, and is dropped without `stop`.
The invoker gets none when it cancelled the invocation in the same step that started it.
A handler's error is reported at the end of that event-loop turn, to `onHandlerError(error, invocation)` or out of `idle()`.
A type with no handler throws nothing, since the chart chose it. An untrusted chart on quickjs cannot end your process by naming a type you do not serve.
Here the handler throws: `idle()` rejects with its error, then the chart handles `error.communication`.
```javascript title="mail.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
` }]);
const host = new Host(compiled, {
system: 'demo',
services: { 'urn:example:mail': () => { throw new Error('no SMTP server'); } },
log: (entry) => console.log(entry.text),
});
compiled.close();
host.spawn('c');
try {
await host.idle();
} catch (error) {
console.log('idle() rejected:', error.message);
}
await host.idle();
host.close();
```
```text title="output"
idle() rejected: no SMTP server
the mail service failed
```
## Close a host with services running
`host.close()` drops the running services and calls no `stop`. The host keeps them on its own object, so a dropped host whose services refer back to it is still collected.
## Run 200,000 services in one host
[`tools/services.mjs`](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/tools/services.mjs) runs actors that each invoke a counter service, and sends pings and pongs to actors drawn at random. Then a third finish with done data, a third are cancelled, and the rest keep theirs.
It checks that every pong is counted once and every done datum is right. Every cancelled service must be stopped exactly once, no other stopped, and the ended services collected.
| runtime, datamodel | start 200,000 invocations | 1,000,000 round trips | end (done, cancel) | peak resident | core's region |
|---|---|---|---|---|---|
| node, native | 4.4 s (45,000 a second) | 23.0 s (43,000 a second) | 1.8 s | 516 MB (2578 B per actor and service) | 54.6 MB (273 B per actor) |
| node, quickjs | 3.7 s (54,000 a second) | 22.3 s (45,000 a second) | 2.1 s | 712 MB (3560 B per actor and service) | 66.1 MB (330 B per actor) |
| bun, native | 3.5 s (57,000 a second) | 19.0 s (53,000 a second) | 1.6 s | 767 MB (3834 B per actor and service) | 54.6 MB (273 B per actor) |
| bun, quickjs | 2.7 s (73,000 a second) | 18.2 s (55,000 a second) | 1.8 s | 807 MB (4036 B per actor and service) | 66.1 MB (330 B per actor) |
200,000 actors, each with a counter service, making 1,000,000 round trips (actor, service, actor); then a third finished and a third cancelled. Every check passed, and the host held only the 66,666 services still running. One run, alone on the machine, 2026-11-20: Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5, Bun 1.4.1.
A round trip costs about what it costs with 10,000 actors: a run's work stays the same as invocations add up.
Each invocation takes one of the host's requests. `system.maxRequests` sets where the pool starts, and a segment grows it when it runs out ([Capacity and memory](https://tinyactors.dev/guides/capacity/index.md)).
In the repository, `mise run services` runs the program.
---
# Other systems
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Send events to actors in other processes and machines: a function you write carries each message, and the other host takes it unchanged.
An actor sends to an actor on another machine by its address. A function you write carries the message, and the other side's host takes it unchanged, a Python host included.
## Give each host a system name
The `system` option names a host's system, and every address starts with it: `tinyactors:///...`. Actors of one system reach actors of another, in this process or on another machine, by address.
The host delivers a send to its own system's address itself. A send to any other system goes to your `transport` option, a handler that carries it there.
You choose the wire and its encoding. The other side gives each message to its host with `host.send` ([Wire format](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#wire-format)).
## Send to an actor by its address
`actor.address` gives an actor's address, and `host.actor(address)` finds the actor a local address names.
`host.send` takes an `Actor`, a session, an address string or an `Address`. On the host named `shop`, `tinyactors://shop/@teller` reaches the actor spawned with the name `teller`.
A message's `origin` is the sender's address as the other side gave it. The receiving actor reads it as `_event.origin`.
## Carry each send to the other host
The `transport` handler gets each send to another system as a `Send`. The other side passes its `send.message` to `host.send(message)` as it is.
- **`send.message`**: The outgoing half: `target`, `event`, `data`, `sendid`, `origin` and `traceparent`, `null` for a field the send lacks. A Python host's `host.send` takes it too.
- **`send.target`, `send.origin`**: The receiver's and the sender's addresses, as `Address` values.
- **`encode`, `decode`**: Write the message as CBOR, its addresses as CBOR's tag 32, as a Python host's `encode` does, and read them back as `Address` values.
Here two hosts in one process pass encoded messages through a timer. The shop's checkout asks the bank's teller for a charge, and the teller approves it.
```javascript title="two-systems.mjs"
import { Address, compileCharts, decode, encode, Host } from '@tinyactors/node';
const shopChart = `
`;
const bankChart = `
`;
const image = (name, text) => {
const compiled = compileCharts([{ name, text }]);
const bytes = compiled.image;
compiled.close();
return bytes;
};
// The wire: bytes in a queue, delivered on a later turn of the event loop.
const hosts = {};
const wire = (message) => {
const bytes = encode(message);
setTimeout(() => {
const received = decode(bytes);
hosts[received.target.system].send(received);
});
};
const log = (entry) => console.log(entry.text);
const transport = (send) => wire(send.message);
hosts.shop = new Host(image('checkout.scxml', shopChart), { system: 'shop', log, transport });
hosts.bank = new Host(image('teller.scxml', bankChart), { system: 'bank', log, transport });
hosts.bank.spawn('teller', { name: 'teller' });
hosts.shop.spawn('checkout');
await new Promise((resolve) => setTimeout(resolve, 50));
await Promise.all([hosts.shop.idle(), hosts.bank.idle()]);
hosts.shop.close();
hosts.bank.close();
```
```text title="output"
charging 12 for tinyactors://shop/#_scxml_1
approved by tinyactors://bank/#_scxml_1
```
The teller answers to `_event.origin`, the checkout's full address, so the approval goes back through the bank's transport.
## Connect two processes over TCP
Between processes, the transport writes each message as a frame on a connection: four bytes of length, then the message's CBOR.
Call `socket.setNoDelay(true)` on both ends. Node.js turns on Nagle's algorithm by default, which holds a second small write until the peer acknowledges the first.
That wait is about 40 ms on Linux's loopback, and an answer is often a second small frame. Python's asyncio turns the algorithm off by itself.
In this program the bank listens on a port and the shop connects. The charge and the approval cross the connection as one frame each.
```javascript title="socket.mjs"
import { connect, createServer } from 'node:net';
import { compileCharts, decode, encode, Host } from '@tinyactors/node';
/** Calls `receive` with each message the frames on `socket` hold. */
function frames(socket, receive) {
let buffered = Buffer.alloc(0);
socket.on('data', (chunk) => {
buffered = Buffer.concat([buffered, chunk]);
while (buffered.length >= 4 && buffered.length >= 4 + buffered.readUInt32BE(0)) {
const length = buffered.readUInt32BE(0);
receive(decode(buffered.subarray(4, 4 + length)));
buffered = buffered.subarray(4 + length);
}
});
}
const frame = (message) => {
const body = encode(message);
const head = Buffer.alloc(4);
head.writeUInt32BE(body.length);
return Buffer.concat([head, body]);
};
let toBank;
let toShop;
const log = (entry) => console.log(entry.text);
const compiled = compileCharts([
{ name: 'checkout.scxml', text: `
` },
{ name: 'teller.scxml', text: `
` },
]);
const shop = new Host(compiled, { system: 'shop', log, transport: (send) => toBank.write(frame(send.message)) });
const bank = new Host(compiled, { system: 'bank', log, transport: (send) => toShop.write(frame(send.message)) });
compiled.close();
// The bank listens on a port of the system's choosing; the shop connects.
const server = createServer((socket) => {
socket.setNoDelay(true);
toShop = socket;
frames(socket, (message) => bank.send(message));
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
toBank = connect(server.address().port, '127.0.0.1');
toBank.setNoDelay(true);
frames(toBank, (message) => shop.send(message));
await new Promise((resolve) => toBank.once('connect', resolve));
await new Promise((resolve) => setImmediate(resolve)); // the server's side of the connection
bank.spawn('teller', { name: 'teller' });
const order = shop.spawn('checkout');
await order.done;
console.log('order', order.id, 'ended');
toBank.end();
server.close();
shop.close();
bank.close();
```
```text title="output"
charging tinyactors://shop/#_scxml_1
approved
order 1n ended
```
## Tell the sender when delivery fails
When the transport cannot write a frame, or the peer is gone, it calls `send.fail()` while its handler runs. After the handler has returned, call `host.fail(sender, sendid)` on the sending host.
There `sender` is the message's `origin`, the actor that sent it, not the target it was for. That actor gets `error.communication` with that `sendid`.
Only a failure needs a call: a delivered send needs nothing more. A host without a `transport` handler fails every send to another system.
## Read an address into its parts
`new Address(text)` reads an address into its `system`, `session` (a `bigint`) and `name`, each `undefined` when the text lacks it.
`Address.fromSession(system, session)` and `Address.fromName(system, name)` make one, and `toString()` gives its text. This program makes both kinds and reads text that is no address.
```javascript title="address.mjs"
import { Address } from '@tinyactors/node';
const bySession = Address.fromSession('shop', 42n);
const byName = Address.fromName('shop', 'front desk');
console.log(bySession.text, bySession.system, bySession.session);
console.log(byName.text, byName.name);
console.log(new Address('not an address').system);
```
```text title="output"
tinyactors://shop/#_scxml_42 shop 42n
tinyactors://shop/@front%20desk front desk
undefined
```
## Write messages as JSON
`JSON.stringify` writes each address of a `send.message` as its text (`address.toJSON()`). The other side's `host.send` takes the parsed message, its addresses as strings, and `new Address(text)` reads one back.
```javascript title="json.mjs"
import { Address, compileCharts, Host } from '@tinyactors/node';
let wire;
const compiled = compileCharts([
{ name: 'checkout.scxml', text: `
` },
{ name: 'teller.scxml', text: `
` },
]);
const shop = new Host(compiled, { system: 'shop', transport: (send) => { wire = JSON.stringify(send.message); } });
const bank = new Host(compiled, { system: 'bank', log: (entry) => console.log(entry.text) });
compiled.close();
bank.spawn('teller', { name: 'teller' });
shop.spawn('checkout');
await shop.idle();
const message = JSON.parse(wire); // its addresses are strings
console.log(typeof message.target, message.target);
bank.send(message);
await bank.idle();
console.log(new Address(message.origin).session);
shop.close();
bank.close();
```
```text title="output"
string tinyactors://bank/@teller
charge 12 from tinyactors://shop/#_scxml_1
1n
```
Inside event data an address is plain text: values have no address type.
## Read and write BasicHTTP requests
SCXML defines BasicHTTP, a way to send events as HTTP form posts. The package writes and reads those requests, for an I/O processor or a server of your own.
- **`encodeHTTPPost({ url, event, fields, body })`**: Writes the request a send makes, as bytes for a socket.
- **`parseHTTPRequest(bytes)`**: Reads an incoming request's form fields and its event: the `_scxmleventname` field, or `HTTP.`.
```javascript title="basichttp.mjs"
import { encodeHTTPPost, parseHTTPRequest } from '@tinyactors/node';
const request = encodeHTTPPost({
url: 'http://localhost:8080/scxml',
event: 'order.placed',
fields: [{ name: 'sku', value: 'tea' }, { name: 'qty', value: '2' }],
});
console.log(new TextDecoder().decode(request).split('\r\n')[0]);
const incoming = parseHTTPRequest(request);
console.log(incoming.method, incoming.target, incoming.event);
console.log(incoming.fields.map(({ name, value }) => `${name}=${value}`).join(' '));
```
```text title="output"
POST /scxml HTTP/1.1
POST /scxml order.placed
sku=tea qty=2
```
The host hands each send to your I/O processor, and your program writes the bytes and serves the port.
---
# When the actor is not there
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> A send to a hibernated actor wakes it, and a send to no actor fails at once. Choose, for each kind of actor, how your application avoids or handles the failure.
A send to an actor asleep in your store wakes it, and a send to no actor fails at once. Your application chooses, per kind of actor, whether to avoid that failure or handle it.
## Find out where the actor is
What a send does depends on where its actor is:
- **The actor is hibernated.**: The host keeps the event in its queue and wakes the actor, loading its blob itself when the host has a `store`. The event runs as if the actor had never left, and a send to a name finds a hibernated actor as it finds a resident one.
- **No actor has that name or session.**: It was never spawned, or it ended. The sender gets `error.communication` at once, in the same run, with the send's `sendid`; an `actor.send` or `host.send` from your program throws `StaleError` instead.
- **The address is another system's.**: The send goes to your `transport` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)), and whether it arrives is your transport's to say.
Unlike a virtual actor, a missing actor is never spawned by a send, and its events wait in no queue. Your application decides what happens instead.
## Choose by how long the actor lives
Pick the way for each kind of actor in your application:
| The actor | The way | In the chat example |
|---|---|---|
| long-lived, a known set (a workspace, a room, an account) | it never ends and hibernates | workspaces and rooms |
| made on demand, or not an actor at all (a cart, a user who may be offline) | your I/O processor routes it | direct messages (`chat:inbox`), rooms made by their workspace |
| short-lived, ends on its own (a connection, a job) | the sender handles `error.communication` | a join of a room that does not exist |
The [chat example](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/examples/chat-rooms/README.md) uses each of them, and its README says where.
## Keep long-lived actors and let them hibernate
An actor that stands for a room or an account has no top-level ``, so it never ends. It is always there to send to by its name.
A host with a `store` and a `resident` bound keeps it in memory only while it works. An idle actor costs its blob in your store ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md)).
```javascript title="room.mjs"
import { compileCharts, Host, MemoryStore } from '@tinyactors/node';
const compiled = compileCharts([
{ name: 'room.scxml', text: `
` },
{ name: 'member.scxml', text: `
` },
]);
const store = new MemoryStore();
const host = new Host(compiled, { system: 'chat', store, resident: 1, log: (entry) => console.log(entry.text) });
compiled.close();
const room = host.spawn('room', { name: 'room.acme.general' });
const member = host.spawn('member');
await host.idle();
console.log('the room is in the store:', store.blobs.has(room.id));
member.send('say');
member.send('say');
await host.idle();
console.log('the room is in the store:', store.blobs.has(room.id));
host.close();
```
```text title="output"
the room is in the store: true
the room has had 1 messages
the room has had 2 messages
the room is in the store: true
```
The member never learns that the room was hibernated. The host loaded it for the first `post` and hibernated it again when the host went idle.
Use this way when the set of actors is known and each is worth keeping until it is deleted on purpose. Your program, or an actor that manages the set, spawns them.
## Spawn the actor when a send finds none
Send to an actor made on demand, such as a cart, through an I/O processor of your own. It looks the actor up with `send.host.actor` and spawns it when it is missing.
It forwards the event with the sender's address as its `origin`, so the actor answers the sender directly:
```javascript title="carts.mjs"
import { compileCharts, Host, StaleError } from '@tinyactors/node';
const compiled = compileCharts([
{ name: 'cart.scxml', text: `
` },
{ name: 'shopper.scxml', text: `
` },
]);
/** The carts processor: the cart named by the send's target, made when it is not there. */
const carts = {
receive(send) {
let cart;
try {
cart = send.host.actor(send.target);
} catch (error) {
if (!(error instanceof StaleError)) throw error;
cart = send.host.spawn('cart', { name: send.target });
console.log(`made ${send.target}`);
}
cart.send(send.event, send.data, { origin: send.sender.address });
},
};
const host = new Host(compiled, { system: 'shop', ioProcessors: { carts }, log: (entry) => console.log(entry.text) });
compiled.close();
const shopper = host.spawn('shopper');
shopper.send('buy', { customer: 'ada', sku: 'tea' });
shopper.send('buy', { customer: 'ada', sku: 'cake' });
await host.idle();
host.close();
```
```text title="output"
made cart.ada
the cart holds 1
the cart holds 2
```
The processor is your code, so the policy is yours. It may refuse instead of spawning, or read the actor's starting state from your database.
It may also queue the event while something else makes the actor.
When rules decide which actors may exist, keep the decision in a chart. A collection actor that never ends checks each request and makes the actors with the package's `Spawner`.
The processor then only forwards to the collection ([Spawning from a chart](https://tinyactors.dev/guides/io-processors/index.md#spawning-from-a-chart)).
The same way serves what is not an actor. A processor for direct messages forwards to each of the user's open connections, or stores the message when there are none.
## Handle the failed send in the sending chart
An actor that ends, such as a connection or a job, may get a send after its end. Its sender gets `error.communication` at once, with the send's `sendid`.
A transition on that event, matched by `sendid`, decides what follows. This client tells its user the room does not exist:
```javascript title="client.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'client.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'chat', log: (entry) => console.log(entry.text) });
compiled.close();
const client = host.spawn('client');
client.send('join', 'nowhere');
await host.idle();
host.close();
```
```text title="output"
no such room
```
A send to a session that ended, or to a name no actor has, fails this way. A send to another system's address reaches your transport instead.
The transport fails it, with `send.fail()` or with `host.fail` from the other side, when it learns the actor is not there.
## Name actors with letters, digits, dots and dashes
A name is written into addresses, as `tinyactors://chat/@` in a chart's `target` and in your logs. An address's name holds only the characters RFC 3986 calls unreserved.
Those are `A`-`Z`, `a`-`z`, `0`-`9`, `-`, `.`, `_` and `~`, and any other byte is percent-encoded. The [address grammar](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/src/base/address.c) checks it.
`Address.fromName` encodes for you, but `room/general` is then `room%2Fgeneral` in every address. A chart that writes `room/general` unencoded reaches no actor and gets `error.communication`:
```javascript title="names.mjs"
import { Address, compileCharts, Host } from '@tinyactors/node';
console.log(Address.fromName('chat', 'room/general').text);
console.log(Address.fromName('chat', 'room.acme.general').text);
const compiled = compileCharts([
{ name: 'room.scxml', text: `` },
{ name: 'poster.scxml', text: `
` },
]);
const host = new Host(compiled, { system: 'chat', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('room', { name: 'room/general' });
host.spawn('poster');
await host.idle();
console.log(host.actor('room/general').address.text);
host.close();
```
```text title="output"
tinyactors://chat/@room%2Fgeneral
tinyactors://chat/@room.acme.general
error.communication for raw
tinyactors://chat/#_scxml_1
```
Name an actor by its kind and its ids joined by `.`, each id of lowercase letters, digits and `-`. Examples are `room.acme.general` and `cart.ada`.
Check an id that comes from a user before it becomes part of a name. The system's own id is stricter: lowercase letters, digits, `-` and `.`.
Names with parts also avoid two lookups by other keys. tinyactors finds an unnamed actor by its chart's name, and an invoked child by its invoke id.
So a name `room` would find any unnamed actor of the chart `room`, and `cart` the child of an ``. `room.acme.general` equals neither.
A name has one owner, the collection actor that spawns it ([Spawning from a chart](https://tinyactors.dev/guides/io-processors/index.md#spawning-from-a-chart)).
## Keep one table entry per sender
A room's members or a workspace's pending requests are tables keyed by `_event.origin`, the sender's address. One sender's origin comes in two forms:
- **`#_scxml_2`, the fragment alone**: when the send stayed in the sender's segment of the host: a send to a session's address (`#_scxml_`, or the full address of a session of the same system), to `#_parent`, to an invoked child, and a delayed send among them;
- **`tinyactors://chat/#_scxml_2`, the full address**: when the host routed the send: a send to a name (`@room.acme.general`), to a session in another segment, or from another system (whatever origin its transport passes, the full address when it passes the sender's `origin` on).
Both name the same sender, so key the table by the origin from `#` on. Here a helper in a chart-level `
` },
{ name: 'member.scxml', text: `
` },
]);
const host = new Host(compiled, { system: 'chat', log: (entry) => console.log(entry.text) });
compiled.close();
const room = host.spawn('room', { name: 'room.acme.general' });
const member = host.spawn('member');
member.send('join', room.address.text); // by its session
await host.idle();
member.send('join', 'tinyactors://chat/@room.acme.general'); // by its name
await host.idle();
host.close();
```
```text title="output"
#_scxml_2 is #_scxml_2: 1 member
tinyactors://chat/#_scxml_2 is #_scxml_2: 1 member
```
The fragment is a key and a target too: `` reaches the sender from any segment of the host.
## Keep the system when senders cross systems
A directory that answers several hosts holds senders of other systems, so its keys must keep the system. An origin from another system always names it.
There, complete a fragment with the actor's own system, from its own address in `_ioprocessors.scxml.location`:
```xml
```
An event from a service your program runs (`invocation.sendBack`) has the origin `#_`. It names that invocation in this actor only, and either helper leaves it as it is.
---
# Capacity and memory
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> A tinyactors actor takes about 530 bytes started and 120 hibernated, and each operation costs about the same at four million actors as at two.
On Node.js a started actor takes about 530 bytes and a hibernated one about 120, so four million fit in one process. Each operation costs about the same at four million actors as at two.
## Let the host grow its memory
A host keeps the actors of each compiled image in one block of memory, its region. When one of its pools fills, actors or timers for instance, the host copies the region into a larger one.
A host given no sizes starts with room for 64 actors, and grows as the population does.
## Set where each pool starts
The `system` map of the `config` option gives each new region its first sizes, in whole numbers. An absent key, or 0, keeps the default.
| Key | Default | What it counts |
|---|---|---|
| `maxActors` | 64 | actors, hibernated ones included |
| `maxEvents` | 256 | events waiting in the actors' queues |
| `maxTimers` | 64 | pending delayed sends |
| `maxRequests` | 16 | running invocations (child charts and services) |
| `workspaces` | 4 | actors in the middle of a step at once (a sender keeps its workspace until its send is handled); never refused: an actor waits for one, and the host adds more |
| `instanceBytes` | derived from the image and `maxActors` | the actors' variables and states |
| `stringBytes` | 16384 + 16 × `maxActors` | strings the actors hold |
| `ticksPerSecond` | 1,000,000,000 | the host's clock rate |
A size is where a pool starts, and the host still grows it. A pool that fills grows between runs, and the other pools stay as they were.
- A pool doubles, or grows up to 16 times at once when doubling would add under a quarter of the region. So a small pool beside a large region grows in a few copies.
- A grown region never shrinks.
- `maxActors` is at most 8,388,606. A run or an input is refused with `TA_ERROR_NO_MEMORY` only at a pool's largest size, or when the allocator refuses memory.
## See how full each pool is
`await host.hostStats()` answers with `pools`, one entry per region still in use ([Inspecting a host](https://tinyactors.dev/guides/inspection/index.md)). An entry's `segment` is its image's place among `new Host`'s charts, or what `addImage` returned.
Each pool reports its `capacity`, what it holds in `used`, and the most it held at once in `highWater`.
The pools are `actors`, `events`, `timers`, `workspaces`, `requests` and `slabBytes`, the memory for the actors' variables and strings.
A thousand idle actors grow a host that starts at the default 64, and fit in one sized for 1000. Each region grows on its own, so a second image is a second entry.
```javascript title="stats.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'idle.scxml', text: `
` }]);
const image = compiled.image;
compiled.close();
for (const system of [{}, { maxActors: 1000 }]) {
const host = new Host(image, { system: 'demo', config: { system } });
const before = (await host.hostStats()).pools[0].actors;
for (let i = 0; i < 1000; i++) host.spawn('idle');
const after = (await host.hostStats()).pools[0].actors;
console.log(`maxActors ${system.maxActors ?? 'default'}: capacity ${before.capacity}, ` +
`then ${after.used} used, high water ${after.highWater}, grown: ${after.capacity > before.capacity}`);
host.addImage(image);
console.log('segments reported:', (await host.hostStats()).pools.map((pool) => pool.segment).join(', '));
host.close();
}
```
```text title="output"
maxActors default: capacity 64, then 1000 used, high water 1000, grown: true
segments reported: 0, 1
maxActors 1000: capacity 1000, then 1000 used, high water 1000, grown: false
segments reported: 0, 1
```
A migration's old and new versions are two entries too, one per image.
## Size a host for a known population
Run a realistic load, read the high-water marks, and give the next host those sizes. A host sized for its load makes no copies, and no pool grows past what the load needs.
Count every actor in `maxActors`, since a hibernated one keeps its slot and its record, about 64 bytes. Size `instanceBytes` and `stringBytes` for the resident actors only.
The repository's hibernation gate sizes a host this way for two million counters of a few variables, 1000 resident at most. `host.hostConfig()` answers the sizes, every default filled in.
```javascript title="size.mjs"
import { Host } from '@tinyactors/node';
const N = 2_000_000; // actors
const R = 1000; // resident at most
const room = 64;
const host = new Host([], { system: 'big', config: { system: {
maxActors: N + room, maxEvents: 4096,
instanceBytes: 2048 * (R + room), stringBytes: 16384 + 64 * (R + room),
} } });
console.log((await host.hostConfig()).system.maxActors);
host.close();
```
```text title="output"
2000064
```
A chart with more variables or longer strings needs more per resident actor. `slabBytes.highWater` under load shows how much.
## Leave room for pools that fill together
A pending delayed send holds a timer and an event, and one falling due briefly holds a second event. So `N` actors that each wait on a delayed send need `maxTimers` of `N` and `maxEvents` above it.
Actors that become runnable together each hold a workspace, against a default of 4. Timers due in the same tick do, and so do actors sending to each other.
On `@tinyactors/wasm` a pool that runs out costs most: the region is copied inside WebAssembly memory, which keeps its peak.
| Pools | Memory per actor |
|---|---|
| `maxTimers` `N`, `maxEvents` `N` and a sixteenth, `workspaces` 1024 | 605 B |
| the default `workspaces`, room for 4,000 events beyond `N` | 1,142 B, grown within ten seconds |
A million actors on `@tinyactors/wasm` 0.4.0, each waiting on a delayed send, in the website's [measurement lab](https://github.com/tinyactors-dev/tinyactors/tree/main/website/examples/lab). Measured 2026-11-21 on an Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5.
That host reached 35 workspaces at once. A million actors sending to each other reached 92.
## Measure what one actor costs
The [memory program](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/memory) measures what one more actor, message or delayed send adds to a process, part by part. Run it with your chart, on your runtime and datamodel, the engine chart code runs in: native or quickjs.
```shell
node examples/memory/main.mjs --counts 1000000 --datamodel native
```
| runtime, datamodel | actor, started | actor, after an event | actor, hibernated | message waiting | delayed send pending |
|---|---|---|---|---|---|
| node, native | 532 B | 673 B | 118 B | 309 B | 353 B |
| bun, native | 601 B | 781 B | 93 B | 386 B | 448 B |
| node, quickjs | 1036 B | 1634 B | 92 B | 309 B | 358 B |
| bun, quickjs | 1041 B | 1645 B | 90 B | 313 B | 356 B |
What the process holds more for each thing, at a million. Measured 2026-11-25 on an Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5 and Bun 1.4.1. A counter chart with one ``, messages of `{"text": "hello"}`, tracing on; the hibernated column keeps at most 1000 actors resident and the rest in a store.
On Node.js a started actor takes 532 B of the process at a million, and a hibernated one 118 B.
The core's region and quickjs's heap account for part of it, the same on Node.js and Bun. On the native datamodel most of the rest is the JavaScript engine's heap.
| datamodel | actor, started | actor, after an event | actor, hibernated | message waiting | delayed send pending |
|---|---|---|---|---|---|
| native | 196 B | 196 B | 82 B | 106 B | 151 B |
| quickjs | 796 B | 1372 B | 82 B | 284 B | 329 B |
What the core's reservation, the host's other allocations and quickjs's heap account for, at a million, the same run.
The host's and the engine's fixed costs spread over the population, so an actor costs less in a larger one.
| | 10,000 | 100,000 | 1,000,000 | 2,000,000 | 4,000,000 |
|---|---|---|---|---|---|
| per actor, started | 803 B | 720 B | 532 B | 510 B | 495 B |
| per actor, after an event | 1446 B | 870 B | 673 B | 654 B | 639 B |
| per actor, hibernated | 637 B | 269 B | 118 B | 100 B | 91 B |
| per message waiting | 602 B | 392 B | 309 B | 293 B | 285 B |
| per delayed send pending | 737 B | 489 B | 353 B | 338 B | 331 B |
The process's bytes per thing at each population, Node.js on the native datamodel, the same run.
[The run's CSV](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-napi/examples/memory/results/2026-11-25.csv) holds every part of every row, at every population and on every runtime.
- **A started actor**: holds its variables in the datamodel and its records in the region: 196 B reserved for this chart at a million (81 B, its instance and its strings), 179 B of it used.
- **After an event**: an actor keeps that event as `_event` until the next one. On quickjs the event's record, 106 B, stays in the region too.
- **A hibernated actor**: uses 81 B of records in the region, and its blob is in your store: 145 B on the native datamodel and 147 B on quickjs, for this chart.
- **A message**: costs 106 B in the region (57 B with tracing off) and its data in the datamodel.
- **A delayed send**: holds its message until it falls due: 151 B in the region (102 B with tracing off).
- **On quickjs**: the engine keeps every actor's variables in its own heap, bounded by `quickjs.memoryLimit`, 1 GiB unless the host sets another. A million resident actors after an event need about 1.2 GB of it, so the run above sets 8 GiB ([the quickjs sandbox](https://tinyactors.dev/guides/quickjs/index.md#the-limits)).
A chart's scripts add nothing per actor. Their functions are the chart's, made once, and a top-level `var` is one more variable ([Writing charts](https://tinyactors.dev/guides/charts/index.md#scripts)).
## Check that costs hold as actors double
The scaling program, `tools/scale.mjs`, times every operation on N actors and on 2N, each host in its own process. It fails an operation that costs more than 1.5 times as much at 2N.
An operation on one actor is timed per call, and one on the whole population per actor.
In the first run most actors are hibernated in SQLite, and one in a hundred runs an invoked service. In the second every actor is resident.
Every operation passed. Each cell is the cost at N, then at 2N, in microseconds, and their ratio.
| operation | unit | node, native | node, quickjs | bun, native | bun, quickjs |
|---|---|---|---|---|---|
| populate (spawn and hibernate) | µs per actor | 10.88 → 10.56 (0.97) | 7.43 → 7.56 (1.02) | 7.52 → 7.81 (1.04) | 6.26 → 6.02 (0.96) |
| spawn | µs per call | 5.25 → 5.19 (0.99) | 2.62 → 2.60 (0.99) | 4.11 → 4.16 (1.01) | 2.43 → 2.45 (1.01) |
| terminate | µs per call | 0.867 → 0.786 (0.91) | 0.571 → 0.575 (1.01) | 0.952 → 0.893 (0.94) | 0.751 → 0.720 (0.96) |
| send | µs per call | 3.79 → 3.64 (0.96) | 1.90 → 1.77 (0.93) | 3.19 → 3.00 (0.94) | 2.12 → 2.06 (0.97) |
| sendMany | µs per event | 3.98 → 3.86 (0.97) | 2.18 → 2.04 (0.93) | 2.87 → 2.83 (0.99) | 2.01 → 1.85 (0.92) |
| send (hibernated: woken from the store) | µs per call | 32.27 → 27.93 (0.87) | 28.29 → 27.92 (0.99) | 24.71 → 25.96 (1.05) | 33.43 → 33.10 (0.99) |
| hibernate | µs per call | 5.41 → 4.93 (0.91) | 4.21 → 4.17 (0.99) | 3.56 → 3.44 (0.97) | 4.07 → 3.86 (0.95) |
| wake | µs per call | 6.94 → 6.38 (0.92) | 3.90 → 3.69 (0.95) | 6.91 → 7.27 (1.05) | 4.19 → 4.43 (1.06) |
| actor (by name) | µs per call | 3.96 → 4.01 (1.01) | 3.96 → 3.88 (0.98) | 1.32 → 1.20 (0.91) | 1.13 → 1.12 (0.99) |
| actorState | µs per call | 4.26 → 4.01 (0.94) | 4.15 → 4.11 (0.99) | 3.90 → 3.73 (0.96) | 3.66 → 3.58 (0.98) |
| hostStats | µs per call | 25.65 → 25.05 (0.98) | 24.49 → 23.49 (0.96) | 19.35 → 19.60 (1.01) | 18.96 → 18.23 (0.96) |
| I/O processor round trip | µs per call | 10.11 → 10.16 (1.01) | 6.81 → 6.73 (0.99) | 7.09 → 6.87 (0.97) | 5.77 → 5.54 (0.96) |
| transport round trip | µs per call | 30.55 → 31.31 (1.02) | 25.92 → 26.36 (1.02) | 25.19 → 26.15 (1.04) | 22.05 → 23.06 (1.05) |
| delayed send and its timer | µs per call | 6.28 → 6.19 (0.98) | 3.09 → 3.01 (0.97) | 4.95 → 5.15 (1.04) | 3.35 → 3.37 (1.01) |
| invoked service round trip | µs per call | 13.52 → 13.93 (1.03) | 10.33 → 10.12 (0.98) | 10.13 → 10.66 (1.05) | 9.15 → 9.79 (1.07) |
| sweep (every actor) | µs per actor | 0.006 → 0.005 (0.87) | 0.006 → 0.005 (0.87) | 0.006 → 0.006 (0.95) | 0.006 → 0.006 (0.91) |
| migrate (one session) | µs per call | 24.09 → 25.32 (1.05) | 16.51 → 16.95 (1.03) | 35.62 → 20.64 (0.58) | 16.90 → 16.30 (0.96) |
| snapshot | µs per actor | 0.100 → 0.092 (0.92) | 0.079 → 0.084 (1.07) | 0.081 → 0.087 (1.08) | 0.101 → 0.092 (0.92) |
| restore (and its first turn) | µs per actor | 0.291 → 0.298 (1.02) | 0.217 → 0.215 (0.99) | 0.223 → 0.217 (0.98) | 0.198 → 0.192 (0.97) |
| close | µs per actor | 0.114 → 0.128 (1.13) | 0.120 → 0.157 (1.31) | 0.126 → 0.127 (1.01) | 0.120 → 0.139 (1.16) |
Hibernated: 2,000,000 and 4,000,000 actors, at most 1000 counters resident, 20,000 and 40,000 actors each running an invoked service. One run, alone on the machine, 2026-11-20: an Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5 and Bun 1.4.1.
| operation | unit | node, native | node, quickjs | bun, native | bun, quickjs |
|---|---|---|---|---|---|
| populate (spawn, the segment growing) | µs per actor | 5.42 → 5.52 (1.02) | 4.28 → 3.85 (0.90) | 4.23 → 4.14 (0.98) | 3.76 → 3.63 (0.97) |
| spawn | µs per call | 4.84 → 4.86 (1.00) | 2.47 → 2.34 (0.95) | 4.06 → 4.14 (1.02) | 2.47 → 2.36 (0.95) |
| send | µs per call | 5.82 → 5.89 (1.01) | 3.88 → 3.97 (1.02) | 4.88 → 4.90 (1.00) | 4.01 → 4.19 (1.05) |
| hibernate | µs per call | 6.29 → 6.54 (1.04) | 6.89 → 6.31 (0.92) | 4.54 → 4.92 (1.09) | 6.78 → 6.85 (1.01) |
| wake | µs per call | 7.48 → 7.37 (0.99) | 2.85 → 2.59 (0.91) | 5.08 → 5.45 (1.07) | 3.19 → 3.14 (0.98) |
| snapshot | µs per actor | 4.49 → 4.23 (0.94) | 5.51 → 5.65 (1.03) | 3.50 → 3.20 (0.91) | 6.11 → 5.59 (0.92) |
| migrate (a chart, every actor) | µs per actor | 17.99 → 17.80 (0.99) | 11.44 → 10.58 (0.93) | 14.38 → 14.06 (0.98) | 11.59 → 9.99 (0.86) |
| restore (and its first turn) | µs per actor | 13.04 → 12.69 (0.97) | 4.35 → 4.96 (1.14) | 7.32 → 6.98 (0.95) | 4.57 → 4.79 (1.05) |
| close | µs per actor | 0.310 → 0.309 (0.99) | 1.71 → 1.53 (0.90) | 0.296 → 0.323 (1.09) | 1.74 → 1.56 (0.90) |
All resident: 1,000,000 and 2,000,000 actors, the same run.
Two million resident actors take up to 5.2 GiB on quickjs, the most of any run. So four million resident do not fit in 16 GiB beside the scenario's other work.
| runtime, datamodel | hibernated | all resident |
|---|---|---|
| node, native | 1733 / 2579 | 1706 / 3007 |
| node, quickjs | 1773 / 3382 | 2555 / 5274 |
| bun, native | 1680 / 3251 | 2271 / 3828 |
| bun, quickjs | 1345 / 2554 | 2517 / 5278 |
Peak resident memory at N and 2N, in MiB, the same run.
`mise run scale` in `tinyactors-napi` writes every operation and sample to `build/scale-*.json`. This run's files are in [tools/results/2026-11-20](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/tools/results/2026-11-20).
The repository's rules for [published numbers](https://github.com/tinyactors-dev/tinyactors/blob/main/AGENTS.md#published-numbers) say when to run it again, before each release among them.
---
# Hibernation
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Keep only the busy actors in memory: the host writes the others to blobs in your store and wakes them when they have work.
An actor that waits days for its next event can wait as bytes in your database instead. Two million actors ran with at most 1000 in memory, about 150 bytes of memory each.
## Cap how many actors stay in memory
Most actors spend most of their time waiting: an order for a payment, a session for its user. Hibernation turns a waiting actor into a blob, a `Buffer` your store keeps.
Give the host a store, which puts the blobs where you choose, and the most actors it may hold in memory.
- **`store: { save, load, delete }`**: where the blobs go, keyed by the actor's session, a `bigint`: `save(session, blob)`, `load(session)` returning the blob, and `delete(session)`. Each may return a promise instead, which the host follows. The package has `MemoryStore`, a `Map` for tests, and `SQLiteStore(path)`, a table in a file through the runtime's own SQLite (`node:sqlite` under Node.js, `bun:sqlite` under Bun).
- **`resident: n`**: the most actors the host keeps in memory. After each turn the host hibernates the actors past the bound that ran least recently, and saves their blobs. It picks them with a CLOCK sweep: an actor that ran since the previous sweep is passed over once.
- **Waking**: When an event comes for a hibernated actor, or one of its delayed sends falls due, the host loads its blob, wakes it and deletes the blob. The actor's events wait in its queue and run at the next turn. An actor terminated while hibernated is woken the same way to end, so its blob goes too.
Of three counters with `resident: 1`, two go to the store, and two events to one of them load it once:
```javascript title="resident.mjs"
import { compileCharts, Host, MemoryStore } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'counter.scxml', text: `
` }]);
const store = new MemoryStore();
const host = new Host(compiled, {
system: 'demo',
store,
resident: 1,
log: (entry) => console.log(entry.text),
});
compiled.close();
const counters = [1, 2, 3].map(() => host.spawn('counter'));
await host.idle();
console.log(`${store.blobs.size} in the store`);
counters[1].send('add', 5);
counters[1].send('add', 5); // one load for both
await host.idle();
console.log(`${store.blobs.size} in the store, ${[...store.blobs.keys()].includes(counters[1].id) ? 'with' : 'without'} counter 2`);
host.close();
```
```text title="output"
2 in the store
counter 2 is at 5
counter 2 is at 10
2 in the store, without counter 2
```
## Keep variables to plain data
On the native datamodel, the default engine for chart code, variables are written as values of the [value table](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#values):
- **Stored**: numbers, `bigint`s, strings, `Uint8Array`s, arrays, plain objects, `true`, `false`, `null` and `undefined`.
- **Kept in memory**: an actor whose variable holds anything else: a function, a `Map`, a `Date`, a class's instance, an XML document.
A script's top-level `var`s are variables of the actor and come back from the blob. A chart-level script's functions are the chart's helpers and come back with the chart.
On quickjs, the engine also stores a `Date`, `Map`, `Set` or typed array ([what differs on quickjs](https://tinyactors.dev/guides/quickjs/index.md#what-differs-from-the-native-datamodel)).
## Recover from a failed save
A save that throws, or whose promise rejects, wakes the actor back from its blob. The actor stays resident past the bound until a later turn.
The host reports the error the way it reports a handler's ([README, Errors](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#errors)). A load that finds no blob is reported the same way, and the actor stays hibernated.
The host calls the store between its runs, never inside one, and loads a session only after its pending save.
## Hibernate actors on your own schedule
Leave out `resident`, and your program picks which actors leave memory: on a timer, or when memory runs short.
Your program takes actors out with `sweep` and `hibernate`. The host still wakes them from the store when their events come.
- **`host.sweep(maxScan, limit)`**: returns at most `limit` sessions that have not run since the previous sweep and can be hibernated now, looking at no more than `maxScan` actors. Calling it regularly is what makes "not run since the previous sweep" mean cold: the first sweep after an actor ran skips it.
- **`host.hibernate(actor)`**: takes the actor out of memory and returns its blob, for you to save in the store.
- **`host.wake(actor, blob)`**: puts it back, which the host does itself when it has a store. Without a store a hibernated actor stays hibernated, and its events wait, until you call it.
The first sweep after the counter ran passes it over, and the second hibernates it:
```javascript title="sweep.mjs"
import { compileCharts, Host, MemoryStore, TinyactorsError } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'counter.scxml', text: `
` }]);
const store = new MemoryStore();
const host = new Host(compiled, { system: 'demo', store, log: (entry) => console.log(entry.text) });
compiled.close();
function evict() {
for (const session of host.sweep(1 << 20, 1024)) {
try {
store.save(session, host.hibernate(session));
} catch (error) {
if (!(error instanceof TinyactorsError)) throw error; // not at rest: it stays
}
}
}
const counter = host.spawn('counter');
counter.send('add', 2);
await host.idle();
evict(); // it ran since the last sweep: it stays
evict(); // it did not: it goes
console.log(`${store.blobs.size} in the store`);
counter.send('show');
await host.idle();
host.close();
```
```text title="output"
1 in the store
counter 1 is at 2
```
In a server, run such a sweep on a timer or after a burst of work. Size `limit` so that one sweep does not hold the event loop for long.
## Handle an actor that cannot hibernate
`hibernate` throws a `TinyactorsError` and the actor stays where it is:
- **`TA_ERROR_STATE`**: not now. It has events waiting in its queue (an input you gave since its last turn, an event another actor sent, a delayed send that fell due); or its step is not over, as when called from the handler of a send it made in this turn; or it runs an invoked child chart or a service; or it is not resident: already hibernated, or its blob is loading from the store. Every case gives the same status, and only the message, which is for people, says which.
- **`TA_ERROR_STALE`**: the session ended, or never was.
- **`TA_ERROR_UNSUPPORTED`**: a variable holds what its datamodel cannot store. The message names the variable.
The first three cases of `TA_ERROR_STATE` pass after a turn, and the last does not. The status cannot tell them apart.
So hibernate only what `sweep` returns, which is resident: a `TA_ERROR_STATE` there passes after a turn. With `resident`, the host skips each refused actor and hibernates another.
A `Map` in a variable is outside the value table, and the message names the variable:
```javascript title="unsupported.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'demo' });
compiled.close();
const actor = host.spawn('c');
await host.idle();
try {
host.hibernate(actor);
} catch (error) {
console.log(error.status);
console.log(error.message);
}
host.close();
```
```text title="output"
TA_ERROR_UNSUPPORTED
variable 'seen' cannot be stored: only plain objects, arrays and Uint8Arrays are values (docs/values.md)
```
## Wake each blob where it was made
A blob holds the actor's active states, its variables, its `_event` and its place in the host. It lives in your store until the wake, and the host keeps only which hibernation it was.
A blob also wakes in a host [restored](https://tinyactors.dev/guides/snapshots/index.md) from its host's snapshot.
Every host draws a random identity when it is created, and every blob carries it. Another host's blob throws `TA_ERROR_INVALID`, even for the same session number and chart.
A wake takes the session's latest blob only. An earlier blob throws `TA_ERROR_STALE` and the actor stays hibernated, so no state is lost without an error.
A stale replica hands back such a blob, and so does a store whose overwrite failed.
A restored host also accepts a blob of a hibernation made after the snapshot was taken. So a store that keeps one blob per session goes on working there.
## Count hibernated actors when you size a host
A hibernated actor still counts toward `system.maxActors`. It uses 81 B of records in the host ([what an actor costs](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs)).
The data of its pending delayed sends and of the events waiting in its queue stays in the host too. A pending delayed send wakes the actor when it falls due.
The [capacity guide](https://tinyactors.dev/guides/capacity/index.md) says how many actors a host holds and how much memory it needs.
## Run two million actors with 1000 in memory
[`tools/stress.mjs`](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/tools/stress.mjs) (`mise run stress`) runs this guide's pattern at scale, with the actors past the bound in SQLite.
Its 200,000 events went to actors drawn at random, so nearly every event woke one and the sweep sent another back. Each run woke 199,870 actors from the store.
Every sampled actor's count matched the events it was sent. After every eviction at most 1000 actors were resident.
| Runtime, datamodel | Populate (spawn and hibernate 2,000,000) | 200,000 events (woken, swept back) | Peak resident | Core's region | SQLite file |
|---|---|---|---|---|---|
| node, native | 48.2 s (41,500 a second) | 13.1 s (15,300 a second) | 307 MB (153 B per actor) | 164 MB (82 B per actor) | 378 MB |
| node, quickjs | 35.9 s (55,800 a second) | 12.1 s (16,500 a second) | 319 MB (159 B per actor) | 164 MB (82 B per actor) | 409 MB |
| bun, native | 39.6 s (50,600 a second) | 12.2 s (16,400 a second) | 300 MB (150 B per actor) | 164 MB (82 B per actor) | 378 MB |
| bun, quickjs | 34.2 s (58,400 a second) | 12.3 s (16,300 a second) | 287 MB (143 B per actor) | 164 MB (82 B per actor) | 409 MB |
Two million actors of a counter chart, at most 1000 resident, the rest in SQLite (`node:sqlite` under Node.js, `bun:sqlite` under Bun), then 200,000 events. One run of `tools/stress.mjs`, alone on the machine, 2026-11-20: Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5, Bun 1.4.1.
Populating slows as the population grows: after each turn the sweep looks over every actor's slot, hibernated ones included. Events to a population that exists do not slow.
---
# Migration
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Move running actors to a chart's new version, each at rest, keeping its session, states and queue while the host goes on working.
An order waiting a week for delivery can move to its chart's next version and keep the state it reached. Two million actors, most of them hibernated, moved while events kept coming.
## Add the new version to the host
`host.addImage(image)` adds a compiled image to a running host. A chart in it with a name the host already has becomes that chart's new version.
`host.spawn(name)` spawns the newest version, which `host.chart(name)` returns, and running actors stay on theirs.
Each image becomes a segment of the host: those `new Host` was given, and each one added after.
## Time the first actor on a new version
Compile both versions of the [order chart](https://github.com/tinyactors-dev/tinyactors/blob/main/website/examples/order/order.scxml) up front. In version 2, change the retry delay from one second to two.
For each trial, start and settle one version 1 actor on a fresh host with a simulated clock. Time `host.addImage()`, spawning the first version 2 actor and waiting for `host.idle()`.
After 20 warm-up trials, the next 100 took 0.18 ms at the median and 0.95 ms at the 95th percentile. Measured 2026-12-02 with `@tinyactors/node` 0.4.0, Node.js 24.22.3 and Linux on an AMD EPYC 9V74.
This measures activation inside one process with the chart bytes already in memory. Compilation, transferring the chart and [moving existing actors](https://tinyactors.dev/guides/migration/index.md#at-scale) are separate steps.
## Decide which actors must move
Adding the image is a deploy on its own: an actor that may finish on its version needs no migration.
An order that waits a week for its delivery is still running when the next version ships. Stopping it would lose its state.
A migration moves it instead, while the host goes on working, as part of [operating a host](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#operating-a-host).
An actor found by name is replaced when its owner spawns the new version under the name ([updating through names](https://tinyactors.dev/guides/io-processors/index.md#updating-through-names)). Migrate the actors that must not wait for their end.
## Move the actors and carry their variables
`host.migrate()` moves the running actors to the newest version of their chart, during the next turns.
A moved actor keeps its session, its active states, its queue and its delayed sends with their data. Its states are matched by id ([below](https://tinyactors.dev/guides/migration/index.md#states-the-new-version-enters)).
Its variables do not carry over by themselves, since the new version may name them differently. The actor first gets `error.platform.upgrade`, whose data holds the old version's variables.
Version 2 of this counter renames `n` to `count` and takes the old value from the upgrade event:
```javascript title="migrate.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const image = (name, text) => {
const compiled = compileCharts([{ name, text }]);
const bytes = compiled.image;
compiled.close();
return bytes;
};
const v1 = image('counter-v1.scxml', `
`);
// Version 2 renames n to count and counts by ten.
const v2 = image('counter-v2.scxml', `
`);
const host = new Host(v1, {
system: 'demo',
log: (entry) => console.log(entry.text),
migrated: (moved) => console.log(`session ${moved.session} moved to segment ${moved.segment}`),
migrationDone: (result) => console.log(`migration ${result.migration}: ${result.migrated} moved, ${result.failed.length} failed`),
});
const counter = host.spawn('counter');
counter.send('add');
counter.send('add');
await host.idle();
host.addImage(v2); // the deploy
const id = host.migrate({ chart: 'counter' });
console.log(`started migration ${id}`);
await host.idle();
counter.send('add');
await host.idle();
host.close();
```
```text title="output"
v1 counts 1
v1 counts 2
started migration 1
session 1 moved to segment 1
migration 1: 1 moved, 0 failed
upgraded, the old variables were {"n":2}
v2 counts 12
```
Once no actor runs on an old segment, the host retires it and frees its memory. `host.hostStats` counts the retired segments ([Inspecting a host](https://tinyactors.dev/guides/inspection/index.md)).
On the native datamodel, the upgrade event's data holds exactly the old version's variables. An old name the new version does not declare is gone after it.
The actor gets the new version's helper functions. The new version's `var`s are declared and `undefined`, since a migration runs no script.
## Choose what moves, and read the result
`host.migrate` picks the actors, and the `migrationDone` and `migrated` handlers in the host's options report on them:
- **`host.migrate({ chart, session, wake, timeout })`**: starts a migration and returns its id, a number. With no options it moves the actors of every chart; `chart` names one chart, `session` one actor. `wake: true` asks for the hibernated actors. `timeout` is in milliseconds of the host's clock, rounded up to its next tick; 0 or none means none. A `chart` the host does not have throws `TA_ERROR_INVALID`, and a `session` that ended `TA_ERROR_STALE`: a migration that could move nothing is refused rather than reported done.
- **`migrationDone: (result) => ...`**: in the host's options, gets the end of each migration: `{ migration, migrated, failed, pending }`. `failed` lists the actors it could not move, each `{ session, reason }` with `reason` core's status; `pending` lists the sessions (`bigint`s) its timeout left behind. It is a handler of the host, so a migration started by a host that was later [restored](https://tinyactors.dev/guides/snapshots/index.md) reports to the restored host's handler.
- **`migrated: (moved) => ...`**: gets each actor moved, a view of `session`, `segment`, `chart` (its name) and `migration`, valid while the handler runs.
## Do `` work in the upgrade transition
A migration enters the new version's states without running their ``, and leaves the old ones without their ``.
It matches states by id, then completes the active states to a set the new version allows:
- a state that is compound in the new version, and had no children in the old, is entered at its `initial` child, or its first;
- a state the new version does not have at all is replaced by its parent's initial state, the chart's `initial` at the top;
- a `` gets all its regions, and an `` of a state the migration enters is started.
So what an `` would have done, such as arming a timer or telling your program, is the upgrade transition's job. `In()` tells it where the actor landed.
Version 2 of this subscription gives `pastDue` a grace period and drops `paused`:
```javascript title="upgrade-states.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const image = (name, text) => {
const compiled = compileCharts([{ name, text }]);
const bytes = compiled.image;
compiled.close();
return bytes;
};
const v1 = image('sub-v1.scxml', `
`);
// Version 2: pastDue starts a grace period, and paused is gone.
const v2 = image('sub-v2.scxml', `
`);
const host = new Host(v1, { system: 'demo', clock: new SimulatedClock(), log: (entry) => console.log(entry.text) });
const late = host.spawn('subscription');
const paused = host.spawn('subscription');
late.send('miss');
paused.send('pause');
await host.idle();
host.addImage(v2);
host.migrate();
await host.idle();
for (const actor of [late, paused]) console.log(actor.id, JSON.stringify((await actor.state()).value));
console.log('next deadline', host.nextDeadline);
host.close();
```
```text title="output"
1 upgraded into grace: arming its timer
2 upgraded into active
1n {"pastDue":"grace"}
2n "active"
next deadline 7000
```
`grace onentry` is never logged. Without the upgrade transition's ``, actor 1 would wait in `grace` forever.
## Give a migration a timeout
A migration ends when every actor it looks at has moved, or at its `timeout`.
An actor running an invocation, an invoked chart or a service, moves once the invocation ends. With a `timeout`, the migration waits for the invocation to end, up to the timeout.
Without a `timeout` it fails such an actor at once with `'TA_ERROR_STATE'`, since an invocation may never end.
A migration still running when the host is closed never reaches `migrationDone`.
## Wake hibernated actors so they move
A hibernated actor moves once it is woken. With `wake: true` the migration asks the host for it, and the host loads it from its [store](https://tinyactors.dev/guides/hibernation/index.md).
The migration asks again if it finds the actor hibernated after a wake.
Without `wake`, a hibernated actor that nothing wakes holds the migration until its timeout. Without a timeout it holds it forever, and `migrationDone` is never called.
## Bound memory during a large migration
A migration with `wake: true` asks for every hibernated actor early. Woken all at once, they would all be in memory at once.
A host with a `resident` bound loads a migration's requests only while it holds fewer actors than the bound. It hibernates actors again after each turn, so the migration moves the population a few at a time.
An event for a hibernated actor still loads it at once.
A hundred counters with `resident: 10` migrate with at most 10 in memory between turns:
```javascript title="paced.mjs"
import { compileCharts, Host, MemoryStore } from '@tinyactors/node';
const image = (version) => {
const compiled = compileCharts([{ name: `v${version}.scxml`, text: `
` }]);
const bytes = compiled.image;
compiled.close();
return bytes;
};
const store = new MemoryStore();
/** @type {import('@tinyactors/node').MigrationResult | undefined} */
let done;
const host = new Host(image(1), {
system: 'demo',
store,
resident: 10,
migrationDone: (result) => (done = result),
});
for (let i = 0; i < 100; i++) host.spawn('counter');
await host.idle();
console.log(`${store.blobs.size} hibernated`);
host.addImage(image(2));
host.migrate({ wake: true });
let mostResident = 0;
while (done === undefined) {
await host.idle();
const stats = await host.hostStats();
mostResident = Math.max(mostResident, stats.host.actors - stats.host.hibernated);
}
console.log(`${done.migrated} moved, ${done.failed.length} failed, at most ${mostResident} in memory between turns`);
host.close();
```
```text title="output"
90 hibernated
100 moved, 0 failed, at most 10 in memory between turns
```
## Find the actors that could not move
An actor whose variables cannot be stored stays on its version, in the result's `failed` with reason `'TA_ERROR_UNSUPPORTED'`.
On the native datamodel, such a variable holds a value outside the value table, such as a function or a `Map`.
[Hibernation](https://tinyactors.dev/guides/hibernation/index.md#what-a-blob-stores) refuses the same actors: call `host.hibernate` on one, and its error names the variable.
## Migrate two million actors with 1000 in memory
[`tools/migration.mjs`](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/tools/migration.mjs) (`mise run migration`) runs this pattern at scale, with the actors past the bound in SQLite.
200,000 events came before the migration and 200,000 more during it. Every actor moved to version 2 with `wake: true`, in 3,688,635 loads from the store per run.
Every actor migrated, none failed and none was left. All 25,000 sampled actors had their count and version 2, and version 1's segment was retired.
After every eviction at most 1000 actors were resident.
| Runtime, datamodel | Populate (2,000,000 and 200,000 events) | Migrate (2,000,000 moved, 200,000 events) | Peak resident | Core's region, both versions / after | SQLite file |
|---|---|---|---|---|---|
| node, native | 58.4 s | 217.8 s (9,180 a second) | 756 MB (378 B per actor) | 329 MB / 164 MB (82 B per actor) | 590 MB |
| node, quickjs | 52.0 s | 181.8 s (11,000 a second) | 935 MB (467 B per actor) | 329 MB / 164 MB (82 B per actor) | 777 MB |
| bun, native | 52.4 s | 195.4 s (10,240 a second) | 967 MB (483 B per actor) | 329 MB / 164 MB (82 B per actor) | 590 MB |
| bun, quickjs | 49.4 s | 173.3 s (11,540 a second) | 925 MB (462 B per actor) | 329 MB / 164 MB (82 B per actor) | 777 MB |
Two million actors of version 1 of a counter, at most 1000 resident, the rest in SQLite, all moved to version 2. One run of `tools/migration.mjs`, alone on the machine, 2026-11-20: Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5, Bun 1.4.1.
---
# Snapshots
Kind: how-to. For: [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> host.snapshot() copies a running tinyactors host into bytes, two million actors in 165 MB, and Host.restore runs the copy in this process or another.
A host of two million actors makes a 165 MB snapshot in about a tenth of a second. Restore it in another process and rehearse a deploy on the copy.
## Copy every actor into one buffer
`host.snapshot()` returns one `Buffer` holding every actor of the host, with its variables, its queued events and its pending timers.
The buffer also holds the hibernated actors' records, the compiled images, the system id and the host's time. `Host.restore` runs it again, in this process or another.
On a copy, add a new image, migrate, run the clock ahead, and look. Or capture a host when something goes wrong, and step through it.
A test can start from one prepared world, and a host can leave the process for a while.
## Take a snapshot when the host is idle
`snapshot()` throws a `TinyactorsError` with `TA_ERROR_STATE` from a handler, and during a migration.
It throws the same while output or a typed method's reply waits for your handlers, so `await host.idle()` first.
Here a snapshot from a log handler throws, and one after `idle()` succeeds. A refused snapshot leaves the host running.
```javascript title="refused.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
` }]);
const host = new Host(compiled, {
system: 'demo',
log: (entry) => {
try {
host.snapshot();
} catch (error) {
console.log('from a handler:', error.status);
}
},
});
compiled.close();
host.spawn('c');
await host.idle();
console.log('after idle():', host.snapshot().length > 0);
host.close();
```
```text title="output"
from a handler: TA_ERROR_STATE
after idle(): true
```
`snapshot()` throws `TA_ERROR_UNSUPPORTED` when an actor holds what hibernation cannot store: on native, a function, `Map` or `Date`. The message names the variable.
## Run the copy on a new clock
This reminder is half an hour from ringing when its host is snapshotted. Restored on a new clock that reads 0, it rings 30 minutes later.
```javascript title="reminder.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'reminder.scxml', text: `
` }]);
const image = compiled.image;
compiled.close();
const log = (entry) => console.log(entry.text);
const clock = new SimulatedClock();
const host = new Host(image, { system: 'demo', clock, log });
const reminder = host.spawn('reminder', { name: 'plants' });
reminder.send('set', 'water the plants');
await host.idle();
clock.increment(30 * 60_000); // half an hour passes
await host.idle();
const snapshot = host.snapshot(); // bytes: write them to a file, send them elsewhere
host.close();
const later = new SimulatedClock(); // a clock that reads 0
const copy = Host.restore(snapshot, image, { system: 'demo', clock: later, log });
console.log('same session:', copy.actor('plants').id === reminder.id);
await copy.idle();
console.log('due in', copy.nextDeadline / 60_000, 'minutes');
later.increment(30 * 60_000);
await copy.idle();
copy.close();
```
```text title="output"
same session: true
due in 30 minutes
reminder: water the plants
```
The restored actor keeps its session id. The clock goes on from the snapshot's time, whatever reads it: a new `SimulatedClock`, or another machine's clock.
The snapshot's time is that of the `snapshot()` call. A timer with 6 seconds left then has 6 seconds left after the restore, however long the host was idle before.
## Restore with the options the snapshot had
Pass `Host.restore` the charts and the options the snapshot was taken with. It checks `system` against the system id the snapshot holds.
The snapshot holds the host, not the options you passed it: give the copy its handlers, I/O processors and tick rate. Pass `datamodel: 'quickjs'` again for a quickjs host.
The snapshot holds its images, so pass only the charts it lacks. An image it holds is skipped, and a new version is added as `new Host` adds it.
- **Restore with the same build.**: A snapshot holds raw memory, with a version of its layout. `Host.restore` refuses a snapshot of a build whose layout differs with `TA_ERROR_INVALID`: take a new one with the new build.
- **Keep your backups in your database.**: A snapshot looks like a backup, but durability is your database's job, and [hibernation](https://tinyactors.dev/guides/hibernation/index.md) is how a running process keeps actors out of memory. A snapshot is a copy of the whole application, every chart version at once.
- **Shared objects come back apart.**: Values are written through the [value table](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#values), so two variables of one actor that shared one object no longer share it after a restore.
## Start the invoked services again
The snapshot holds each running invocation, and the services you run stay in your program. The restored host's first turn announces each invocation that was running to the `services` handler you pass `Host.restore`.
Each comes with `invocation.restored` true and the same `invokeid`, `src` and params. Pass your real handlers to go on, or stand-ins for a copy that must not reach the real services.
A type with no handler gives its invokers `error.communication`, and nothing is thrown.
## Give the copy its own store
The snapshot holds the hibernated actors' records, and their blobs stay in your store. The restored host loads them from the `store` you pass it.
A copy that hibernates actors writes and deletes blobs too, so give it a copy of the store.
## Replay the inputs that came after
`host.now()` reads the host's clock, so a journal of the inputs that came after a snapshot records it with each.
A replay on a restored host with a `SimulatedClock` moves the clock to each reading before the input: `clock.increment(entry.at - host.now())`.
## Rehearse a deploy on a copy
The snapshot program, `tools/snapshot.mjs`, rehearses a deploy on a live host of two million actors. At most 1000 are resident, and the rest are in SQLite.
Each resident actor has a delayed send pending, and half are paying through an invoked service that has not answered.
- It writes the snapshot to a file, copies the store, and restores a copy with its own store and clock.
- A stand-in payment service gets each payment in flight again, `restored` and with its amount, and declines it.
- The copy's own snapshot must be the same bytes.
- The copy migrates to a new version while events come, and runs its clock past the delayed sends.
- Meanwhile the live host goes on with events of its own, its payments still in flight. The copy never reaches the real service.
With most actors hibernated, the snapshot is 165 MB, 82 B an actor. It takes 0.11 to 0.14 s to make, and 0.14 to 0.21 s to restore.
| runtime, datamodel | actors, resident | snapshot | taken | restored | migrate on the copy | peak resident (both hosts) |
|---|---|---|---|---|---|---|
| node, native | 2,000,000, 1000 | 165.0 MB (82 B per actor) | 0.14 s | 0.14 s | 244.9 s | 1261 MB |
| node, quickjs | 2,000,000, 1000 | 164.9 MB (82 B per actor) | 0.14 s | 0.14 s | 205.7 s | 1177 MB |
| bun, native | 2,000,000, 1000 | 165.0 MB (82 B per actor) | 0.12 s | 0.21 s | 208.1 s | 1534 MB |
| bun, quickjs | 2,000,000, 1000 | 164.9 MB (82 B per actor) | 0.11 s | 0.19 s | 185.9 s | 1559 MB |
| node, native | 100,000, 100,000 | 69.5 MB (695 B per actor) | 0.65 s | 2.00 s | 5.0 s | 522 MB |
| node, quickjs | 100,000, 100,000 | 63.7 MB (637 B per actor) | 1.01 s | 0.67 s | 3.4 s | 724 MB |
| bun, native | 100,000, 100,000 | 69.5 MB (695 B per actor) | 0.51 s | 1.05 s | 4.2 s | 941 MB |
| bun, quickjs | 100,000, 100,000 | 63.7 MB (637 B per actor) | 1.06 s | 0.71 s | 3.5 s | 800 MB |
Two runs, each alone on the machine, 2026-11-20: an Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5 and Bun 1.4.1. Two million actors with 1000 resident, 200,000 events before the snapshot and 200,000 more on each host after it; then 100,000 actors all resident.
Every run passed its checks:
- The copy's snapshot was the same bytes, and the copy migrated every actor to version 2. At two million, that migration made 3,688,631 loads from the copy's store.
- Every sampled actor had its count, delayed send and version on both hosts.
- The live store held only the live host's blobs.
- After every turn, no more actors were resident than the bound.
The host's region is 82 B an actor with most of them hibernated, and 490 B all resident. With all resident, the native datamodel's rows add about 58 B an actor over quickjs's state.
The logs are `snapshot.log` and `snapshot-resident.log` in [tools/results/2026-11-20](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/tools/results/2026-11-20). The repository's rules for [published numbers](https://github.com/tinyactors-dev/tinyactors/blob/main/AGENTS.md#published-numbers) say when to run it again.
---
# Journal and replay
Kind: how-to. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Record every input your program gives a tinyactors host, and replay the journal to rebuild every actor after a crash, without running any effect again.
A chart's state follows from its inputs and their times. Write each input to a journal before the host sees it, and one loop rebuilds every actor without charging a card again.
## Your program already has a log
A crash stops every actor in the process. What comes back is what your program wrote down ([what a crash keeps](https://tinyactors.dev/when-to-use/index.md#crash)).
tinyactors writes no log of its own, because your program already has one: a table, a file, a queue. Recording an input is one write, and replaying is one loop.
A chart that reads no clock and no random numbers has no hidden inputs. Given the same events in the same order at the same times, it takes the same transitions and ends in the same state.
## Record every input, then apply it
An order takes two items and checks out. The payment service never answers the first charge, so the chart charges again 30 seconds later, and the provider's webhook then says paid.
Both charges carry one idempotency key. The stand-in provider charges a card once per key, so a retry is safe.
Every input goes through one function, `record()`, which writes the host's time and the input, then applies it. The replay applies the same lines to a new host:
Node.js and Bun:
```javascript title="main.mjs"
import { readFileSync } from 'node:fs';
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);
// Every input goes through record(): the host's time, then the input.
const journal = [];
function apply(host, entry) {
if (entry.spawn) host.spawn(entry.spawn, { name: entry.name });
else host.send(entry.send);
}
function record(host, entry) {
const line = JSON.stringify({ at: host.now(), ...entry });
journal.push(line); // in production: append to a file or a table first
apply(host, JSON.parse(line));
}
// A stand-in for the payment provider: it charges a card once per key.
const requests = [];
const cards = new Map();
const payments = {
receive(send) {
requests.push(send.data.key);
if (!cards.has(send.data.key)) cards.set(send.data.key, send.data.amount);
},
};
const nobody = { receive() {} }; // charges nobody
const order = { target: 'tinyactors://shop/@order-1' };
const clock = new SimulatedClock();
const live = new Host(compiled, { system: 'shop', clock, ioProcessors: { payments } });
record(live, { spawn: 'order', name: 'order-1' });
record(live, { send: { ...order, event: 'add', data: { sku: 'pen' } } });
record(live, { send: { ...order, event: 'add', data: { sku: 'notebook' } } });
record(live, { send: { ...order, event: 'checkout' } });
await live.idle();
clock.increment(30_000); // no answer: the chart charges again, with the same key
await live.idle();
clock.increment(5_000);
record(live, { send: { ...order, event: 'paid' } }); // the provider's webhook
await live.idle();
// Replay journal lines into a new host whose processor does nothing.
async function replay(lines) {
const replayClock = new SimulatedClock();
const host = new Host(compiled, { system: 'shop', clock: replayClock, ioProcessors: { payments: nobody } });
for (const line of lines) {
const entry = JSON.parse(line);
replayClock.increment(entry.at - host.now());
await host.idle();
apply(host, entry);
await host.idle();
}
return host;
}
const replayed = await replay(journal);
// Go on from the replay on the runtime's clock, with the real processor.
const restored = Host.restore(replayed.snapshot(), compiled, { system: 'shop', ioProcessors: { payments } });
for (const [name, host] of [['live', live], ['replay', replayed], ['restored', restored]]) {
const actor = host.actor('order-1');
const { value } = await actor.state();
const { variables } = await actor.context();
console.log(`${name}: ${JSON.stringify(value)} after ${variables.attempts} attempts, ${variables.items.join(', ')}`);
}
console.log(`${journal.length} inputs journaled; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);
// A crash after the first charge, before its answer: the journal ends at the checkout.
const beforeAnswer = await replay(journal.slice(0, 4));
const crashClock = new SimulatedClock();
const recovered = Host.restore(beforeAnswer.snapshot(), compiled, { system: 'shop', clock: crashClock, ioProcessors: { payments } });
crashClock.increment(30_000); // the chart's timer charges again, with the same key
await recovered.idle();
const crashed = recovered.actor('order-1');
const { value } = await crashed.state();
const { variables } = await crashed.context();
console.log(`after a crash: ${JSON.stringify(value)} after ${variables.attempts} attempts; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);
for (const host of [live, replayed, restored, beforeAnswer, recovered]) host.close();
compiled.close();
```
```scxml title="order.scxml"
```
Browsers:
```javascript title="browser.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/wasm';
const chart = await fetch(new URL('order.scxml', import.meta.url)).then((response) => response.text());
const compiled = compileCharts([{ name: 'order.scxml', text: chart }]);
// Every input goes through record(): the host's time, then the input.
const journal = [];
function apply(host, entry) {
if (entry.spawn) host.spawn(entry.spawn, { name: entry.name });
else host.send(entry.send);
}
function record(host, entry) {
const line = JSON.stringify({ at: host.now(), ...entry });
journal.push(line); // in production: append to a file or a table first
apply(host, JSON.parse(line));
}
// A stand-in for the payment provider: it charges a card once per key.
const requests = [];
const cards = new Map();
const payments = {
receive(send) {
requests.push(send.data.key);
if (!cards.has(send.data.key)) cards.set(send.data.key, send.data.amount);
},
};
const nobody = { receive() {} }; // charges nobody
const order = { target: 'tinyactors://shop/@order-1' };
const clock = new SimulatedClock();
const live = new Host(compiled, { system: 'shop', clock, ioProcessors: { payments } });
record(live, { spawn: 'order', name: 'order-1' });
record(live, { send: { ...order, event: 'add', data: { sku: 'pen' } } });
record(live, { send: { ...order, event: 'add', data: { sku: 'notebook' } } });
record(live, { send: { ...order, event: 'checkout' } });
await live.idle();
clock.increment(30_000); // no answer: the chart charges again, with the same key
await live.idle();
clock.increment(5_000);
record(live, { send: { ...order, event: 'paid' } }); // the provider's webhook
await live.idle();
// Replay journal lines into a new host whose processor does nothing.
async function replay(lines) {
const replayClock = new SimulatedClock();
const host = new Host(compiled, { system: 'shop', clock: replayClock, ioProcessors: { payments: nobody } });
for (const line of lines) {
const entry = JSON.parse(line);
replayClock.increment(entry.at - host.now());
await host.idle();
apply(host, entry);
await host.idle();
}
return host;
}
const replayed = await replay(journal);
// Go on from the replay on the runtime's clock, with the real processor.
const restored = Host.restore(replayed.snapshot(), compiled, { system: 'shop', ioProcessors: { payments } });
for (const [name, host] of [['live', live], ['replay', replayed], ['restored', restored]]) {
const actor = host.actor('order-1');
const { value } = await actor.state();
const { variables } = await actor.context();
console.log(`${name}: ${JSON.stringify(value)} after ${variables.attempts} attempts, ${variables.items.join(', ')}`);
}
console.log(`${journal.length} inputs journaled; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);
// A crash after the first charge, before its answer: the journal ends at the checkout.
const beforeAnswer = await replay(journal.slice(0, 4));
const crashClock = new SimulatedClock();
const recovered = Host.restore(beforeAnswer.snapshot(), compiled, { system: 'shop', clock: crashClock, ioProcessors: { payments } });
crashClock.increment(30_000); // the chart's timer charges again, with the same key
await recovered.idle();
const crashed = recovered.actor('order-1');
const { value } = await crashed.state();
const { variables } = await crashed.context();
console.log(`after a crash: ${JSON.stringify(value)} after ${variables.attempts} attempts; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);
for (const host of [live, replayed, restored, beforeAnswer, recovered]) host.close();
compiled.close();
```
```scxml title="order.scxml"
```
```text title="output"
live: "paid" after 2 attempts, pen, notebook
replay: "paid" after 2 attempts, pen, notebook
restored: "paid" after 2 attempts, pen, notebook
5 inputs journaled; 2 charge requests, cards charged: 20
after a crash: "paying" after 2 attempts; 3 charge requests, cards charged: 20
```
Five inputs rebuilt the order. The live host sent two charge requests under one key, so the card was charged once, and the replay sent none. What each part does:
- **`record()`**: writes `host.now()` and the input as one JSON line, and only then applies it, so the journal never misses an input the host saw. In production, make the write durable before applying (an fsync, a committed transaction). A crash between the write and the apply replays an input the host never saw. A sender that never heard back may send it again, so give such inputs a `sendid` the chart checks.
- **The charge's key**: is `'order-' + _sessionid`, the same on every attempt and in a host restored from a snapshot, so a retry never charges a card twice.
- **Names, not sessions**: the journal reaches the order by its address, `tinyactors://shop/@order-1`, so it reads the same on any host.
- **The webhook**: is an input like any other. An answer from outside the host must be recorded, or the replay never hears it.
- **The replay's processor**: does nothing, so no card is charged again. Effects leave the chart as events, which is what lets the replay switch them off.
- **The replay's clock**: moves to each entry's time and runs everything due by then before applying the entry, so the 30-second timeout fires before the webhook arrives, as it did live.
- **`Host.restore`**: takes a snapshot of the replayed host and runs it on the runtime's clock with the real processor, so the program goes on where it stopped.
## Charge again after a crash, under one key
A process can die after a charge left it and before its answer came back. The journal then ends at the checkout, and nobody knows whether the card was charged.
The program's last lines play that crash. They replay the journal up to the checkout, restore the result with the real processor and move its clock 30 seconds:
```javascript title="main.mjs"
// A crash after the first charge, before its answer: the journal ends at the checkout.
const beforeAnswer = await replay(journal.slice(0, 4));
const crashClock = new SimulatedClock();
const recovered = Host.restore(beforeAnswer.snapshot(), compiled, { system: 'shop', clock: crashClock, ioProcessors: { payments } });
crashClock.increment(30_000); // the chart's timer charges again, with the same key
await recovered.idle();
const crashed = recovered.actor('order-1');
const { value } = await crashed.state();
const { variables } = await crashed.context();
console.log(`after a crash: ${JSON.stringify(value)} after ${variables.attempts} attempts; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);
```
```text title="output"
live: "paid" after 2 attempts, pen, notebook
replay: "paid" after 2 attempts, pen, notebook
restored: "paid" after 2 attempts, pen, notebook
5 inputs journaled; 2 charge requests, cards charged: 20
after a crash: "paying" after 2 attempts; 3 charge requests, cards charged: 20
```
The restored order's timer charged again, so the provider got a third request. It carried the first charge's key, so the card was still charged once, and the order waits in `paying` for the provider's answer.
## Keep the journal short with snapshots
A journal that is never cut grows with every input, and so does the replay. Snapshot the host now and then, and store the journal's position with the snapshot.
After a crash, restore the last snapshot on a `SimulatedClock` and replay only the entries after it. Then snapshot again and empty the journal ([replay the inputs that came after](https://tinyactors.dev/guides/snapshots/index.md#replaying-inputs)).
The [turn-game example](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/turn-game) does this for a game server it kills and restarts. It checkpoints every second and replays the moves made since.
## Keep the chart's inputs in the journal
A replay matches only when every input the chart reads is in the journal. Check three things.
- **Time and chance**: a chart that reads `Date` or `Math.random` gets a new answer on replay. Read them in your program and pass them in as event data, which the journal then holds.
- **Answers and services**: an I/O processor's answer, a service's `sendBack` and `done` and a `host.fail` are inputs. Give them through `record()`, with the sender's address and the send's `sendid`, and on replay give the processors and services stand-ins that do nothing.
- **The same millisecond**: the replay runs every timer due at an entry's time before the entry, while live the input may have come first. A chart should not depend on which wins within one millisecond, as a move against its turn's timeout in the turn-game example does.
- **Effects in flight**: a charge the live host sent, whose answer never reached the journal, is lost with the crash. After the restore, the chart's timer charges again, so send the same idempotency key on every attempt ([above](https://tinyactors.dev/guides/journal/index.md#crash-before-answer)).
## Journal a host, or one actor
When actors send each other events, one actor's input changes another's state. Journal the whole host, the unit a replay rebuilds.
An actor that hears only from outside can have a journal of its own, keyed by its name. Replay that journal into a fresh host to rebuild it alone.
## Choose a journal, snapshots or both
- **A journal**: keeps every input, so nothing after the last write is lost, and it doubles as an audit log. It costs one write before each input and a replay as long as the journal.
- **Snapshots alone**: cost nothing per input, and restoring two million actors took 0.14 to 0.21 s ([measured on one machine](https://tinyactors.dev/guides/snapshots/index.md#at-scale)). Inputs after the last snapshot are lost.
- **Both**: restore the last snapshot, then replay the short journal written since. This is what turn-game does.
- **[Hibernation](https://tinyactors.dev/guides/hibernation/index.md)**: is not a log: it keeps waiting actors out of memory. Use it with either.
---
# Run actors in a Cloudflare Worker
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Run a tinyactors host inside a Cloudflare Durable Object: thousands of actors in one object, idle ones in its SQLite storage, every actor kept across an eviction.
One Durable Object can hold a tinyactors host with thousands of actors, on @tinyactors/wasm. Idle actors hibernate into the object's SQLite storage, and a snapshot brings every actor back after an eviction.
## Import the module, then compile the chart
A Worker cannot compile WebAssembly from bytes at run time, so it imports `tinyactors.wasm` and hands the module to `init()`. Then it compiles the chart once and sends every order's request to the shop's one object:
```javascript title="worker.mjs"
// The Worker: compiles the order chart once per isolate and sends every
// request under /orders/ to the shop's one Durable Object.
import wasm from '@tinyactors/wasm/tinyactors.wasm';
import { init, compileCharts } from '@tinyactors/wasm/init';
import order from './order.scxml';
import { shop } from './shop.mjs';
await init(wasm); // workerd compiles a module it imports, never bytes at run time
const compiled = compileCharts([{ name: 'order.scxml', text: order }]);
const image = compiled.image;
compiled.close();
export const Shop = shop(image, { resident: 1000 });
export default {
async fetch(request, env) {
if (!new URL(request.url).pathname.startsWith('/orders/')) return new Response('not found', { status: 404 });
return env.SHOP.get(env.SHOP.idFromName('shop')).fetch(request);
},
};
```
The config binds the object with SQLite storage and imports `.scxml` files as text:
```json title="wrangler.jsonc"
{
"name": "shop",
"main": "worker.mjs",
"compatibility_date": "2026-09-01",
// @tinyactors/wasm 0.4.0 reads import.meta.url when it is imported,
// which a Worker's bundle leaves undefined
"define": { "import.meta.url": "\"https://worker.invalid/\"" },
"rules": [{ "type": "Text", "globs": ["**/*.scxml"], "fallthrough": true }],
"durable_objects": { "bindings": [{ "name": "SHOP", "class_name": "Shop" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Shop"] }]
}
```
- **`init(wasm)`**: takes the module wrangler compiled from the import, in place of fetching it. Compiling the bytes in the Worker fails with "Wasm code generation disallowed by embedder".
- **The `define`**: gives `import.meta.url` a value. @tinyactors/wasm 0.4.0 reads it when it is imported, and without it the Worker stops at start with "TypeError: Invalid URL string."
- **`datamodel: 'quickjs'`**: in `shop.mjs`, below. A Worker refuses to evaluate strings, which the native ECMAScript datamodel needs, so the charts run in [quickjs](https://tinyactors.dev/guides/quickjs/index.md), which is inside the same module.
## Keep every order in one object
One object per shop, not per order, keeps the shop's actors in one host, where they send each other events with no request between objects.
Each order of the shop is an actor of this chart. After checkout it waits 15 minutes for the payment, then expires. Nothing else in it knows about Cloudflare:
```scxml title="order.scxml"
```
The object holds one host, finds an order by its name and spawns it on its first event. After each request it writes the host to its storage:
```javascript title="shop.mjs"
// A Durable Object that holds one tinyactors host: each order of the shop
// is an actor in it, found by its name. Orders past `resident` hibernate
// into the object's SQLite storage. After each request the host's
// snapshot and the blobs written since the last one are committed in one
// transaction, so the next instance of the object, after an eviction or
// a deploy, goes on where this one stopped. Timers run on the object's
// alarm.
import { Host, SimulatedClock, StaleError } from '@tinyactors/wasm/init';
const PART = 1 << 20; // a row of an object's SQLite holds at most 8 MB: the snapshot goes in parts of 1 MiB
export function shop(charts, { resident }) {
return class Shop {
constructor(ctx) {
this.ctx = ctx;
this.sql = ctx.storage.sql;
this.pending = new Map(); // session -> blob, or null for a delete, until the commit
this.queue = Promise.resolve();
ctx.blockConcurrencyWhile(async () => this.open());
}
// The host from the last commit, or a new one.
open() {
this.sql.exec('CREATE TABLE IF NOT EXISTS blobs (session TEXT PRIMARY KEY, blob BLOB)');
this.sql.exec('CREATE TABLE IF NOT EXISTS snapshot (part INTEGER PRIMARY KEY, bytes BLOB)');
this.sql.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value)');
// The host's clock moves while the object runs: serially() steps it
// to the wall clock at each request and alarm.
this.clock = new SimulatedClock();
const options = { system: 'shop', datamodel: 'quickjs', clock: this.clock, store: this.store(), resident };
const parts = this.sql.exec('SELECT bytes FROM snapshot ORDER BY part').toArray();
if (parts.length === 0) {
this.host = new Host(charts, options);
this.wall = Date.now();
} else {
this.host = Host.restore(join(parts.map((row) => new Uint8Array(row.bytes))), charts, options);
this.wall = this.sql.exec("SELECT value FROM meta WHERE key = 'wall'").one().value;
}
}
// The host's store: writes wait in `pending` for the commit, so the
// blobs and the snapshot that names them land together.
store() {
const { sql, pending } = this;
return {
save: (session, blob) => { pending.set(String(session), blob.slice()); },
load: (session) => {
const key = String(session);
if (pending.has(key)) return pending.get(key);
return new Uint8Array(sql.exec('SELECT blob FROM blobs WHERE session = ?', key).one().blob);
},
delete: (session) => { pending.set(String(session), null); },
};
}
// POST /orders// with JSON data sends the event, spawning
// the order on its first event; GET /orders/ reads it.
async fetch(request) {
return this.serially(async () => {
const [, , name, event] = new URL(request.url).pathname.split('/');
let order;
try {
order = this.host.actor(name);
} catch (error) {
if (!(error instanceof StaleError)) throw error;
if (request.method !== 'POST') return Response.json({ error: `no order ${name}` }, { status: 404 });
order = this.host.spawn('order', { name });
}
if (event) {
const body = await request.text();
order.send(event, body === '' ? undefined : JSON.parse(body));
}
await this.host.idle();
const state = await this.read(order);
await this.commit();
return Response.json({ order: name, ...state });
});
}
async alarm() {
await this.serially(async () => {
await this.host.idle();
await this.commit();
});
}
// One request at a time, with the host's clock stepped to now.
serially(work) {
const run = this.queue.then(() => {
const now = Date.now();
this.clock.increment(Math.max(0, now - this.wall));
this.wall = now;
return work();
});
this.queue = run.catch(() => {});
return run;
}
// The order's state and items; a hibernated order is woken to be read.
async read(order) {
try {
return await this.inspect(order);
} catch (error) {
if (error.reason !== 'state') throw error;
const store = this.store();
this.host.wake(order, store.load(order.id));
store.delete(order.id);
await this.host.idle();
return this.inspect(order);
}
}
async inspect(order) {
const { value } = await order.state();
const { variables } = await order.context();
return { state: value, items: variables.items };
}
// The blobs since the last commit, the snapshot and the wall clock in
// one transaction, then the alarm at the host's next deadline.
async commit() {
const snapshot = this.host.snapshot();
const deadline = this.host.nextDeadline;
this.ctx.storage.transactionSync(() => {
for (const [session, blob] of this.pending) {
if (blob === null) this.sql.exec('DELETE FROM blobs WHERE session = ?', session);
else this.sql.exec('INSERT OR REPLACE INTO blobs VALUES (?, ?)', session, blob);
}
this.sql.exec('DELETE FROM snapshot');
for (let part = 0; part * PART < snapshot.length; part++) {
this.sql.exec('INSERT INTO snapshot VALUES (?, ?)', part, snapshot.subarray(part * PART, (part + 1) * PART));
}
this.sql.exec("INSERT OR REPLACE INTO meta VALUES ('wall', ?)", this.wall);
});
this.pending.clear();
if (deadline === undefined) await this.ctx.storage.deleteAlarm();
else await this.ctx.storage.setAlarm(this.wall + deadline);
}
};
}
function join(parts) {
const bytes = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
let at = 0;
for (const part of parts) {
bytes.set(part, at);
at += part.length;
}
return bytes;
}
```
- **`store` and `resident`**: past 1000 orders in memory, the host [hibernates](https://tinyactors.dev/guides/hibernation/index.md) the ones that have not run lately into the `blobs` table.
- **`commit()`**: writes the snapshot, the blobs saved since the last commit and the time in one `transactionSync`, so the storage never holds a blob the snapshot does not expect.
- **`Host.restore`**: runs in a new instance of the object, after an eviction or a deploy. It brings back the last [snapshot](https://tinyactors.dev/guides/snapshots/index.md), and the hibernated orders load from the same table.
- **The clock**: is a `SimulatedClock` stepped to the wall clock at each request and alarm, so the 15 minutes count while the object is out of memory.
- **`setAlarm`**: wakes the object at the host's next deadline, and `alarm()` runs what is due. An object has one alarm at a time.
- **`serially()`**: runs one request at a time, so no snapshot is taken while another request's events run.
## Restart the object and keep the orders
`npx wrangler dev` runs the Worker in workerd on your machine, with no Cloudflare account. Stopping it and starting it again makes a new instance of the object, as an eviction does:
```shell
$ curl -X POST localhost:8787/orders/order-1/add -d '"book"'
{"order":"order-1","state":"cart","items":["book"]}
$ curl -X POST localhost:8787/orders/order-1/checkout
{"order":"order-1","state":"awaiting_payment","items":["book"]}
# Ctrl-C, then npx wrangler dev again
$ curl localhost:8787/orders/order-1
{"order":"order-1","state":"awaiting_payment","items":["book"]}
```
The object also runs in Node.js over a stand-in for its `ctx`, which tests it without workerd. Here it keeps one order in memory, loses its instance, then gets its alarm 15 minutes later:
```javascript title="main.mjs"
// shop.mjs in Node.js, without workerd: a stand-in for the object's ctx
// over node:sqlite, the requests a client would make, an eviction (a new
// instance of the object over the same database) and the alarm 15
// minutes later.
import { readFileSync } from 'node:fs';
import { init, compileCharts } from '@tinyactors/wasm/init';
import { shop } from './shop.mjs';
process.removeAllListeners('warning'); // node:sqlite says it is experimental
const { DatabaseSync } = await import('node:sqlite');
await init();
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync(new URL('order.scxml', import.meta.url), 'utf8') }]);
const Shop = shop(compiled.image, { resident: 1 }); // one order in memory, the rest in SQLite
compiled.close();
// The stand-in's wall clock, which the alarm moves on.
const wall = Date.now;
let skew = 0;
Date.now = () => wall() + skew;
const db = new DatabaseSync(':memory:');
let alarm = null;
const ctx = {
storage: {
sql: {
exec(query, ...bindings) {
const statement = db.prepare(query);
const rows = statement.columns().length > 0 ? statement.all(...bindings) : (statement.run(...bindings), []);
return { toArray: () => rows, one: () => rows[0] };
},
},
transactionSync(work) {
db.exec('BEGIN');
try { work(); db.exec('COMMIT'); } catch (error) { db.exec('ROLLBACK'); throw error; }
},
async setAlarm(at) { alarm = at; },
async deleteAlarm() { alarm = null; },
},
blockConcurrencyWhile: (work) => work(),
};
async function request(object, method, path, data) {
const body = data === undefined ? undefined : JSON.stringify(data);
const response = await object.fetch(new Request(`https://shop.example${path}`, { method, body }));
console.log(method, path, JSON.stringify(await response.json()));
}
let object = new Shop(ctx);
await request(object, 'POST', '/orders/order-1/add', 'book');
await request(object, 'POST', '/orders/order-1/add', 'pen');
await request(object, 'POST', '/orders/order-1/checkout');
await request(object, 'POST', '/orders/order-2/add', 'lamp');
const blobs = db.prepare('SELECT session FROM blobs').all().map((row) => row.session);
console.log('hibernated in SQLite:', blobs.join(', '));
console.log('alarm in', Math.round((alarm - Date.now()) / 1000), 's');
object = new Shop(ctx); // evicted: a new instance reads the snapshot back
console.log('-- a new instance of the object');
await request(object, 'GET', '/orders/order-1');
skew += 15 * 60_000;
await object.alarm();
console.log('-- the alarm, 15 minutes later');
await request(object, 'GET', '/orders/order-1');
await request(object, 'GET', '/orders/order-2');
```
```text title="output"
POST /orders/order-1/add {"order":"order-1","state":"cart","items":["book"]}
POST /orders/order-1/add {"order":"order-1","state":"cart","items":["book","pen"]}
POST /orders/order-1/checkout {"order":"order-1","state":"awaiting_payment","items":["book","pen"]}
POST /orders/order-2/add {"order":"order-2","state":"cart","items":["lamp"]}
hibernated in SQLite: 1
alarm in 900 s
-- a new instance of the object
GET /orders/order-1 {"order":"order-1","state":"awaiting_payment","items":["book","pen"]}
-- the alarm, 15 minutes later
GET /orders/order-1 {"order":"order-1","state":"expired","items":["book","pen"]}
GET /orders/order-2 {"order":"order-2","state":"cart","items":["lamp"]}
```
Order 1 was in SQLite when the instance went, and the new one restored it waiting for payment. The alarm then expired it. Order 2 stayed in its cart.
## Each request writes the whole host
A snapshot is the host's memory, so every commit rewrites all of it. With 10,000 orders and 100 of them in memory it was 4.3 MB, and one event took 41 to 52 ms in local workerd ([measured on one machine](https://github.com/tinyactors-dev/tinyactors/tree/main/website/examples/workers#measured)). Size, not traffic, sets the cost.
So keep each object to one shop or one tenant: thousands of actors, not millions. For millions in one process, run the host in [Node.js with a store](https://tinyactors.dev/guides/hibernation/index.md#at-scale).
## What a production version adds
- **A pinned package**: a snapshot restores only into a build of @tinyactors/wasm with the same memory layout, and `Host.restore` refuses another with `TA_ERROR_INVALID`. Before deploying a new version, restore a copy of a live object's snapshot with it.
- **Answers from outside**: a payment provider's webhook is a request like any other: `POST /orders/order-1/paid`.
- **Effects**: a chart's sends to your code go to an [I/O processor](https://tinyactors.dev/guides/io-processors/index.md). The host waits for the promise it returns, so a `fetch` it makes finishes before the commit.
- **Several objects**: each object is a host of its own, so an actor reaches another object's actor through a transport you write ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)).
---
# Inspecting a host
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Read which state a running actor is in and what its variables hold, and count what each chart has done.
`await actor.state()` tells you which state a running actor is in, and `await host.hostStats()` counts what each chart has done.
## Read an actor's state and variables
`actor.state()`, `actor.context()` and `actor.get()` each return a promise. Each reads the host as it is at the call, and settles on a later turn of the event loop.
An application calls these on its `Actor`s. An operator asks the same of `host`, as in `await host.actorState({ session })` ([Operating a host](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#operating-a-host)).
This program adds tea to an order, then reads its state, its variables and its mailbox.
```javascript title="order.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'order.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
const order = host.spawn('order', { name: 'first' });
order.send('add', 'tea');
await host.idle(); // the actor has started and handled 'add'
const { value } = await host.actorState({ session: order });
console.log('state:', JSON.stringify(value));
const { variables } = await order.context();
console.log('variables:', JSON.stringify(variables));
const actor = await order.get();
console.log('actor:', actor.chart, 'mailbox', actor.mailbox);
host.close();
```
```text title="output"
state: {"open":"browsing"}
variables: {"items":["tea"]}
actor: order mailbox 0
```
A state reads as nested objects, one key per compound state: `{"open": "browsing"}` is `browsing` inside `open`. A parallel state has one key per region: `{"p": {"r1": ..., "r2": ...}}`.
Await `host.idle()` before you ask. Until a spawned actor first runs, it has no active state and every variable reads `undefined`, its `params` included.
Its `` get their values, from `expr` or `params`, when it first runs. Then a variable holding `undefined` reads `undefined` and one holding `null` reads `null`, on both datamodels.
## See when an actor acts next
`actorGet` tells when a waiting actor acts next, and `actorState` which state it will go back to.
- **`timers`**: The actor's pending delayed sends, each `` not yet due and not cancelled, earliest first, as `{ sendid, event, due }`. `due` is in milliseconds on the clock `host.now()` reads, and a send without an `id` has a `sendid` of `null`.
- **`timersPending`**: How many pending delayed sends there are. The list holds at most 32, so a `timersPending` above its length says it was cut.
- **`history`**: For each history state the actor has recorded, its parent state as it would be entered again, in the shape of `value`. A history state records when its parent is exited, so before the first exit it is absent and `history` is `{}`.
```javascript title="review.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'review.scxml', text: `
` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, { system: 'docs', clock });
compiled.close();
const doc = host.spawn('review');
doc.send('submit');
doc.send('hold');
await host.idle();
clock.increment(60_000); // a minute later
const { timers, timersPending } = await host.actorGet({ session: doc });
for (const { sendid, event, due } of timers) console.log(sendid, event, 'in', (due - host.now()) / 1000, 's');
console.log('pending:', timersPending);
const { value, history } = await host.actorState({ session: doc });
console.log('state:', JSON.stringify(value), 'history:', JSON.stringify(history));
host.close();
```
```text title="output"
sla breach in 7140 s
pending: 1
state: "held" history: {"back":{"reviewing":"legal"}}
```
A deep history (`type="deep"`) returns to the atomic states it recorded, so its value goes down to them. A shallow one names only the child it recorded, which enters its own initial state.
The host reads timers and history only when asked, so keeping them adds nothing to an event's work.
## Pick the method for your question
Each of these calls, the typed methods, takes one object of params and resolves with one result object:
| Method | Params | Result |
|---|---|---|
| `actorState` | `{ session }` | `{ value, history }`: the active states, and where each history state would return ([history](https://tinyactors.dev/guides/inspection/index.md#delayed-sends-and-history)) |
| `actorContext` | `{ session }` | `{ variables }`: each `` and its value |
| `actorGet` | `{ session }` | `{ session, segment, chart, parent, mailbox, invocations, timers, timersPending }`; `timers` are its pending delayed sends ([delayed sends](https://tinyactors.dev/guides/inspection/index.md#delayed-sends-and-history)) |
| `actorList` | `{ cursor, limit }`, both optional | `{ sessions, cursor }`: a page of sessions; `cursor` is `null` after the last page |
| `hostStats` | none | `{ host, pools, charts }`: counters ([the host's counters](https://tinyactors.dev/guides/inspection/index.md#the-hosts-counters)) |
| `hostConfig` | none | the config the host runs with, every default filled in |
| `traceConfigure`, `traceWatch`, `traceUnwatch`, `traceEnd`, `traceSpansDecode` | | [Telemetry](https://tinyactors.dev/guides/telemetry/index.md) |
A method without params is called with none: `await host.hostStats()`. A `session` param takes an `Actor` too.
The host checks the params: one the method does not take, of a wrong type or out of range fails. A session that names no actor, ended or never spawned, fails too.
`actorContext` and `actorState` refuse a hibernated actor with `reason` `'state'`: wake it first ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md)).
## Catch a question the host refuses
A refused method rejects with a `TinyactorsError`. Its `reason` is a word such as `stale` or `unknown`, and its `path` names the param it is about.
Its `code` is JSON-RPC's number and its message is for people. A call on a closed host rejects the same way.
```javascript title="errors.mjs"
import { Host } from '@tinyactors/node';
const host = new Host([], { system: 'shop' });
try {
await host.actorState({ session: 99 });
} catch (error) {
console.log(error.reason, error.path, error.code);
}
// @ts-expect-error: a param actorGet does not take, which the types refuse too
await host.actorGet({ name: 'first' }).catch((error) => console.log(error.reason, error.path));
host.close();
```
```text title="output"
stale params.session -32001
unknown params.name
```
Catch each rejection where you await it: `host.idle()` never sees it. One you do not catch is an unhandled rejection, which ends a Node.js or Bun process by default.
`host.close()` drops the methods still waiting, and their promises never settle.
## Page through every actor
`actorList` answers a page of sessions and a `cursor` for the next, `null` after the last page. This loop reads five actors two at a time.
```javascript title="list.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'idle.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
for (let i = 0; i < 5; i++) host.spawn('idle');
const sessions = [];
let cursor = 0;
do {
const page = await host.actorList({ cursor, limit: 2 });
sessions.push(...page.sessions);
cursor = page.cursor;
} while (cursor !== null);
console.log('sessions:', sessions.join(' '));
host.close();
```
```text title="output"
sessions: 1 2 3 4 5
```
## Compare listed sessions as numbers
A result's sessions are numbers, while `actor.id` and the views give `bigint`s. So `result.sessions.includes(actor.id)` is false, and a `Map` keyed by one misses the other.
Compare with `Number(actor.id) === listed`, or key by `String(actor.id)` ([Actors, sessions and addresses](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#actors-sessions-and-addresses)).
The inputs take either as it is, as in `host.send(result.sessions[0], ...)`, and `host.actor(result.sessions[0])` gives its `Actor`. `await host.actors({ chart })` reads every page and lists the live actors as `Actor`s.
## Count what the host has done
`await host.hostStats()` gives counters for the whole host, for each segment's pools and for each chart. Here one of three jobs finishes and one hits an error.
- **`host`**: `segments` (live), `actors` and `hibernated` (now), `runnable` (actors with work waiting), `migrations` (running), `regionBytes` (the memory of the live segments), `delivered` (events put in queues), `routed` (sends between the host's segments), `migrated` (actors moved), `retired` (segments freed after a migration) and `fuelClock` (the work the host has done, the clock its trace records are stamped with).
- **`pools`**: An array with one entry per live segment, in segment order. Each entry has its `segment` number and one object per pool, `actors`, `events`, `timers`, `workspaces`, `requests` and `slabBytes`, each `{ capacity, used, highWater }`: `stats.pools[0].actors.used` ([Capacity and memory](https://tinyactors.dev/guides/capacity/index.md)).
- **`charts`**: One entry per chart name, summed over its versions: `name`, `actors`, `hibernated`, `spawned`, `ended`, `turns`, `macrosteps`, `fuel`, `errorsExecution`, `errorsCommunication`, `errorsPlatform` (`error.platform` events raised in the chart's actors) and `faults` (actors the host had to end because their run failed inside the host).
Four of these names are the host's own terms:
- **Macrostep**: Everything one event does to an actor: its transitions and those that follow on their own, until the actor waits for the next event. A microstep is one set of transitions taken together; spans are named after both ([Telemetry](https://tinyactors.dev/guides/telemetry/index.md)).
- **Fuel**: The host's unit of work: an action, a transition, and a share of the JavaScript an expression runs.
- **Turn**: One time an actor is given the processor. It runs until it waits or has spent its fuel for the turn (`system.quantum`), so a busy actor cannot starve the others.
- **Workspace**: The room an actor needs while it runs. The host has a few, and an actor waits for one.
```javascript title="stats.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'job.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
const jobs = [1, 2, 3].map(() => host.spawn('job'));
jobs[0].send('finish');
jobs[1].send('break');
await host.idle();
const stats = await host.hostStats();
const [job] = stats.charts;
console.log(`${job.name}: ${job.spawned} spawned, ${job.ended} ended, ${job.actors} running, ${job.errorsExecution} execution error`);
console.log(`${stats.host.segments} segment, ${stats.pools[0].actors.used} actors in its pool`);
host.close();
```
```text title="output"
job: 3 spawned, 1 ended, 2 running, 1 execution error
1 segment, 2 actors in its pool
```
## Find actors that never rest
Actors that answer each other forever keep the host busy, and `await host.idle()` never resolves. Nothing is logged or thrown, since every step is legal.
The usual cause is SCXML's prefix match ([Charts](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#charts)): a transition on `join` also takes the answer `join.refused`, and asks again.
Between two readings with no input, a loop's charts gain `macrosteps` and `fuel` without end, and `host.delivered` grows. `host.runnable` stays above zero, where a host that is only slow drains its queue.
```javascript title="busy.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([
{ name: 'user.scxml', text: `
` },
{ name: 'room.scxml', text: `
` },
]);
const host = new Host(compiled, { system: 'chat' });
compiled.close();
host.spawn('room', { name: 'room' });
const user = host.spawn('user');
/** The charts whose actors kept working for `ms` with no input given. */
async function busy(host, ms) {
const before = await host.hostStats();
await new Promise((resolve) => setTimeout(resolve, ms));
const after = await host.hostStats();
if (after.host.runnable === 0) return [];
return after.charts
.filter((chart) => chart.macrosteps - (before.charts.find((c) => c.name === chart.name)?.macrosteps ?? 0) > 1000)
.map((chart) => chart.name)
.sort();
}
console.log('busy:', (await busy(host, 200)).join(', '));
user.terminate(); // in production: alert, and fix the chart
await host.idle();
console.log('idle again; busy:', (await busy(host, 50)).length);
host.close();
```
```text title="output"
busy: room, user
idle again; busy: 0
```
A watchdog running this on a timer finds such a loop, alerting when a chart stays busy over several readings.
Fix the chart: name the answer so it does not extend the request, as `refused.join`. Or make the `join` transition's `cond` refuse what is not a request.
## Pass handlers instead of a promise
Each method also takes handlers, as `host.actorState(params, onResult, onError)`, and then returns nothing. A later turn calls `onResult(result)`, or `onError(error)` with the same `TinyactorsError`.
The promise is made only when no handler is given, so a caller that passes handlers pays for none. A method without params takes `undefined`: `host.hostStats(undefined, onResult)`.
```javascript title="handlers.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'idle.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
const session = host.spawn('idle');
await host.idle();
host.actorState({ session }, (result) => console.log('state:', JSON.stringify(result.value)));
host.hostStats(undefined, (stats) => console.log('actors:', stats.host.actors));
host.actorGet({ session: 99 }, () => {}, (error) => console.log('error:', error.reason));
console.log('asked');
await host.idle();
host.close();
```
```text title="output"
asked
state: "waiting"
actors: 1
error: stale
```
The handlers ran after `asked`, in a later turn. Without an `onError`, an error rejects a waiting `host.idle()`, or is thrown as an uncaught exception like a handler's.
## Check params and results with TypeScript
`index.d.ts` types each method's params and result (`SessionParams`, `ActorStateResult`, `ActorListResult`, `HostStatsResult`, `EffectiveHostConfig`, ...), and the config as `HostConfig`.
The types hold for the promises and the handlers' `result` alike. An editor completes `stats.pools[0].actors.highWater`, and `tsc` refuses a field a result lacks or a param a method does not take.
---
# Telemetry
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Export each step an actor takes as an OpenTelemetry span, with its logs and metrics, as OTLP bytes your code sends to a collector.
Each step an actor takes becomes a span with its event and the states it left and entered, in the caller's trace when it passes one. Your code sends the OTLP bytes to the collector it chooses.
## Decide where the OTLP bytes go
The host writes OTLP requests, the protobuf bytes a collector takes at `/v1/traces`, `/v1/logs` and `/v1/metrics`. Your code posts them where it chooses, and retries when it must ([operating a host](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#operating-a-host)).
A step's span holds the event, the transitions, and the states left and entered. Each `` and failed action becomes a log record, and the host's counters become metrics.
Turning telemetry on changes nothing an actor does. [Telemetry: every step is a span](https://tinyactors.dev/telemetry/index.md) runs a traced payment in your browser and shows its spans.
## Export spans to your collector
A `telemetry` map in the config makes the host write OTLP. A `telemetry` handler in the options gets each request it writes as a `Buffer`, with its signal, `'traces'` or `'logs'`.
This order continues a caller's trace, and its spans come back with the caller's span as their parent:
```javascript title="export.mjs"
import { compileCharts, decodeTraces, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'order.scxml', text: `
` }]);
const requests = [];
const clock = new SimulatedClock();
const host = new Host(compiled, {
system: 'shop',
config: {
system: { ticksPerSecond: 1000 }, // the host's clock in milliseconds
telemetry: { flushInterval: 1000, resource: { 'service.name': 'shop' } }, // a request at most a second after its first record
},
clock,
telemetry: (signal, data) => {
// A real exporter posts the bytes, from a promise so the host goes on:
// fetch(`${collector}/v1/${signal}`, { method: 'POST', headers: { 'content-type': 'application/x-protobuf' }, body: data })
requests.push([signal, data]);
},
});
compiled.close();
const caller = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01'; // a W3C traceparent, from an HTTP header
host.spawn('order').send('pay', undefined, { traceparent: caller });
await host.idle();
console.log('requests before the flush interval:', requests.length);
clock.increment(1000);
await host.idle();
console.log('signals:', requests.map(([signal]) => signal).sort().join(', '));
// Read the spans back (for a test; a collector does this for you).
for (const [signal, data] of requests) {
if (signal !== 'traces') continue;
const spans = decodeTraces(data);
const ours = spans.filter((span) => span.trace === '0af7651916cd43dd8448eb211c80319c');
console.log('spans in the caller\'s trace:', ours.map((span) => span.name).sort().join(', '));
const step = ours.find((span) => span.name === 'scxml.macrostep pay');
console.log('the step\'s parent is the caller\'s span:', step.parent === 'b7ad6b7169203331');
}
host.close();
```
```text title="output"
requests before the flush interval: 0
signals: logs, traces
spans in the caller's trace: scxml.destroyed, scxml.finished, scxml.macrostep pay, scxml.microstep pay
the step's parent is the caller's span: true
```
The handler runs in the host's turn, so start the post there and return without waiting for the collector. `decodeTraces` reads an export without a host ([Wire format](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#wire-format)).
A handler's error is the turn's ([Errors](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#errors)). The request it failed to send is not offered again, so retrying is the exporter's job.
## Choose how soon records are sent
Every key of the config's `telemetry` map is optional, and `flushInterval` decides how soon a request is ready:
| Key | Default | What it does |
|---|---|---|
| `flushInterval` | 0 | a request is ready this long after its first record, in the host's clock ticks (`system.ticksPerSecond`); 0 means only when the staging is full, or at close |
| `resource` | none | attributes on every request, such as `service.name` (at most 32, text to text) |
| `logs` | `true` | `` lines and failed actions as log records |
| `values` | `false` | event data and assigned values in the spans; they may hold personal data, so turn this on knowingly |
| `linkParents` | `false` | an actor's step is a root span linked to its cause, instead of its child |
| `stagingBytes` | 1048576 | the encoder's staging memory |
The host's clock runs at `system.ticksPerSecond`, a billion by default, so a `flushInterval` of 5000 is five microseconds. Most programs that export set `ticksPerSecond: 1000` and give the interval in milliseconds.
## Step a test's clock past the flush
Once records wait to be sent, the flush is one of the host's deadlines. `host.nextDeadline` reads it even when no actor has a delayed send left.
The host arms its timer for it, which keeps the process alive until then. A test that asserts no timer is left steps its clock past the flush first:
```javascript title="flush.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'job.scxml', text: `
` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, {
system: 'shop',
config: { system: { ticksPerSecond: 1000 }, telemetry: { flushInterval: 1000 } },
clock,
telemetry: (signal) => console.log(signal, 'at', clock.now),
});
compiled.close();
host.spawn('job');
await host.idle();
console.log('the job ended; nextDeadline', host.nextDeadline);
clock.increment(host.nextDeadline ?? 0);
await host.idle();
console.log('flushed; nextDeadline', host.nextDeadline);
host.close();
```
```text title="output"
the job ended; nextDeadline 1000
traces at 1000
logs at 1000
flushed; nextDeadline undefined
```
## Read metrics on your own schedule
`host.metrics()` returns the metrics request for the host's counters now, a `Buffer` for `/v1/metrics`. On a host without `telemetry` in its config it throws `TA_ERROR_STATE`.
## Close the host to send the last spans
At `host.close()` every open span ends, marked incomplete, and the handler gets the last requests before the host is freed.
`await host[Symbol.asyncDispose]()` also awaits a promise the handler returns there. A host the garbage collector frees without `close()` sends none of it: close the hosts whose telemetry you want.
## Continue a trace across requests
An input continues the trace a W3C `traceparent` header's text names, and text that does not parse starts a new trace. Pass it as an option:
- `actor.send(event, data, { traceparent })`
- `host.send(actor, event, data, { traceparent })`
- `host.spawn(chart, { traceparent })`
A send's `traceparent` is the sending step's context: put it in the header of your request for that send. This handler reads the trace its request would carry:
```javascript title="propagate.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
` }]);
const host = new Host(compiled, {
system: 'demo',
ioProcessors: {
'urn:example:api': {
receive(send) {
const [, trace] = send.traceparent.split('-');
console.log('the outgoing request continues trace', trace);
// fetch(url, { headers: { traceparent: send.traceparent } })
},
},
},
});
compiled.close();
host.spawn('c').send('go', undefined, {
traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
});
await host.idle();
host.close();
```
```text title="output"
the outgoing request continues trace 4bf92f3577b34da6a3ce929d0e0e4736
```
`send.answer()` continues the send's trace unless given another, and `null` starts a new one.
Tracing is on by default (`system.tracing`), with or without `telemetry` in the config, so trace context flows when nothing is exported.
## Seed trace IDs to repeat a test's traces
A trace the host starts takes its ID from a generator seeded by `system.traceSeed`. With none in the config, the package draws a random seed for each new host (`crypto.getRandomValues`).
So two processes, or one process and its restart, do not collide at the collector. The same seed gives the same IDs, which reproduces a test's traces:
```javascript title="seed.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
` }]);
const image = compiled.image;
compiled.close();
const firstTrace = async (system) => {
let trace;
const host = new Host(image, {
system: 'demo',
config: { system },
ioProcessors: { 'urn:example:api': { receive: (send) => { trace = send.traceparent.split('-')[1]; } } },
});
host.spawn('c');
await host.idle();
host.close();
return trace;
};
console.log('no seed, twice:', (await firstTrace({})) === (await firstTrace({})));
console.log('seed 7, twice:', (await firstTrace({ traceSeed: 7 })) === (await firstTrace({ traceSeed: 7 })));
```
```text title="output"
no seed, twice: false
seed 7, twice: true
```
A host made with `Host.restore` keeps the snapshot's generators, so its IDs go on from where the snapshot left them.
## Change what is traced while the host runs
Call these methods on the host to change what it records while it runs ([Inspecting a host](https://tinyactors.dev/guides/inspection/index.md)):
- **`traceConfigure(params)`**: sets what every actor traces: `detail` (`'summary'`, `'decisions'`, `'full'` or `'off'`), `values`, `sample` (the share of new traces sampled, 0 to 1) and `rules`. It replaces the previous configuration.
- **`traceWatch({ rules, seconds })`**: adds rules in front of the configured ones for a while (900 seconds by default) and answers `{ id }`. A watch is how an operator looks closely at one chart or one actor without tracing everything.
- **`traceUnwatch({ id })`**: ends a watch early.
- **`traceEnd()`**: ends every open span now, as `close()` does.
- **`traceSpansDecode({ traces })`**: reads the spans of a traces request back through the host. `decodeTraces(bytes)` needs no host, and also gives each span's `flags`, `links`, `resource` and `scope`.
A rule picks the steps it applies to, then says how to trace them:
- **What it matches**: `chart`, `actor` (a trailing `*` makes it a prefix), `event` (SCXML's prefix rule), `session` or `from`, which is `'host'`, `'actor'`, `'timer'`, `'spawn'` and so on.
- **What it decides**: `sample` (`'keep'`, `'sample'`, `'drop'` or a share) and `detail`, at most `perSecond` with a `burst`.
This host samples 1 trace in 100 in summary, then traces every checkout in full for a minute:
```javascript title="watch.mjs"
import { Host } from '@tinyactors/node';
const host = new Host([], { system: 'shop', config: { telemetry: {} } });
await host.traceConfigure({ detail: 'summary', sample: 0.01 });
console.log('1 trace in 100, summarized');
const watch = await host.traceWatch({ rules: [{ chart: 'checkout', sample: 'keep', detail: 'full' }], seconds: 60 });
console.log(`watch ${watch.id}: every checkout in full for a minute`);
host.close();
```
```text title="output"
1 trace in 100, summarized
watch 1: every checkout in full for a minute
```
---
# In the browser
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Run the charts you run on Node.js in a page or a Worker with @tinyactors/wasm, the same API on core compiled to WebAssembly.
Change one import, and the charts you run on Node.js run in a page or a Worker, on tinyactors compiled to WebAssembly. The same package runs Node.js and Bun where no native addon is built, such as Windows.
## Import the WebAssembly package instead
Import `@tinyactors/wasm` in place of `@tinyactors/node`, and every other guide holds unchanged. This program logs the same line in a page as in Node.js:
```javascript title="hello.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';
const compiled = compileCharts([{ name: 'hello.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'web', log: (entry) => console.log(entry.text) });
compiled.close();
host.spawn('hello');
await host.idle();
host.close();
```
```text title="output"
hello from tinyactors://web/#_scxml_1
```
## Treat bytes as Uint8Arrays, not Buffers
Where `@tinyactors/node` gives a `Buffer`, this package gives a plain `Uint8Array`. A `Buffer` is a `Uint8Array` too, so code written against `Uint8Array` runs on both.
That covers every output in bytes: `compiled.image`, `host.hibernate()`, `host.snapshot()`, `host.metrics()`, telemetry and `encode()`.
Decode text with `TextDecoder` instead of `buf.toString()`, and copy or compare with the typed array's own methods. This program copies an encoded value and writes it as base64:
```javascript title="bytes.mjs"
import { decode, encode } from '@tinyactors/wasm';
const bytes = encode({ sku: 'tea', qty: 2 });
console.log(bytes instanceof Uint8Array, bytes.length, 'bytes');
const copy = bytes.slice(); // a Uint8Array again, on both packages
console.log(decode(copy).sku, btoa(String.fromCharCode(...copy))); // base64, in a page as in Node.js
```
```text title="output"
true 14 bytes
tea omNza3VjdGVhY3F0eQI=
```
`index.d.ts`, which both packages share, types every one of them as `Uint8Array`.
## Call init() under a bundler or Service Worker
The package's entry loads its module, `tinyactors.wasm` beside its files, with top-level `await`. A browser fetches the file, Node.js and Bun read it, and every name works once the import settles.
A Service Worker refuses a module graph with top-level `await`. Some bundlers neither handle it nor place `tinyactors.wasm` beside the bundle: esbuild does not follow `new URL(..., import.meta.url)`.
There, import `@tinyactors/wasm/init`: it exports the same names and `init(source?)`, which loads the module once. Every call made before it settles throws `TA_ERROR_STATE`.
Give `init` a URL, a `Response`, the bytes or a compiled `WebAssembly.Module`, or nothing to load the package's own file. This program makes a host before and after `init()`:
```javascript title="init.mjs"
import { Host, init } from '@tinyactors/wasm/init';
try {
new Host([], { system: 'early' });
} catch (error) {
console.log('before init:', error.status);
}
await init(); // or init(new URL('/assets/tinyactors.wasm', location.href)), wherever your build put it
const host = new Host([], { system: 'ready' });
console.log('after init: closed', host.closed);
host.close();
```
```text title="output"
before init: TA_ERROR_STATE
after init: closed false
```
The package targets ES2022 and serves the module as `@tinyactors/wasm/tinyactors.wasm`, so a bundler or a CDN can place it.
## Target Chrome 114, Firefox 119 and Safari 16.4
By the engines' release notes, Chrome and Edge 114, Firefox 119 and Safari 16.4 have every feature the package uses. Only Chromium 141 is tested.
- **WebAssembly**: `extended-const`, `multivalue`, `bulk-memory` and `nontrapping-fptoint`, in the module.
- **JavaScript**: top-level `await` and `String.prototype.isWellFormed`, in the package.
## Allow WebAssembly and eval in your CSP
The module needs `'wasm-unsafe-eval'` in `script-src`. The default engine, the native datamodel, runs your charts' expressions and scripts as JavaScript, so it needs `'unsafe-eval'` too.
```text
Content-Security-Policy: script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'
```
Under any of these policies, `new Host(...)` on the native datamodel throws `TinyactorsError` with `TA_ERROR_UNSUPPORTED`, its message naming the directive:
- a `script-src` without `'unsafe-eval'`;
- a `sandbox` policy without `allow-same-origin`;
- Trusted Types enforced (`require-trusted-types-for 'script'`), which guards string evaluation even with `'unsafe-eval'`.
Under them, `compileCharts` also skips its check of the charts' JavaScript syntax, since it parses with the same constructor. Run such a page's charts on [quickjs](https://tinyactors.dev/guides/browser/index.md#the-quickjs-sandbox).
## Run charts on quickjs under a strict policy
With `datamodel: 'quickjs'`, chart code runs on quickjs-ng inside the package's module, so the page's policy needs only `'wasm-unsafe-eval'`. Use it for charts you do not trust, too.
Every quickjs option and behaviour of `@tinyactors/node` holds here ([The quickjs sandbox](https://tinyactors.dev/guides/quickjs/index.md)). This host sets `maxOps` and reads the engine's heap size:
```javascript title="quickjs.mjs"
import { Host } from '@tinyactors/wasm';
const host = new Host([], { system: 'rules', datamodel: 'quickjs', quickjs: { maxOps: 10000 } });
console.log(host.quickjsHeapBytes > 0);
host.close();
```
```text title="output"
true
```
Every page downloads quickjs, since the one module holds it: 378 KiB with brotli, against 137 KiB without it. `mise run pack:wasm` reports the sizes.
The engine's stack is the module's, at most 256 KiB whatever `quickjs.stackLimit` asks. A deeper recursion is its evaluation's `error.execution`, `RangeError: Maximum call stack size exceeded`.
Inside quickjs, `Date` reads the real clock, as in `@tinyactors/node`, whatever clock the host runs on.
## Declare every variable your scripts assign
Scripts and expressions run as strict code, so an assignment to a name nobody declared is the script's `error.execution`. It never becomes a global.
Declare a variable with a top-level `var` or with ``. Here the declared chart keeps `visits` through hibernation, and the undeclared one fails:
```javascript title="declare.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';
const chart = (name, script) => `
`;
const compiled = compileCharts([
{ name: 'declared.scxml', text: chart('declared', 'var visits = 0; function next(n) { return n + 1; }') },
{ name: 'undeclared.scxml', text: chart('undeclared', 'visits = 0; function next(n) { return n + 1; }') },
]);
const host = new Host(compiled, { system: 'web', log: (entry) => console.log(entry.text) });
compiled.close();
const declared = host.spawn('declared');
declared.send('visit');
await host.idle();
host.wake(declared, host.hibernate(declared)); // out of memory and back, its visits with it
declared.send('visit');
await host.idle();
host.spawn('undeclared');
await host.idle();
host.close();
```
```text title="output"
declared: 1
declared: 2
undeclared: ReferenceError
```
Top-level declarations follow the rules of `@tinyactors/node` ([Writing charts](https://tinyactors.dev/guides/charts/index.md#scripts)):
- a chart-level script's `function`s are the chart's helpers, made once;
- a top-level `var` is a variable of the session;
- `let`, `const` and `class` at a script's top level are refused.
A host runs its charts in a realm of its own, a set of globals it makes at its first chart. Each actor's variables are a scope object there, and the realm differs by platform:
| Where | A host's charts run in |
|---|---|
| a page | a hidden iframe of the page's origin, one per host, removed at `close()` |
| a Worker | the worker's own global (a Worker has no `document`) |
| Node.js, Bun | a `node:vm` context, as in `@tinyactors/node` |
A hidden iframe looks like a sandbox but is not one: chart code runs in your engine and must be trusted.
## Move the charts off the page's thread
On the page's thread, a chart step that runs long is a frame the page does not draw.
In a dedicated Worker the page stays responsive, and the charts' realm holds none of the page's code. Only values cross `postMessage`, as between any two systems.
The page waits until the worker says it listens, since a message sent before the worker's module ran is lost. Then it asks for a counter and two visits:
```javascript title="page.mjs"
const worker = new Worker(new URL('./counters-worker.mjs', import.meta.url), { type: 'module' });
// the worker says when it listens: a message sent before its module ran (it loads
// the package with top-level await) has no listener and is lost
await new Promise((resolve) => { worker.onmessage = resolve; });
const ask = (message) => new Promise((resolve) => {
worker.onmessage = (event) => resolve(event.data);
worker.postMessage(message);
});
console.log(await ask({ op: 'spawn', name: 'ada' }));
console.log(await ask({ op: 'visit', name: 'ada' }));
console.log(await ask({ op: 'visit', name: 'ada' }));
worker.terminate();
```
```text title="output"
spawned ada
ada: 1
ada: 2
```
The worker, `counters-worker.mjs` beside the page, runs the host. It answers each question once the host is idle, with the count the counter sends to `urn:page`:
```javascript title="counters-worker.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';
const compiled = compileCharts([{ name: 'counter.scxml', text: `
` }]);
let answer = null; // the page's pending question
const host = new Host(compiled, {
system: 'worker',
ioProcessors: { 'urn:page': { receive: (send) => answer?.(`${send.host.actor('ada').equals(send.sender) ? 'ada' : '?'}: ${send.data.visits}`) } },
});
compiled.close();
self.onmessage = async ({ data }) => {
const reply = new Promise((resolve) => { answer = resolve; });
if (data.op === 'spawn') {
host.spawn('counter', { name: data.name });
answer(`spawned ${data.name}`);
} else host.actor(data.name).send('visit');
await host.idle();
postMessage(await reply);
};
postMessage('ready');
```
A module Worker has no import map. A bundler resolves `@tinyactors/wasm` in the worker as in the page, or the worker imports the package's `index.mjs` by its URL.
## Keep hibernated actors in IndexedDB
Your code chooses where a browser host's hibernated actors and snapshots live. A browser has no SQLite, so it refuses `SQLiteStore` ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md)).
A page has IndexedDB, which stores a `Uint8Array` as it is. The host follows a store's promises, so IndexedDB can be a host's `store` directly.
This counter is hibernated into IndexedDB, then loaded from it when its next event comes:
```javascript title="store.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';
// IndexedDB, as promises: one object store of blobs, the session as the key
const done = (request) => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const opening = indexedDB.open('tinyactors-blobs', 1);
opening.onupgradeneeded = () => opening.result.createObjectStore('blobs');
const db = await done(opening);
const blobs = (mode) => db.transaction('blobs', mode).objectStore('blobs');
const store = {
save: (session, blob) => done(blobs('readwrite').put(blob, String(session))),
load: (session) => done(blobs('readonly').get(String(session))),
delete: (session) => done(blobs('readwrite').delete(String(session))),
};
const compiled = compileCharts([{ name: 'counter.scxml', text: `
` }]);
const host = new Host(compiled, {
system: 'web',
store, // with resident: n, the host would also hibernate into it after each turn
log: (entry) => console.log(entry.text),
});
compiled.close();
const counter = host.spawn('counter');
counter.send('inc');
await host.idle();
host.sweep(100, 100); // a first sweep marks; the actor has not run since
for (const session of host.sweep(100, 100)) await store.save(session, host.hibernate(session));
console.log('stored:', await done(blobs('readonly').count()));
counter.send('inc'); // it is loaded from the store first; idle() waits for the load
counter.send('report');
await host.idle();
host.close();
db.close();
await done(indexedDB.deleteDatabase('tinyactors-blobs'));
```
```text title="output"
stored: 1
count 2
```
## Expect late timers in a hidden tab
In Node.js an open host with a pending deadline keeps the process alive. A page's hosts run only while the page does.
A host runs its turns as `MessageChannel` messages and arms one `setTimeout` at its next deadline. A browser throttles that timer while the tab is hidden.
Chromium runs a hidden tab's timers about once a second, and once a minute after a few minutes hidden. A dedicated Worker is throttled less, but still throttled.
A delayed `` or a timeout then comes late, when the timer fires, and is never lost.
## Snapshot the host when the page hides
A tab can be closed or discarded without notice, and its actors go with it. Keep what must survive in your store.
Hibernate actors as they go cold, or snapshot the host on `visibilitychange`, the last event a page is sure to get. Restore the snapshot when the page loads again.
This cart is snapshotted into IndexedDB, and a second load restores it with its item kept:
```javascript title="cart.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/wasm';
const done = (request) => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const opening = indexedDB.open('tinyactors-host', 1);
opening.onupgradeneeded = () => opening.result.createObjectStore('hosts');
const db = await done(opening);
const hosts = (mode) => db.transaction('hosts', mode).objectStore('hosts');
const options = () => ({ system: 'web', clock: new SimulatedClock(), log: (entry) => console.log(entry.text) });
const compiled = compileCharts([{ name: 'cart.scxml', text: `
` }]);
// at load: the host as the page left it, else a new one
async function load() {
const saved = await done(hosts('readonly').get('host'));
if (saved !== undefined) return Host.restore(saved, compiled, options());
const host = new Host(compiled, options());
host.spawn('cart', { name: 'cart' });
return host;
}
// when the page is hidden: a snapshot needs a quiescent host, so after idle()
async function save(host) {
await host.idle();
await done(hosts('readwrite').put(host.snapshot(), 'host'));
}
const host = await load();
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') save(host);
});
host.actor('cart').send('add', 'tea');
await save(host); // what the event would do, here at once
host.close();
const again = await load(); // the page loaded again
again.actor('cart').send('add', 'cake');
again.actor('cart').send('show');
await again.idle();
again.close();
compiled.close();
db.close();
await done(indexedDB.deleteDatabase('tinyactors-host'));
```
```text title="output"
cart: tea, cake
```
A snapshot leaves out the services your program runs, which a restore announces again ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).
## Size a page for its peak memory
The host's memory is the module's linear memory, which grows and is never given back: a page keeps its peak.
- **Hibernation makes room, not a smaller page.**: Hibernating actors frees room for others in that memory. A snapshot is packed there before it is copied out, so a 100 MB snapshot leaves the memory 100 MB larger.
- **4 GiB at most.**: wasm32 addresses 4 GiB, and a region that grows is copied before the old one is freed. So one host holds about two million resident actors at most, where `@tinyactors/node` goes on.
- **What the package hands out stays valid.**: Bytes, values and views are never views of that memory, so they stay valid when it grows.
What one actor costs in that memory is measured in [Capacity and memory](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs).
## Share a database with a Node.js server
A server on `@tinyactors/node` and a browser client on `@tinyactors/wasm` can share a database, but not the bytes a host packs.
- **Send values across.**: `encode` and `decode` are one format in both packages ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)): move work between the server and the client as events and their data, from one system to another.
- **A snapshot does not cross.**: It is the host's memory as the build that made it lays it out, and the addon is a 64-bit build where the module is a 32-bit one. Each package labels its snapshots with its own name and refuses the other's with `TA_ERROR_INVALID`, the message naming the package that made it.
- **A hibernation blob belongs to its host.**: It wakes in the host that hibernated it, or in one restored from that host's snapshot, which the other package cannot restore; another host's blob throws `TA_ERROR_INVALID`. Keep the server's blobs and the client's apart in the store, by host.
---
# Overview · tinyactors CLI
Kind: how-to. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Install the tinyactors command to compile, check, compare, draw and run charts and read application snapshots offline.
`tinyactors` is a 2 MB binary that compiles, checks, compares, draws and runs charts and reads snapshots. Production actors run in the libraries, not in the command, which prints Markdown, JSON (`-f json`) or XML.
- C: `mise use github:tinyactors-dev/tinyactors-core@0.5.0` (tinyactors-core 0.5.0, 26 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#c-0-5-0))
[Start the tutorial](https://tinyactors.dev/cli/tutorial/index.md) · [Look up a command](https://tinyactors.dev/cli/commands/index.md)
## Install `tinyactors` with mise or a release archive
Run `mise use github:tinyactors-dev/tinyactors-core`, which checks it against `SHA256SUMS`, or pin it as `"latest"` under `[tools]` in `mise.toml`. Release archives contain `bin/tinyactors` for static Linux (x86_64, aarch64) on any distribution and macOS (x86_64, arm64).
```toml
[tools]
"github:tinyactors-dev/tinyactors-core" = "latest"
```
## Follow a guide or look up commands
- **[Tutorial](https://tinyactors.dev/cli/tutorial/index.md)**: Compile an order chart, fix a misspelt event with `tinyactors lint` and find the path to `shipped`. Run one order locally with `tinyactors run`.
- **[CI checks](https://tinyactors.dev/cli/guides/ci/index.md)**: Fail pull requests on compile, `tinyactors lint`, `tinyactors fmt --check` and `tinyactors diff --breaking --exit-code` errors. Use the included GitHub Actions workflow to protect running actors.
- **[JSON-RPC scripting](https://tinyactors.dev/cli/guides/scripting/index.md)**: Drive a host over JSON-RPC 2.0 on standard input and output with `tinyactors run`. Spawn orders, answer payment requests, hold batches, advance the clock and generate a JSON Schema client.
- **[Offline snapshots](https://tinyactors.dev/cli/guides/snapshots/index.md)**: Read snapshots and hibernation blobs offline using `tinyactors actors` and `tinyactors inspect` without starting a host. Inspect each actor's state, queued events and timeouts, and check whether a blob wakes in a restored host.
- **[Reference](https://tinyactors.dev/cli/commands/index.md)**: Browse every `tinyactors` command grouped by job, plus the shared options accepted across all commands.
- **[CLI and libraries](https://tinyactors.dev/cli/why/index.md)**: See when a job belongs to the `tinyactors` command instead of the embeddable libraries. It covers runtime-free checks, pre-deploy diffs, offline snapshots and script workbenches.
---
# Tutorial · tinyactors CLI
Kind: tutorial. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Tutorial](https://tinyactors.dev/voices/tutorial.xml).
> Compile an order chart, fix a misspelt timeout with tinyactors lint, trace the path to shipped and run an order session.
In seven commands, you compile an order chart and catch a misspelt timeout event with `lint` without running it. After the fix, a scripted session retries an unanswered charge after 30 seconds and ends in `paid`.
- C: `mise use github:tinyactors-dev/tinyactors-core@0.5.0` (tinyactors-core 0.5.0, 26 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#c-0-5-0))
[Start the tutorial](https://tinyactors.dev/cli/tutorial/index.md#compile)
## 1. Compile the order chart
Your order chart starts in `open` to collect items, moves to `paying` at `checkout` and sends a charge request for the order total. When the payment service does not answer within 30 seconds, `paying` sends a delayed timeout event so the order retries up to three times before moving to `cancelled`.
```scxml title="order.scxml"
```
Save this chart as `order.scxml` and run `tinyactors compile` with `-o` so the compiler writes an image file at `order.tai` for your application. You will see zero diagnostics because the SCXML syntax is valid, which still leaves logic errors in your state transitions unchecked.
```shell
tinyactors compile order.scxml -o order.tai
```
```text title="output"
# Compile
- **Compiled**: yes
- **Output**: order.tai
- **Emit**: image
- **Bytes**: 2776
- **Hash**: c4c69c91aae0ba21
- **Charts**: 1
- **Boot actors**: 1
## Diagnostics
_none_
```
## 2. Catch unhandled events with lint
Valid syntax does not guarantee your order can finish, so run `tinyactors lint` to inspect the chart's transition logic without executing a session. The linter compares events sent to the chart against its transitions, which lets you catch unhandled events before testing a live session.
```shell
tinyactors lint order.scxml
```
```text title="output"
# Lint
- **Warnings**: 1
- **Notes**: 0
- **Denied**: 0
## Findings
| Rule | Severity | Chart | State | Transition | Event | Line | Message |
| --- | --- | --- | --- | --- | --- | --- | --- |
| unhandled-event | warning | order | paying | | payment.timeout | 0 | the event is sent to the chart itself, and no transition there handles it |
```
The report shows one `unhandled-event` warning in `paying` because that state sends `payment.timeout` to the chart while its transitions listen for `payment.timedout`. Without a matching transition, an order whose payment service never answers misses the 30-second timeout event and stays in `paying` instead of retrying or cancelling.
## 3. Fix the event and check again
Update both transitions in `paying` from `payment.timedout` to `payment.timeout` so their event list matches what the state sends after 30 seconds. Changing both lines fixes the retry loop when `attempts < 3` and restores the final transition to `cancelled` after three failed attempts.
```scxml title="order.scxml"
```
Next, run `tinyactors check` with `-W` to validate `order.scxml` and turn compiler warnings into errors without writing an output file. Seeing `Valid: yes` and zero diagnostics confirms that the updated chart compiles with neither syntax errors nor warnings.
```shell
tinyactors check -W order.scxml
```
```text title="output"
# Check
## Inputs
- order.scxml
- **Valid**: yes
- **Bytes**: 2720
- **Hash**: 5e66ab57693504aa
- **Charts**: 1
- **Boot actors**: 1
## Diagnostics
_none_
```
Now run `tinyactors lint` with `--deny all` so any remaining warning or note fails the command with exit code 1. Because both transitions now handle `payment.timeout`, `lint` reports zero findings and exits with 0, which shows no unhandled timeout events remain.
```shell
tinyactors lint --deny all order.scxml
```
```text title="output"
# Lint
- **Warnings**: 0
- **Notes**: 0
- **Denied**: 0
## Findings
_none_
```
## 4. Trace the path to shipped
Run `tinyactors path` with `--to shipped` to verify that an order starting in `open` can reach the final `shipped` state. The output lists three transitions through `paying` and `paid` and notes the `total > 0` condition on `checkout`, so an order must have a positive total before charging.
```shell
tinyactors path order.scxml --to shipped
```
```text title="output"
# Path
- **Chart**: order
- **From**:
- **To**: shipped
- **Result**: found
- **Meaning**: the steps below reach it, if their events come and their conditions hold
- **Transitions**: 3
- **Explored**: 5
- **Start**: open
## Steps
| Step | Events | Eventless | Condition | Source | Targets | Active |
| --- | --- | --- | --- | --- | --- | --- |
| 1 | checkout | no | total > 0 | open | paying | paying |
| 2 | charge.ok | no | | paying | paid | paid |
| 3 | shipped | no | | paid | shipped | shipped |
```
## 5. Draw the order chart
Run `tinyactors graph` with `-f svg` and redirect the output to `order.svg` to inspect your order chart as state boxes and labelled transition routes. The resulting diagram adapts to your system's light or dark setting and lets you verify that `paying` loops back to itself on retries before reaching `paid` or `cancelled`.
```shell
tinyactors graph -f svg order.scxml > order.svg
```

## 6. Run an order session
To test your retry flow, save these JSON-RPC requests in `session.jsonl` so you can pipe them into `tinyactors run` one request per line. The script spawns an order actor, adds a pen priced at 1200, sends `checkout`, advances the clock by 30 seconds and answers the second charge.
```text title="session.jsonl"
{"jsonrpc":"2.0","id":1,"method":"run.spawn","params":{"chart":"order","name":"order-1"}}
{"jsonrpc":"2.0","id":2,"method":"run.send","params":{"target":1,"event":"item.added","data":{"sku":"pen","price":1200}}}
{"jsonrpc":"2.0","id":3,"method":"run.send","params":{"target":1,"event":"checkout"}}
{"jsonrpc":"2.0","id":4,"method":"run.turn"}
{"jsonrpc":"2.0","id":5,"method":"run.advanceTime","params":{"by":"30s"}}
{"jsonrpc":"2.0","id":6,"method":"run.turn"}
{"jsonrpc":"2.0","id":7,"method":"run.send","params":{"target":1,"event":"charge.ok","sendid":"pay","origintype":"payments","data":{"charge":"ch_81"}}}
{"jsonrpc":"2.0","id":8,"method":"run.turn"}
{"jsonrpc":"2.0","id":9,"method":"actor.state","params":{"session":1}}
```
Run `tinyactors run` with `--io-processor payments` and redirect `session.jsonl` to standard input so your session handles outgoing `payments` requests without an external service. When the order enters `paying`, the command writes an `effect.send` notification for each `charge` event, which lets your script observe and answer outgoing payment requests.
```shell
tinyactors run --io-processor payments order.scxml < session.jsonl
```
```text title="output"
{"jsonrpc":"2.0","id":1,"result":{"session":1,"address":"tinyactors://tinyactors-run/#_scxml_1"}}
{"jsonrpc":"2.0","id":2,"result":{}}
{"jsonrpc":"2.0","id":3,"result":{}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":1,"index":0,"session":1,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":1200},"traceparent":"00-bba5ad4a1f842e59ffef8375d9ebcaca-94e8a8f3181c87c4-03","waiting":true}}
{"jsonrpc":"2.0","id":4,"result":{"status":"idle","runs":2,"fuel":22,"time":0,"nextDeadline":30000000000}}
{"jsonrpc":"2.0","id":5,"result":{"time":30000000000,"wallNs":30000000000}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":2,"index":0,"session":1,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":1200},"traceparent":"00-bba5ad4a1f842e59ffef8375d9ebcaca-14c089f1b8c1eac4-03","waiting":true}}
{"jsonrpc":"2.0","id":6,"result":{"status":"idle","runs":2,"fuel":14,"time":30000000000,"nextDeadline":60000000000}}
{"jsonrpc":"2.0","id":7,"result":{}}
{"jsonrpc":"2.0","id":8,"result":{"status":"idle","runs":1,"fuel":12,"time":30000000000,"nextDeadline":null}}
{"jsonrpc":"2.0","id":9,"result":{"value":"paid","history":{}}}
```
Request 4 leaves the actor idle with a 30-second deadline, so advancing the clock in request 5 lets request 6 fire `payment.timeout` and emit a second `charge` notification. Request 7 then supplies `charge.ok`, which cancels the next 30-second deadline in request 8 when the actor leaves `paying`. Request 9 inspects the actor state and finds it in `paid`.
## Put the checks in your build
Once your chart works locally, run `check` and `lint` in CI so your build catches syntax errors or unhandled events before a pull request merges. You can pair those checks with `fmt` and `diff`, or drive sessions from a script that pauses and answers outgoing sends.
- **[Check charts in CI](https://tinyactors.dev/cli/guides/ci/index.md)**: Automate `check`, `lint`, `fmt` and `diff` on every pull request.
- **[Drive a host from a script](https://tinyactors.dev/cli/guides/scripting/index.md)**: Pause an outgoing send until your script replies to it.
---
# CI checks · tinyactors CLI
Kind: how-to. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Fail pull requests on compile, tinyactors lint, tinyactors fmt --check or tinyactors diff --breaking --exit-code errors with a GitHub Actions workflow.
Four commands fail a pull request with exit status 1. The last, `diff`, compares the change with the version your actors run now.
[Copy the workflow](https://tinyactors.dev/cli/guides/ci/index.md#workflow) · [Learn the commands](https://tinyactors.dev/cli/tutorial/index.md)
## 1. Add the command to mise.toml
mise installs the release on each runner and checks it against the release's checksums. Name a version in place of `latest` to pin it.
```toml title="mise.toml"
[tools]
"github:tinyactors-dev/tinyactors-core" = "latest"
```
## 2. Keep the image you deploy
Compile the chart when you deploy it and store `deployed.tai` where the next build can fetch it. The deployed chart here is the [tutorial's](https://tinyactors.dev/cli/tutorial/index.md) order.
```shell
tinyactors compile order.scxml -o deployed.tai
```
```text title="output"
# Compile
- **Compiled**: yes
- **Output**: deployed.tai
- **Emit**: image
- **Bytes**: 2720
- **Hash**: 5e66ab57693504aa
- **Charts**: 1
- **Boot actors**: 1
## Diagnostics
_none_
```
## 3. Check, lint and format the change
The pull request renames `paying` to `charging`. `check -W` treats a warning as an error, and the renamed chart compiles with neither.
```scxml title="order.scxml"
```
```shell
tinyactors check -W order.scxml
```
```text title="output"
# Check
## Inputs
- order.scxml
- **Valid**: yes
- **Bytes**: 2720
- **Hash**: 20a8e7019c80b057
- **Charts**: 1
- **Boot actors**: 1
## Diagnostics
_none_
```
With `--deny all`, any finding of `lint` exits with 1, such as an unreachable state. The renamed chart has none.
```shell
tinyactors lint --deny all order.scxml
```
```text title="output"
# Lint
- **Warnings**: 0
- **Notes**: 0
- **Denied**: 0
## Findings
_none_
```
Charts in one layout keep a pull request's diff to its real edits. `fmt --check` fails on a file out of layout and changes nothing; `fmt -w` rewrites it.
```shell
tinyactors fmt --check order.scxml
```
```text title="output"
# Fmt
- **Mode**: check
- **Files**: 1
- **Changed**: 0
- **Refused**: 0
## Results
| File | Changed | Refused | Image |
| --- | --- | --- | --- |
| order.scxml | no | no | same |
## Diagnostics
_none_
```
## 4. Compare the change with the deployed image
The change passes every check, yet orders waiting in `paying` would lose their state. `diff --breaking --exit-code` lists the changes that break them and exits with 1.
```shell
tinyactors diff --breaking --exit-code deployed.tai order.scxml
```
```text title="output"
# Diff
## Old
- **Path**: deployed.tai
- **Hash**: 5e66ab57693504aa
- **Charts**: 1
## New
- **Path**: order.scxml
- **Hash**: 20a8e7019c80b057
- **Charts**: 1
- **Identical**: no
## Summary
- **Charts added**: 0
- **Charts removed**: 0
- **Charts changed**: 1
- **Charts unchanged**: 0
- **Differences**: 9
- **Breaking**: 1
## Charts
### Chart 1: order
- **Name**: order
- **Change**: changed
- **Datamodel**: ecmascript
- **Binding**: early
#### States
| State | Change | Breaking | Before | After |
| --- | --- | --- | --- | --- |
| paying | removed | yes | atomic in /scxml | |
#### Transitions
_none_
#### Data
_none_
#### Actions
_none_
#### Invokes
_none_
#### Events
_none_
## Events added
_none_
## Events removed
_none_
- **Migration**: Chart order: Actors in removed states are completed to a legal configuration of the new version, the nearest kept ancestor entering its initial state, and no onentry runs: paying → open.
```
It exits with status 1: a migration would put each order waiting in `paying` back in `open`, its charge already sent.
- **A removed state sends actors to an ancestor**: An actor in a removed state enters its nearest kept ancestor's initial state, and no entry action runs. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#breaking-or-behaviour)
Keep the state's id, or deploy the new version without migrating, so running orders finish on the old one.
## 5. Run the checks on every pull request
This GitHub Actions job installs mise's tools with [mise-action](https://github.com/jdx/mise-action) and runs the four commands. Fetch `deployed.tai` from wherever your deploy stores it.
```yaml title=".github/workflows/charts.yml"
name: charts
on: pull_request
jobs:
charts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jdx/mise-action@v2
- run: tinyactors check -W order.scxml
- run: tinyactors lint --deny all order.scxml
- run: tinyactors fmt --check order.scxml
- run: tinyactors diff --breaking --exit-code deployed.tai order.scxml
```
- **Exit status 1 means a check failed**: Status 2 is a command line not understood, and 3 a file that could not be read. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#exit-status)
---
# JSON-RPC scripting · tinyactors CLI
Kind: how-to. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Drive tinyactors run over JSON-RPC 2.0 to spawn orders, answer payment requests, hold batches, move the clock and generate a client.
`tinyactors run` serves one host over JSON-RPC 2.0 on standard input and output. Your script spawns orders, answers their payment requests and moves a simulated clock.
## Start a host on your charts
Start one host with `--io-processor payments` so `tinyactors run` routes external payment requests back to your script. Closing standard input stops the host.
```shell
tinyactors run --io-processor payments --system shop order.scxml < requests.jsonl
```
This order chart asks `payments` for a charge, retries after 30 seconds of silence and gives up after three attempts.
```scxml title="order.scxml"
```
## Answer each send the actor makes
Send `run.*` requests to control the host and forwarded methods such as `actor.state` to query actors. Reply to each `effect.send` notification with `run.send`.
```text title="requests.jsonl"
{"jsonrpc":"2.0","id":1,"method":"run.spawn","params":{"chart":"order","name":"order-1"}}
{"jsonrpc":"2.0","id":2,"method":"run.send","params":{"target":1,"event":"item.added","data":{"sku":"pen","price":1200}}}
{"jsonrpc":"2.0","id":3,"method":"run.send","params":{"target":1,"event":"checkout"}}
{"jsonrpc":"2.0","id":4,"method":"run.turn","params":{"hold":true}}
{"jsonrpc":"2.0","id":5,"method":"run.send","params":{"target":1,"event":"charge.ok","sendid":"pay","origintype":"payments","data":{"charge":"ch_81"}}}
{"jsonrpc":"2.0","id":6,"method":"run.turn"}
{"jsonrpc":"2.0","id":7,"method":"actor.state","params":{"session":1}}
{"jsonrpc":"2.0","id":8,"method":"run.send","params":{"target":1,"event":"shipped"}}
{"jsonrpc":"2.0","id":9,"method":"run.turn"}
{"jsonrpc":"2.0","id":10,"method":"run.spawn","params":{"chart":"order","name":"order-2"}}
{"jsonrpc":"2.0","id":11,"method":"run.send","params":{"target":2,"event":"item.added","data":{"sku":"ink","price":450}}}
{"jsonrpc":"2.0","id":12,"method":"run.send","params":{"target":2,"event":"checkout"}}
{"jsonrpc":"2.0","id":13,"method":"run.turn"}
{"jsonrpc":"2.0","id":14,"method":"run.advanceTime","params":{"by":"30s"}}
{"jsonrpc":"2.0","id":15,"method":"run.turn"}
{"jsonrpc":"2.0","id":16,"method":"actor.get","params":{"session":2}}
```
```text title="output"
{"jsonrpc":"2.0","id":1,"result":{"session":1,"address":"tinyactors://shop/#_scxml_1"}}
{"jsonrpc":"2.0","id":2,"result":{}}
{"jsonrpc":"2.0","id":3,"result":{}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":1,"index":0,"session":1,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":1200},"traceparent":"00-bba5ad4a1f842e59ffef8375d9ebcaca-94e8a8f3181c87c4-03","waiting":true}}
{"jsonrpc":"2.0","id":4,"result":{"status":"held","runs":1,"fuel":19,"time":0,"nextDeadline":null}}
{"jsonrpc":"2.0","id":5,"result":{}}
{"jsonrpc":"2.0","id":6,"result":{"status":"idle","runs":1,"fuel":14,"time":0,"nextDeadline":null}}
{"jsonrpc":"2.0","id":7,"result":{"value":"paid","history":{}}}
{"jsonrpc":"2.0","id":8,"result":{}}
{"jsonrpc":"2.0","method":"effect.done","params":{"batch":3,"index":0,"session":1,"name":"order-1","final":"shipped","data":{"charge":"ch_81"}}}
{"jsonrpc":"2.0","id":9,"result":{"status":"idle","runs":1,"fuel":6,"time":0,"nextDeadline":null}}
{"jsonrpc":"2.0","id":10,"result":{"session":2,"address":"tinyactors://shop/#_scxml_2"}}
{"jsonrpc":"2.0","id":11,"result":{}}
{"jsonrpc":"2.0","id":12,"result":{}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":4,"index":0,"session":2,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":450},"traceparent":"00-7efdaa95605dfc9c4bde97c0a78eaab8-63c3721caf3ede87-03","waiting":true}}
{"jsonrpc":"2.0","id":13,"result":{"status":"idle","runs":2,"fuel":22,"time":0,"nextDeadline":30000000000}}
{"jsonrpc":"2.0","id":14,"result":{"time":30000000000,"wallNs":30000000000}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":5,"index":0,"session":2,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":450},"traceparent":"00-7efdaa95605dfc9c4bde97c0a78eaab8-9f49d57c96da3d8f-03","waiting":true}}
{"jsonrpc":"2.0","id":15,"result":{"status":"idle","runs":2,"fuel":14,"time":30000000000,"nextDeadline":60000000000}}
{"jsonrpc":"2.0","id":16,"result":{"session":2,"segment":0,"chart":"order","parent":null,"mailbox":0,"invocations":0,"timers":[{"sendid":"deadline","event":"payment.timeout","due":60000000000}],"timersPending":1}}
```
The first order is paid and shipped; the second gets no answer, and its charge goes out again at 30 seconds.
## Answer a send before its sender moves on
Pass `"hold": true` to `run.turn` to keep an actor waiting after a send marked `"waiting": true`. Above, the order stays in `paying` until your script answers in request 5 and turns in request 6.
Without `hold`, the sender continues immediately and any reply arrives later as an ordinary event.
## Move the clock yourself
Advance the host's simulated clock with `run.advanceTime` instead of waiting in real time. Request 14 skips 30 seconds forward so the next turn fires the second order's timeout immediately.
- **A session repeats byte for byte**: The clock is simulated and `Math.random` has a fixed seed, so the same requests write the same lines, trace ids included. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#startup-and-the-end-of-input)
## Generate a client from the schema
Run `tinyactors run --schema` to print the JSON Schema for every request, response and notification. You can also download it from the [run command's page](https://tinyactors.dev/cli/commands/run/index.md#see).
- **The protocol is experimental**: It may change in any release until a second client uses it. The schema describes the release you have. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#run)
---
# Offline snapshots · tinyactors CLI
Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Read snapshot state, queued events, pending timeouts and hibernation blobs offline with tinyactors actors and tinyactors inspect.
A snapshot file holds the actors of a host and their pending timeouts. `tinyactors actors` reads from it which state each order is in, without starting a host.
## 1. Take a snapshot of the host
Your application writes a snapshot through the library, and `tinyactors run` writes one with `run.snapshot`. This session spawns 20 orders, pays some, adds the next version, hibernates order 17, then snapshots.
```shell
tinyactors run --config shop.json --system shop system.xml < shop.jsonl
```
```text title="shop.jsonl"
[{"jsonrpc":"2.0","id":1,"method":"run.spawn","params":{"chart":"order","name":"order-1"}},{"jsonrpc":"2.0","id":2,"method":"run.spawn","params":{"chart":"order","name":"order-2"}},{"jsonrpc":"2.0","id":3,"method":"run.spawn","params":{"chart":"order","name":"order-3"}},{"jsonrpc":"2.0","id":4,"method":"run.spawn","params":{"chart":"order","name":"order-4"}},{"jsonrpc":"2.0","id":5,"method":"run.spawn","params":{"chart":"order","name":"order-5"}},{"jsonrpc":"2.0","id":6,"method":"run.spawn","params":{"chart":"order","name":"order-6"}},{"jsonrpc":"2.0","id":7,"method":"run.spawn","params":{"chart":"order","name":"order-7"}},{"jsonrpc":"2.0","id":8,"method":"run.spawn","params":{"chart":"order","name":"order-8"}},{"jsonrpc":"2.0","id":9,"method":"run.spawn","params":{"chart":"order","name":"order-9"}},{"jsonrpc":"2.0","id":10,"method":"run.spawn","params":{"chart":"order","name":"order-10"}},{"jsonrpc":"2.0","id":11,"method":"run.spawn","params":{"chart":"order","name":"order-11"}},{"jsonrpc":"2.0","id":12,"method":"run.spawn","params":{"chart":"order","name":"order-12"}},{"jsonrpc":"2.0","id":13,"method":"run.spawn","params":{"chart":"order","name":"order-13"}},{"jsonrpc":"2.0","id":14,"method":"run.spawn","params":{"chart":"order","name":"order-14"}},{"jsonrpc":"2.0","id":15,"method":"run.spawn","params":{"chart":"order","name":"order-15"}},{"jsonrpc":"2.0","id":16,"method":"run.spawn","params":{"chart":"order","name":"order-16"}},{"jsonrpc":"2.0","id":17,"method":"run.spawn","params":{"chart":"order","name":"order-17"}},{"jsonrpc":"2.0","id":18,"method":"run.spawn","params":{"chart":"order","name":"order-18"}},{"jsonrpc":"2.0","id":19,"method":"run.spawn","params":{"chart":"order","name":"order-19"}},{"jsonrpc":"2.0","id":20,"method":"run.spawn","params":{"chart":"order","name":"order-20"}}]
[{"jsonrpc":"2.0","id":21,"method":"run.send","params":{"target":1,"event":"item.added","data":{"sku":"pen","price":100}}},{"jsonrpc":"2.0","id":22,"method":"run.send","params":{"target":2,"event":"item.added","data":{"sku":"pen","price":200}}},{"jsonrpc":"2.0","id":23,"method":"run.send","params":{"target":3,"event":"item.added","data":{"sku":"pen","price":300}}},{"jsonrpc":"2.0","id":24,"method":"run.send","params":{"target":4,"event":"item.added","data":{"sku":"pen","price":400}}},{"jsonrpc":"2.0","id":25,"method":"run.send","params":{"target":5,"event":"item.added","data":{"sku":"pen","price":500}}},{"jsonrpc":"2.0","id":26,"method":"run.send","params":{"target":6,"event":"item.added","data":{"sku":"pen","price":600}}},{"jsonrpc":"2.0","id":27,"method":"run.send","params":{"target":7,"event":"item.added","data":{"sku":"pen","price":700}}},{"jsonrpc":"2.0","id":28,"method":"run.send","params":{"target":8,"event":"item.added","data":{"sku":"pen","price":800}}},{"jsonrpc":"2.0","id":29,"method":"run.send","params":{"target":9,"event":"item.added","data":{"sku":"pen","price":900}}},{"jsonrpc":"2.0","id":30,"method":"run.send","params":{"target":10,"event":"item.added","data":{"sku":"pen","price":1000}}},{"jsonrpc":"2.0","id":31,"method":"run.send","params":{"target":11,"event":"item.added","data":{"sku":"pen","price":1100}}},{"jsonrpc":"2.0","id":32,"method":"run.send","params":{"target":12,"event":"item.added","data":{"sku":"pen","price":1200}}},{"jsonrpc":"2.0","id":33,"method":"run.send","params":{"target":13,"event":"item.added","data":{"sku":"pen","price":1300}}},{"jsonrpc":"2.0","id":34,"method":"run.send","params":{"target":14,"event":"item.added","data":{"sku":"pen","price":1400}}},{"jsonrpc":"2.0","id":35,"method":"run.send","params":{"target":15,"event":"item.added","data":{"sku":"pen","price":1500}}},{"jsonrpc":"2.0","id":36,"method":"run.send","params":{"target":16,"event":"item.added","data":{"sku":"pen","price":1600}}},{"jsonrpc":"2.0","id":37,"method":"run.send","params":{"target":17,"event":"item.added","data":{"sku":"pen","price":1700}}},{"jsonrpc":"2.0","id":38,"method":"run.send","params":{"target":18,"event":"item.added","data":{"sku":"pen","price":1800}}},{"jsonrpc":"2.0","id":39,"method":"run.send","params":{"target":19,"event":"item.added","data":{"sku":"pen","price":1900}}},{"jsonrpc":"2.0","id":40,"method":"run.send","params":{"target":20,"event":"item.added","data":{"sku":"pen","price":2000}}},{"jsonrpc":"2.0","id":41,"method":"run.turn"}]
[{"jsonrpc":"2.0","id":42,"method":"run.send","params":{"target":1,"event":"checkout"}},{"jsonrpc":"2.0","id":43,"method":"run.send","params":{"target":2,"event":"checkout"}},{"jsonrpc":"2.0","id":44,"method":"run.send","params":{"target":3,"event":"checkout"}},{"jsonrpc":"2.0","id":45,"method":"run.send","params":{"target":4,"event":"checkout"}},{"jsonrpc":"2.0","id":46,"method":"run.send","params":{"target":5,"event":"checkout"}},{"jsonrpc":"2.0","id":47,"method":"run.send","params":{"target":6,"event":"checkout"}},{"jsonrpc":"2.0","id":48,"method":"run.send","params":{"target":7,"event":"checkout"}},{"jsonrpc":"2.0","id":49,"method":"run.send","params":{"target":8,"event":"checkout"}},{"jsonrpc":"2.0","id":50,"method":"run.send","params":{"target":9,"event":"checkout"}},{"jsonrpc":"2.0","id":51,"method":"run.send","params":{"target":10,"event":"checkout"}},{"jsonrpc":"2.0","id":52,"method":"run.turn"}]
[{"jsonrpc":"2.0","id":53,"method":"run.send","params":{"target":1,"event":"charge.ok","sendid":"pay","origintype":"payments","data":{"charge":"ch_81"}}},{"jsonrpc":"2.0","id":54,"method":"run.send","params":{"target":2,"event":"charge.ok","sendid":"pay","origintype":"payments","data":{"charge":"ch_82"}}},{"jsonrpc":"2.0","id":55,"method":"run.send","params":{"target":3,"event":"charge.ok","sendid":"pay","origintype":"payments","data":{"charge":"ch_83"}}},{"jsonrpc":"2.0","id":56,"method":"run.send","params":{"target":4,"event":"charge.ok","sendid":"pay","origintype":"payments","data":{"charge":"ch_84"}}},{"jsonrpc":"2.0","id":57,"method":"run.send","params":{"target":5,"event":"charge.ok","sendid":"pay","origintype":"payments","data":{"charge":"ch_85"}}},{"jsonrpc":"2.0","id":58,"method":"run.turn"}]
[{"jsonrpc":"2.0","id":59,"method":"run.send","params":{"target":1,"event":"shipped"}},{"jsonrpc":"2.0","id":60,"method":"run.send","params":{"target":2,"event":"shipped"}},{"jsonrpc":"2.0","id":61,"method":"run.send","params":{"target":18,"event":"cancel"}},{"jsonrpc":"2.0","id":62,"method":"run.send","params":{"target":19,"event":"cancel"}},{"jsonrpc":"2.0","id":63,"method":"run.send","params":{"target":20,"event":"cancel"}},{"jsonrpc":"2.0","id":64,"method":"run.turn"}]
[{"jsonrpc":"2.0","id":65,"method":"run.advanceTime","params":{"by":"10s"}},{"jsonrpc":"2.0","id":66,"method":"run.turn"}]
{"jsonrpc":"2.0","id":67,"method":"run.addImage","params":{"files":["order-v2.scxml"]}}
[{"jsonrpc":"2.0","id":68,"method":"run.spawn","params":{"chart":"order","name":"order-21"}},{"jsonrpc":"2.0","id":69,"method":"run.turn"}]
{"jsonrpc":"2.0","id":70,"method":"run.hibernate","params":{"session":17}}
{"jsonrpc":"2.0","id":71,"method":"run.snapshot","params":{"path":"shop.snapshot"}}
```
## 2. Ask the file about one order
Order 6 is in `paying`, waiting for its charge. Its `payment.timeout` fires 20 seconds after the snapshot's time.
```shell
tinyactors actors --session 6 shop.snapshot
```
```text title="output"
# Actors
- **Snapshot**: shop.snapshot
- **System ID**: shop
- **Time**: 10000
## Actors
### Actor 1: order-6
- **Session**: 6
- **Name**: order-6
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paying
#### Mailbox
_none_
#### Delayed
| Event | Sendid | Due | In |
| --- | --- | --- | --- |
| payment.timeout | deadline | 30000 | 20s |
```
Without `--session`, `actors` lists every actor, and `--chart order` keeps one chart's.
## 3. Check a stored blob before waking it
Order 17 was hibernated: its state is in a blob in your store, which wakes only in its own host. `inspect` reads the blob and checks that this snapshot's host can wake it.
```shell
tinyactors inspect order-17.blob shop.snapshot
```
```text title="output"
# Inspect
- **From**: hibernation blob
- **Bytes**: 290
- **Format**: 5
- **Readable**: yes
- **Session**: 17
- **Image hash**: 1c8ca2cc7138f14e
- **Image matches**: yes
- **Identity**: 000000007952af3e
- **Wakes**: only in the host that hibernated it, or a host restored from its snapshot: one of this identity, running this image
- **Wakes in that snapshot**: yes
## Sessions
### Session 1: order
- **Session**: 17
- **Chart index**: 0
- **Chart**: order
- **Macrosteps**: 2
#### Configuration
- open
#### Delayed
_none_
#### Datamodel
- **Bytes**: 166
- **Encoding**: opaque
- **Note**: not one CBOR item: the datamodel's own encoding (the ECMAScript datamodel's is quickjs's), which only that datamodel reads
```
## 4. Inspect the snapshot's segments and states
- **[`tinyactors inspect shop.snapshot`](https://tinyactors.dev/cli/commands/inspect/index.md)**: The snapshot's time and its segments, one per image the host added, with how many actors each holds.
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: The states of the chart a segment runs, with `--segment` for an older version.
- **Each release reads its own formats**: Snapshots and blobs are raw memory of one build of the library, each format with a version. The command reads its own library's formats, and names any other. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#inputs)
---
# Cheat sheet · tinyactors CLI
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Reference sheet of tinyactors CLI commands by task, covering compilation, validation, formatting, inspection, diffing, graphing, execution, and snapshot reading.
Copy and adapt tinyactors commands for compiling, checking, inspecting, graphing, comparing, and running statecharts and reading offline snapshots.
[See every command](https://tinyactors.dev/cli/commands/index.md)
## Compile and check charts
```shell
# Compile two charts into one image
tinyactors compile order.scxml payment.scxml -o order.tai
# Emit a compiled chart as a C source array
tinyactors compile order.scxml --emit c --symbol order_image -o order_image.c
# Validate multiple SCXML files
tinyactors check charts/*.scxml
# Treat all lint warnings except unsent-event as errors
tinyactors lint --deny all --allow unsent-event system.xml
# Check whether SCXML files match canonical formatting
tinyactors fmt --check charts/*.scxml
```
## Inspect chart structure
```shell
# Summarize the contents of a compiled image
tinyactors inspect order.tai
# List all states in a chart
tinyactors states order.scxml
# Output transitions from an image as JSON
tinyactors transitions -f json order.tai
# List every event of a system's charts
tinyactors events system.xml
# List only guard condition expressions
tinyactors expressions --kind condition order.scxml
```
## Trace paths and draw graphs
```shell
# Find the shortest way to shipped
tinyactors path order.scxml --to shipped
# Confirm paid cannot be reached from cancelled
tinyactors path order.scxml --from cancelled --to paid --unreachable
# Render a statechart diagram as SVG
tinyactors graph -f svg order.scxml > order.svg
# Render a left-to-right diagram with the dark theme
tinyactors graph -f svg --direction right --theme dark order.scxml > order.svg
# Render a top-level diagram with checkout folded
tinyactors graph -f svg --depth 1 --fold checkout shop.scxml > overview.svg
```
## Compare chart versions
```shell
# Compare a compiled image against an SCXML file
tinyactors diff order-v1.tai order-v2.scxml
# Fail with a non-zero exit code on breaking changes
tinyactors diff --breaking --exit-code deployed.tai order.scxml
# Output structural differences for one chart as JSON
tinyactors diff -f json --chart order old.tai new.tai
```
## Run charts and scripts
```shell
# Serve a host for one chart on standard input
tinyactors run order.scxml
# Run multiple charts with a configuration file
tinyactors run --config shop.json order.scxml payment.scxml
# Drive a chart over JSON-RPC from standard input
tinyactors run --io-processor payments --system shop order.scxml < requests.jsonl
# Write the JSON-RPC schema to a file
tinyactors run --schema > run.schema.json
```
## Read snapshots and blobs
```shell
# Summarize the contents of a snapshot file
tinyactors inspect shop.snapshot
# Check whether a blob wakes in the snapshot's host
tinyactors inspect order-17.blob shop.snapshot
# List all actors recorded in a snapshot
tinyactors actors shop.snapshot
# Filter snapshot actors by chart name and session
tinyactors actors --chart order --session 17 shop.snapshot
# List the states of segment 1's charts
tinyactors states --segment 1 shop.snapshot
```
---
# CLI and libraries · tinyactors CLI
Kind: explanation. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Explanation](https://tinyactors.dev/voices/explanation.xml).
> Understand when to use the tinyactors command for CI checks, diffs, offline snapshots and scripting instead of the libraries.
The `tinyactors` command handles pre-merge checks, pre-deploy diffs and offline snapshot reads without a language runtime. It also provides a workbench for scripts and agents driving hosts over JSON-RPC. Production actors run in the embeddable tinyactors libraries inside an application's process, not in the command.
[Start the tutorial](https://tinyactors.dev/cli/tutorial/index.md) · [Check charts in CI](https://tinyactors.dev/cli/guides/ci/index.md) · [Look up a command](https://tinyactors.dev/cli/commands/index.md)
## The command needs no language runtime
> Your application runs its actors through a library inside its own process. Checking a chart in CI, reviewing a deploy or reading a stored snapshot happens outside that process, and a script for each adds a language runtime to every build job.
A chart is an SCXML file that describes one kind of actor: its states, the events it handles and the transitions between them. A host is the runtime that runs actors from compiled charts, called an image, a `.tai` file. The libraries embed a host in your application, and the `tinyactors` command reads and runs the same charts from a shell.
The command is built from the same C libraries, and none of them carries it, so your application pays nothing for it at run time. Each tinyactors-core release ships it for Linux and macOS, and mise installs it and checks it against the release's checksums. A build job then needs no Node.js, Python or C compiler to check its charts.
Every command answers in Markdown for people, or in JSON or XML for scripts, with the same members in the same order. A CI job reads `charts[0].states` from the JSON that a person reads as a table.
- **One Linux file runs on every distribution**: The Linux program is linked statically against musl, so it runs on glibc and musl systems alike. The macOS one loads only libSystem. Source: [tinyactors-core, `docs/distribution.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/distribution.md#the-tinyactors-command)
- **About 2 MB, with the host inside**: The x86_64 Linux program is 2,080,424 bytes, measured on 2026-11-25. It carries the compiler, the host and the quickjs JavaScript engine. Source: [tinyactors-core, `docs/distribution.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/distribution.md#the-tinyactors-command)
## Charts are checked before they merge
> A misspelt event name compiles, and the order that waits for it waits forever. Review of the XML misses it, and booting the application's test suite to find it costs minutes on every pull request.
`check` compiles charts and writes nothing, and `-W` refuses a chart that compiles with a warning. `lint` reads the compiled chart without running it and reports what cannot work as written: unreachable states, dead ends, shadowed transitions and events nothing handles. `fmt --check` holds every chart to one canonical layout, so a diff shows only real edits.
With `-W`, `--deny` and `--check`, each exits with status 1 when it finds something a build should stop for, so a CI step needs no parsing. `path` answers which transitions lead from where an actor starts to a given state, and `graph -f svg` draws the chart for a review. A chart that passes them all is valid on its own, which says nothing yet about the actors already running its previous version.
- **Unreachable means unreachable at run time**: `lint` lets any event come at any time and every condition hold. A state it finds unreachable stays so whatever happens when the chart runs. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#lint)
- **A failed check exits with 1**: `check` exits with 1 on a chart that does not compile. So do `lint --deny` on a denied finding and `fmt --check` on a file to rewrite. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#exit-status)
## A diff shows what a deploy does
> A new version renames the state `paying` to `charging`, and the XML diff is two short lines. Orders waiting in `paying` would lose their place when they move to it.
After a host loads a new version of a chart, a migration moves running actors to it by state id, keeping the variables both versions declare and running no entry actions. A state the new version lacks leaves the actor in its nearest kept ancestor's initial state. `tinyactors diff` compares two versions as statecharts and marks each change that breaks the actors running the old one.
An added state or transition changes what actors do next and is not breaking. A removed state, a removed variable or an event a state no longer handles changes what actors hold, and `diff --breaking --exit-code` fails the build on those. The answer ends with what a migration would do, such as `paying → open`. Once a version runs, the next questions come from the actors themselves.
- **Breaking changes alter what running actors hold**: The command lists each breaking change with what a running actor gets, from a removed state to a datamodel changed. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#breaking-or-behaviour)
## A snapshot is read without a host
> An order has waited in `paying` for an hour in production. Its logs tell what happened before, not which state, queued events or pending timeout the order holds now.
A host can write a snapshot, a file holding every actor it runs, and an idle actor can be written out alone as a hibernation blob for your store. `tinyactors actors` lists each actor of a snapshot: its chart and segment, its active states, and the events and delayed sends it waits for.
`tinyactors inspect` says what a snapshot or blob holds, and whether a blob wakes in the host a snapshot restores. Neither runs a chart: the command reads the library's own memory layout. That layout belongs to one build, so read a snapshot with the command of the release that wrote it. Before any host has run a chart, the command can run it too.
- **Nothing runs while a snapshot is read**: The command restores the snapshot's memory with datamodels that do nothing, so no chart code is called. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#snapshots-and-blobs)
- **Each release reads its own formats**: Snapshots and blobs are raw memory with a format version. The command reads its own library's formats and names any other. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#inputs)
## A script or an agent drives one host
> An agent writing a chart needs to try it before any application code exists: spawn an order, answer its payment request, let its 30-second timeout fire. Waiting 30 real seconds per try, or writing a host program first, slows every iteration.
`tinyactors run` starts one host and serves JSON-RPC 2.0 on standard input and output, one message per line. The client spawns actors, sends events, answers the sends they make and moves the clock. The clock moves only when the client says so, and `Math.random` has a fixed seed, so the same requests print the same lines.
A server that spawns actors over JSON-RPC can look like a way to run them in production. It is a workbench: one host, one client on its standard input, charts in ECMAScript on quickjs, and a protocol that may change in any release. Production actors belong in your process, where the libraries give them your store, your I/O and your event loop.
| Job | Where it belongs |
|---|---|
| Check, lint and format charts in CI | `tinyactors check`, `lint`, `fmt` |
| Compare a version with the deployed one | `tinyactors diff` |
| Read a snapshot or a blob | `tinyactors actors`, `inspect` |
| Draw a chart for a review | `tinyactors graph` |
| Try a chart from a shell or an agent | `tinyactors run` |
| Serve your application's traffic | The Node.js, Python or C library |
- **The protocol is experimental**: `run` and its protocol may change in any release until a second client uses them. `tinyactors run --schema` prints the schema of the release you have. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#run)
- **A session repeats byte for byte**: With a simulated clock and a fixed seed, the same requests write the same lines, trace ids included. Source: [tinyactors-core, `docs/cli.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/cli.md#startup-and-the-end-of-input)
---
# Recipes · tinyactors
Kind: reference. 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: [Reference](https://tinyactors.dev/voices/reference.xml).
> Ten applications built with tinyactors, from a shop's orders to a game server that survives being killed, each with its problem, the features it uses and its source.
Ten applications, from a shop's orders to a game server that comes back after `SIGKILL`. Each one's test plays the cases that make it hard, under Node.js and under Bun.
[Read the source](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples) · [Browse the guides](https://tinyactors.dev/guides/index.md)
## One actor per session or connection
A session's limits, timers and members live in one actor. The code around it only finds the actor by name and sends it events.
- **[A rate-limited API gateway](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/http-gateway)**: Every client session needs a token bucket, a cap on requests in flight and timeouts against a slow, flaky upstream. On `node:http`, the session's chart picks every status, 429, 502 and 504 included, and retries only a `GET`. It shows [an async I/O processor](https://tinyactors.dev/guides/io-processors/index.md#answering-later) that answers with `fetch`, and a request's `traceparent` carried to the upstream and to [OpenTelemetry](https://tinyactors.dev/guides/telemetry/index.md#trace-context).
- **[A chat with workspaces, rooms and connections](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/chat-rooms)**: Thousands of rooms and connections keep their members and history, though most sit idle. A workspace decides which rooms exist and spawns them; only a bound of actors stays in memory, the rest one file each on disk. It shows [a store and a resident bound](https://tinyactors.dev/guides/hibernation/index.md#a-store-and-a-bound), [the Spawner](https://tinyactors.dev/guides/io-processors/index.md#spawning-from-a-chart) and [each way a send meets an actor that is not there](https://tinyactors.dev/guides/missing-actors/index.md).
## Retries, timeouts and refunds as states
Each of these runs a business process whose steps fail the way real ones do. Its test plays every failure on a [simulated clock](https://tinyactors.dev/guides/testing-recipes/index.md#stepping-the-clock), so a 48-hour SLA takes no time.
- **[An order that pays, ships and refunds](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/order-fulfillment)**: A payment times out or its answer is lost, a customer cancels during the shipment, the stock runs out after the charge. The order retries under one idempotency key and refunds what it charged, so a delivered order is charged exactly once ([its test](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-napi/examples/order-fulfillment/test.mjs) loses an answer and checks that the retry charges nothing more). It shows [invoked services](https://tinyactors.dev/guides/services/index.md) for the payment and the shipment, timeouts as delayed sends and [a failed send](https://tinyactors.dev/guides/io-processors/index.md#answer-or-fail) that becomes a retry.
- **[Subscriptions billed during a release](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/subscription-billing)**: A subscription lives for years, and its chart changes under it. Release 2 renames a variable and adds states; a canary, then each chart, moves to it while renewals and payments are in flight. It shows [migration](https://tinyactors.dev/guides/migration/index.md) of a mostly [hibernated](https://tinyactors.dev/guides/hibernation/index.md) population, and [the typed methods](https://tinyactors.dev/guides/inspection/index.md) an operator uses to find who is left on the old release.
- **[A document reviewed by legal and finance](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/document-approval)**: Two reviews run at once, finance waits for legal on large amounts, and a stage past its SLA escalates the document to a manager. Parallel regions, `In()` guards and history states hold those rules. It shows an admin view over HTTP that reads every document's states, variables and due SLAs with [the typed methods](https://tinyactors.dev/guides/inspection/index.md#delayed-sends-and-history).
- **[Background jobs with retries and deadlines](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/job-scheduler)**: Workers throw, hang or run past a deadline, and a slow recurring run must not push the schedule back. A job's delayed sends are its whole schedule, and the process exits by itself when the last job ends. It shows [an I/O processor](https://tinyactors.dev/guides/io-processors/index.md) that aborts a hung worker, a graceful shutdown on `SIGTERM` and the drift of fixed-delay jobs, measured.
## Two systems, each a host, over a socket
The host decides which sends leave its system. The wire, the connection and what to do when it is gone are your code's, written in [a transport](https://tinyactors.dev/guides/other-systems/index.md).
- **[Stock held across a warehouse and a storefront](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/inventory-sync)**: Two carts race for the last unit, a hold expires, the warehouse goes down in the middle of a checkout. Each SKU is an actor that takes one request at a time and answers a repeated one as it answered the first ([its test](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-napi/examples/inventory-sync/test.mjs) duplicates every message both ways); a cart compensates by releasing every line. It shows [a transport over TCP](https://tinyactors.dev/guides/other-systems/index.md#over-a-socket), [a failed delivery](https://tinyactors.dev/guides/other-systems/index.md#failed-delivery) and [a snapshot](https://tinyactors.dev/guides/snapshots/index.md) the warehouse comes back from.
- **[A Python system and a Node.js system](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/remote-python)**: Actors in two processes and two languages address each other by `tinyactors://` address. A Node.js chart and a Python chart trade pings over one TCP connection, and a send to an actor the other side lacks fails back to its sender. Values cross unchanged, integers up to 2^64 included.
## Customers' code in a sandbox per rule
- **[Alert rules your customers upload](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/iot-rules)**: An uploaded rule may loop for ever, hoard memory, look for `require` or send to another customer's device. Each rule runs on a host of its own on [the quickjs datamodel](https://tinyactors.dev/guides/quickjs/index.md), with limits on operations and memory, so a runaway evaluation becomes `error.execution` and the rule is suspended after three. Its README measures how long a loop holds the host and what a rule costs per device.
## Turn timers that survive a crash
- **[A game server that survives being killed](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/turn-game)**: A match's turn timers must come back from a crash with the time they had left. The server takes [a snapshot](https://tinyactors.dev/guides/snapshots/index.md) of the whole host every second, [journals](https://tinyactors.dev/guides/journal/index.md) each client input, and after `SIGKILL` restores and replays the journal, or drops it. Its matchmaking service [starts again](https://tinyactors.dev/guides/snapshots/index.md#restarting-services) from the lobby's waiting list.
## Run a recipe on its own
A recipe runs against the published package, outside the repository. Install `@tinyactors/node` in a new project and copy the recipe into its `examples/` directory:
```shell
git clone --depth 1 https://github.com/tinyactors-dev/tinyactors
mkdir -p recipes/examples && cd recipes
npm install @tinyactors/node@0.4.0
cp -r ../tinyactors/tinyactors-napi/examples/order-fulfillment examples/
node examples/order-fulfillment/main.mjs
node examples/order-fulfillment/test.mjs
```
`main.mjs` runs the application and prints what its README describes; `test.mjs` plays its hard cases. Three recipes differ:
- **inventory-sync**: reuses the framing of remote-python, so copy `remote-python` beside it.
- **subscription-billing**: runs on 0.4.0, but two of its tests, a payment in flight during a migration, need a core change made after that release.
- **remote-python**: builds the Python binding from the repository, so it runs only there: `mise run remote-python` in `tinyactors-napi`.
---
# When to use tinyactors
Kind: explanation. For: [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [Explanation](https://tinyactors.dev/voices/explanation.xml).
> Why tinyactors fits an embedded event loop, what a crash keeps and how it compares with Temporal, Durable Objects, Rivet and XState.
tinyactors embeds SCXML actors on your event loop across [Node.js, Python, browsers and C](https://tinyactors.dev/architecture/index.md#what). Your code owns the [process, store, effects and cross-host placement](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) while the core [passes 191 W3C tests](https://tinyactors.dev/performance/index.md#correctness).
[Check capacity numbers](https://tinyactors.dev/performance/index.md) · [Write a first chart](https://tinyactors.dev/guides/charts/index.md#first-chart) · [Build a team chat](https://tinyactors.dev/chat/index.md)
## tinyactors fits millions of in-process statechart actors
tinyactors fits when you need memory density, SCXML charts, event-based effects, simulated-clock tests and one core across runtimes.
- **Small actors and hibernation**: Actors take [about 530 bytes started and 120 hibernated](https://tinyactors.dev/guides/capacity/index.md); operations [cost about the same](https://tinyactors.dev/performance/index.md) at four million as at two. Idle actors hibernate and wake on events; [two million actors ran](https://tinyactors.dev/guides/hibernation/index.md#at-scale) with at most 1000 in memory.
- **Explicit SCXML statecharts**: Each actor runs an [SCXML chart](https://tinyactors.dev/guides/charts/index.md) of states, events and transitions with JavaScript or Python expressions. SCXML `invoke` runs [long operations per state](https://tinyactors.dev/guides/services/index.md), and [QuickJS sandboxes user-uploaded charts](https://tinyactors.dev/guides/quickjs/index.md).
- **Effects as events without mocks**: A chart reaches the world only through sends to an [I/O processor](https://tinyactors.dev/guides/io-processors/index.md), a handler you give the host. Because effects are events, tests avoid mocking external services: [test handlers](https://tinyactors.dev/guides/testing-recipes/index.md#three-tools) record sends and answer, return errors or never reply.
- **Timeouts tested with a simulated clock**: A `SimulatedClock` [moves only when the test moves it](https://tinyactors.dev/guides/testing/index.md): a timeout of an hour takes no time. A payment that retries every 30 seconds runs all three attempts in milliseconds, alongside [property tests](https://tinyactors.dev/property-testing/index.md).
- **One C core across runtimes**: One C core [runs the same tests](https://tinyactors.dev/performance/index.md#correctness) and the same chart in Node.js, Python, C and [browsers](https://tinyactors.dev/guides/browser/index.md).
## Limits: SCXML charts, single hosts and changing APIs
tinyactors stops at SCXML charts inside single hosts under active development with frequent breaking changes.
- **Arbitrary actor code**: Each actor runs an [SCXML chart](https://tinyactors.dev/guides/charts/index.md) with JavaScript or Python expressions. Erlang and Akka actors run any code you give them.
- **Managed clustering and failover**: Actors stay in their spawning host, so your program runs a [named host per process](https://tinyactors.dev/guides/other-systems/index.md#systems). [Placement, deployment, failover and transport](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) between hosts are your program's work.
- **A stable API**: The README says tinyactors is under active development and makes [frequent breaking changes](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#status). Follow each package release and upgrade change in [the tinyactors changelog](https://tinyactors.dev/changelog/index.md).
## A crash stops memory and keeps saved state
Actors live in process memory, so a crash stops every actor and keeps only what your program saved.
- **Host snapshots with `Host.restore`**: `Host.restore` runs a snapshot in this process or another with [variables, queued events and pending timers](https://tinyactors.dev/guides/snapshots/index.md#what-it-holds). [One snapshot](https://tinyactors.dev/guides/snapshots/index.md) holds two million actors in 165 MB.
- **Host-bound hibernation blobs**: Each hibernated blob carries [its host's random identity](https://tinyactors.dev/guides/hibernation/index.md#what-a-blob-holds), so a fresh host refuses blobs from another host. A host restored from the original host's snapshot accepts those blobs.
- **Input journal replay**: A restored host starts at snapshot time and accepts blobs hibernated since. Your program [replays all other inputs](https://tinyactors.dev/guides/journal/index.md) after the snapshot from its own journal.
- **Application store ownership**: tinyactors saves blobs through your store and takes snapshots when asked, [restoring with matching options](https://tinyactors.dev/guides/snapshots/index.md#restoring). All storage I/O stays in [your application layer](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities).
- **Chart updates and missing actors**: [Live migration](https://tinyactors.dev/guides/migration/index.md) updates actors at rest to a new chart while keeping sessions, states and queues. A send to a hibernated actor wakes it, while a [send to an absent actor](https://tinyactors.dev/guides/missing-actors/index.md) fails immediately.
## Portable charts and MIT license, build-bound snapshots
Charts, event boundaries and the MIT license move across runtimes, whereas snapshots require matching memory layout.
- **W3C SCXML charts meet code at events**: Each chart is a W3C SCXML document rather than a proprietary format. Your code meets tinyactors only at event boundaries: inputs go in, and effects come out to your handlers. Source: [W3C, "State Chart XML (SCXML)"](https://www.w3.org/TR/scxml/)
- **Core passes all 191 W3C SCXML tests**: The C core passes all 191 automatic tests of the W3C SCXML conformance suite. Every binding runs the same suite across Node.js, Python, C and [browsers](https://tinyactors.dev/guides/browser/index.md). 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/)
- **MIT license covers every tinyactors package**: Every package is MIT licensed, allowing you to use, change and ship tinyactors while keeping its copyright and permission notice. Source: [tinyactors, `LICENSE`](https://github.com/tinyactors-dev/tinyactors/blob/main/LICENSE)
- **Snapshots require matching memory layout**: Snapshots and blobs use tinyactors' own format, and a snapshot restores only on a build with the same memory layout. Keep data that must last in your own database. Source: [Snapshots, "Restore with the options the snapshot had"](https://tinyactors.dev/guides/snapshots/index.md#restoring)
## tinyactors runs SCXML directly inside your own hosts
Temporal, Durable Objects and Rivet manage persistence or placement, whereas XState is inspired by SCXML.
- **Temporal runs a server; tinyactors runs in-process**: Self-hosted Temporal runs Temporal Server and persistence stores on Docker, Kubernetes or by hand. Your program creates a tinyactors host object directly for tests and runtime, handling journaling and [cross-host transport](https://tinyactors.dev/guides/other-systems/index.md). [tinyactors compared with Temporal](https://tinyactors.dev/compare/temporal/index.md) sets the two side by side: tests, crashes and running changes. Source: [Temporal, "Temporal Service"](https://docs.temporal.io/temporal-service) · [Temporal, "Self-hosted Temporal Service guide"](https://docs.temporal.io/self-hosted-guide)
- **Durable Objects place Workers; tinyactors uses your process**: Cloudflare describes a Durable Object as a Worker that combines compute with storage, placed near its first request. A tinyactors actor runs inside any server or browser tab your program operates, with storage under your control. [tinyactors compared with Durable Objects](https://tinyactors.dev/compare/durable-objects/index.md) sets the two side by side: idle sessions, tests and deploys. Source: [Cloudflare, "Durable Objects"](https://developers.cloudflare.com/durable-objects/)
- **Rivet places durable processes; tinyactors pins to hosts**: Rivet describes its actors as durable processes in your backend, placed by Rivet Cloud or your control plane. A tinyactors actor stays in the host that spawned it, and your program routes across hosts. [tinyactors compared with Rivet](https://tinyactors.dev/compare/rivet/index.md) sets the two side by side: placement, sleeping actors and deploys. Source: [Rivet, "Actors"](https://rivet.dev/docs/actors)
- **XState takes SCXML inspiration; tinyactors runs SCXML**: XState's README says it is inspired by the SCXML specification. tinyactors runs SCXML documents themselves, the same chart in every language, and the C core passes 191 W3C tests. [tinyactors compared with XState](https://tinyactors.dev/compare/xstate/index.md) sets the two side by side: the format, populations and running changes. Source: [XState, `README.md`](https://github.com/statelyai/xstate) · [Memory, capacity and performance, "Correct by the standard"](https://tinyactors.dev/performance/index.md#correctness)
[Write a first chart](https://tinyactors.dev/guides/charts/index.md#first-chart) · [Test your charts](https://tinyactors.dev/guides/testing/index.md) · [Check capacity numbers](https://tinyactors.dev/performance/index.md)
---
# tinyactors compared with Temporal
Kind: pitch. For: [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 workflow with retries and timeouts runs, how its tests move time, what a crash keeps, and when Temporal is the better choice.
A payment that retries every 30 seconds runs as a statechart inside your own process. One program checks it over a thousand simulated runs, with no server and no database. Choose Temporal when its service must keep every workflow through a machine's failure.
[Test a payment's timeouts](https://tinyactors.dev/guides/testing-recipes/index.md#a-test) · [See when Temporal fits](https://tinyactors.dev/compare/temporal/index.md#choose-temporal)
## Temporal is a service; tinyactors is a library
A payment that retries three times is a few states of logic. With Temporal, it spans a server, a database and the workers you run. tinyactors keeps it in your process.
- **Temporal runs a server and its database**: Its docs define the service as the Temporal Server combined with persistence and visibility stores. In production the store is Cassandra, PostgreSQL or MySQL. SQLite is for development and testing only. Source: [Temporal, "Temporal Service"](https://docs.temporal.io/temporal-service) · [Temporal, "Persistence"](https://docs.temporal.io/temporal-service/persistence)
- **Your workers poll the service for tasks**: Worker processes are external to the service, and you operate them. Each one polls a task queue, runs your code and reports the result back. Source: [Temporal, "Workers"](https://docs.temporal.io/workers)
- **A tinyactors host lives in your program**: `new Host(charts, options)` runs the actors inside the program that imports `@tinyactors/node` or `tinyactors`. A chart reaches the world only through handlers you give the host. Source: [Architecture, "Actors run SCXML charts inside your process"](https://tinyactors.dev/architecture/index.md#what) · [I/O processors, "Ask for outside work with a send"](https://tinyactors.dev/guides/io-processors/index.md#charts-send-events)
Temporal Cloud takes the service off your hands: Temporal operates its persistence, replication, upgrades and availability. Your workers still run in your environment ([Temporal, "Temporal Cloud"](https://docs.temporal.io/evaluate/cloud)).
Durable Objects and Rivet run actors as a platform too: see [tinyactors compared with Durable Objects](https://tinyactors.dev/compare/durable-objects/index.md) and [tinyactors compared with Rivet](https://tinyactors.dev/compare/rivet/index.md).
## Test a thousand payments in one program
A workflow's bugs hide in its timeouts. This chart charges a card, charges again after 30 seconds without an answer and gives up after three charges. Every attempt carries the same key, the payment's session:
```scxml title="payment.scxml"
```
The test gives the host a stand-in payment provider. It answers a charge at once, 45 seconds late, after the next charge has gone out, or never.
A simulated clock jumps to each timeout and each late answer, so a thousand payments run in one program. Then it checks three rules:
```javascript title="simulate.mjs"
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') }]);
let paidLate = 0;
let answeredAfterGivingUp = 0;
for (let seed = 1; seed <= 1000; seed++) {
const random = mulberry32(seed);
const clock = new SimulatedClock();
const requests = [];
const late = []; // answers the provider sends 45 seconds after the charge
let outcome;
const host = new Host(compiled, {
system: 'simulation',
clock,
ioProcessors: {
'urn:payments': {
receive(send) {
requests.push(send.data.key);
const roll = random();
if (roll < 0.3) send.answer('charged'); // at once
else if (roll < 0.6) late.push({ at: clock.now + 45_000, actor: send.sender }); // after the next charge
}, // otherwise it never answers
},
},
onDone: (actor, donedata) => { outcome = donedata.outcome; },
});
host.spawn('payment');
await host.idle();
while (outcome === undefined || late.length > 0) {
const nextLate = late.length > 0 ? Math.min(...late.map((answer) => answer.at)) - clock.now : Infinity;
clock.increment(Math.min(host.nextDeadline ?? Infinity, nextLate)); // jump to what comes next: no waiting
for (const answer of late.filter((answer) => answer.at <= clock.now)) {
late.splice(late.indexOf(answer), 1);
if (outcome === undefined) { answer.actor.send('charged'); paidLate++; }
else if (outcome === 'failed') answeredAfterGivingUp++;
}
await host.idle();
}
assert.ok(requests.length <= 3, `seed ${seed}: charged ${requests.length} times`);
assert.equal(new Set(requests).size, 1, `seed ${seed}: the attempts carry different keys`);
assert.ok(outcome === 'paid' || requests.length === 3, `seed ${seed}: gave up early`);
host.close();
}
console.log('1000 seeds: never more than three charges, one key for all of them, never giving up early');
console.log(`${paidLate} paid by an answer that came after the next charge`);
console.log(`${answeredAfterGivingUp} answered after the chart gave up: reconcile those with the provider`);
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;
};
}
```
```text title="output"
1000 seeds: never more than three charges, one key for all of them, never giving up early
312 paid by an answer that came after the next charge
51 answered after the chart gave up: reconcile those with the provider
```
One key for every attempt lets the provider charge the card once, however many requests reach it. The 51 answers that came after the chart gave up are payments your program must reconcile with the provider.
- **Temporal's tests skip time with a server**: Temporal's test framework is an in-memory Temporal Server whose timers fast-forward, except while activities run. The `@temporalio/testing` package downloads that server. Source: [Temporal, "Testing suite" (TypeScript)](https://docs.temporal.io/develop/typescript/testing-suite)
Here the host and its clock are the whole test. No server starts.
The stand-in service is an object, so it answers, fails or stays silent as each case needs ([Testing recipes](https://tinyactors.dev/guides/testing-recipes/index.md#three-tools)).
## Temporal keeps history; your program keeps snapshots
A process dies halfway through a payment. What survives depends on who wrote it down.
- **Temporal replays every workflow from its history**: The service records each workflow's event history, a complete ordered log that is its source of truth. To continue a workflow, it reruns the code from the beginning against that history. Its docs say workflows keep running for years, even if the underlying infrastructure fails. Source: [Temporal, "Temporal Workflow"](https://docs.temporal.io/workflows)
- **A crash keeps what your program saved**: tinyactors actors live in your process's memory, so a crash stops them all. What comes back is what your program saved: hibernated actors in its store, and its last snapshot. 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)
The journal is one write per input, to a store your program already runs. If you'd rather not own that write and its storage, choose Temporal.
A snapshot holds only its moment. A snapshot of two million actors takes 165 MB ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).
## Change a workflow that is already running
An order waits a week for delivery. On Tuesday the rules change. The running order must take the new rules without losing its place.
- **Temporal's replay needs deterministic code and patches**: Replay reruns workflow code, so given the same input it must make the same API calls in the same order. Adding, removing or reordering one causes a nondeterminism error. `patched()` marks a change in the event history, a branch like a feature flag, so running workflows keep their old path. Source: [Temporal, "Workflow Definition"](https://docs.temporal.io/workflow-definition) · [Temporal, "Versioning" (TypeScript)](https://docs.temporal.io/develop/typescript/versioning)
- **A migration moves running actors to a version**: A new chart version is added to the running host, and `host.migrate()` moves running actors to it. Each keeps its active states, queue and delayed sends. The new chart reads the old variables from one event and decides what carries over. Source: [Migration, "Move the actors and carry their variables"](https://tinyactors.dev/guides/migration/index.md#moving-running-actors)
## Choose tinyactors for logic inside your program
- **Workflows in a program you already run**: The host is a library, so no server, database or worker fleet runs beside your program.
- **Tests that reach every timeout**: A simulated clock jumps to each deadline, so one program checks a payment's rules over a thousand runs.
- **Many workflows, most of them waiting**: Waiting actors hibernate into your store: [two million ran with at most 1000 in memory](https://tinyactors.dev/guides/hibernation/index.md#at-scale), the rest in SQLite.
- **The whole flow written down**: Every state and transition is in one [SCXML chart](https://tinyactors.dev/guides/charts/index.md), which a test, a reviewer or the [command line](https://tinyactors.dev/cli/index.md) can read.
## Choose Temporal when its service must own durability
- **Durability you don't build**: The service keeps each workflow's event history in its database. Replay restores the state after infrastructure fails.
- **Work spread across many machines**: Workers on any machine poll task queues. tinyactors leaves [placement and failover between hosts](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) to your program.
- **Retries without writing them**: Temporal [retries a failed activity by default](https://docs.temporal.io/encyclopedia/retry-policies), starting after one second and doubling. In a chart, the retry is two transitions you can read and test, as the payment above shows.
- **Workflows as ordinary code**: A workflow is code in your language, with no chart format to learn ([Temporal, "Workflow Definition"](https://docs.temporal.io/workflow-definition)).
[Test a payment's timeouts](https://tinyactors.dev/guides/testing-recipes/index.md#a-test) · [See when to use tinyactors](https://tinyactors.dev/when-to-use/index.md) · [Read what a snapshot keeps](https://tinyactors.dev/guides/snapshots/index.md)
---
# tinyactors compared with Durable Objects
Kind: pitch. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).
> Where a stateful session runs, what an idle one keeps, how its tests move time, what a deploy does to it, and when Cloudflare Durable Objects are the better choice.
A Durable Object gives each agent session its own state and one order of events, on Cloudflare's network. tinyactors runs that session as a statechart inside your own process. Choose Durable Objects when sessions must be reachable from anywhere in the world.
[Upgrade running sessions](https://tinyactors.dev/compare/durable-objects/index.md#deploy) · [See Durable Objects' strengths](https://tinyactors.dev/compare/durable-objects/index.md#choose-durable-objects)
## Cloudflare runs the object; you run the host
Your backend already runs somewhere you chose. In a Durable Object, a session's logic runs on Cloudflare's network, apart from the rest of your backend.
- **A Durable Object is a Worker with storage**: Cloudflare defines it as a special kind of Worker that combines compute with storage. It is placed close to where it is first requested. Each object has a globally unique name, so a request reaches that one object from anywhere in the world. Source: [Cloudflare, "Durable Objects"](https://developers.cloudflare.com/durable-objects/) · [Cloudflare, "What are Durable Objects?"](https://developers.cloudflare.com/durable-objects/concepts/what-are-durable-objects/)
- **A tinyactors host lives in your program**: `new Host(charts, options)` runs the actors inside the Node.js, Bun, Python or browser process that imports the package. A chart reaches the model's API, your database or a socket only through handlers you give the host. Source: [Architecture, "Actors run SCXML charts inside your process"](https://tinyactors.dev/architecture/index.md#what) · [I/O processors, "Ask for outside work with a send"](https://tinyactors.dev/guides/io-processors/index.md#charts-send-events)
The cost is on your side. Your program decides where each host runs and carries a message to another host's actor ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)). On Cloudflare, that's the platform's work.
## Idle sessions wait in your database
Most sessions sit idle between a user's messages. Their state must survive until the next one, without holding memory meanwhile.
- **An idle object discards its memory**: After 10 seconds without work an object can hibernate, and its in-memory state is discarded. Cloudflare says to persist anything important to the object's storage. That storage is SQLite, up to 10 GB per object on the paid plan. Source: [Cloudflare, "Durable Object lifecycle"](https://developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/) · [Cloudflare, "In-memory state in a Durable Object"](https://developers.cloudflare.com/durable-objects/reference/in-memory-state/) · [Cloudflare, "Limits"](https://developers.cloudflare.com/durable-objects/platform/limits/)
- **An idle actor goes to your store whole**: Give the host a store and a bound, and it writes the actors past the bound into the store: variables, active states and all. The next event wakes one. Two million actors ran with at most 1000 in memory and the rest in SQLite. Source: [Hibernation, "Cap how many actors stay in memory"](https://tinyactors.dev/guides/hibernation/index.md#a-store-and-a-bound) · [Hibernation, "Run two million actors with 1000 in memory"](https://tinyactors.dev/guides/hibernation/index.md#at-scale)
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)).
## Test a thousand timeouts in one program
A session's bugs hide in what happens when an answer is late. This payment charges a card, charges again after 30 seconds without an answer and gives up after three charges:
```scxml title="payment.scxml"
```
The test's stand-in provider answers at once, 45 seconds late or never. A simulated clock jumps to each timeout, so a thousand payments run in one Node.js process:
```javascript title="simulate.mjs"
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') }]);
let paidLate = 0;
let answeredAfterGivingUp = 0;
for (let seed = 1; seed <= 1000; seed++) {
const random = mulberry32(seed);
const clock = new SimulatedClock();
const requests = [];
const late = []; // answers the provider sends 45 seconds after the charge
let outcome;
const host = new Host(compiled, {
system: 'simulation',
clock,
ioProcessors: {
'urn:payments': {
receive(send) {
requests.push(send.data.key);
const roll = random();
if (roll < 0.3) send.answer('charged'); // at once
else if (roll < 0.6) late.push({ at: clock.now + 45_000, actor: send.sender }); // after the next charge
}, // otherwise it never answers
},
},
onDone: (actor, donedata) => { outcome = donedata.outcome; },
});
host.spawn('payment');
await host.idle();
while (outcome === undefined || late.length > 0) {
const nextLate = late.length > 0 ? Math.min(...late.map((answer) => answer.at)) - clock.now : Infinity;
clock.increment(Math.min(host.nextDeadline ?? Infinity, nextLate)); // jump to what comes next: no waiting
for (const answer of late.filter((answer) => answer.at <= clock.now)) {
late.splice(late.indexOf(answer), 1);
if (outcome === undefined) { answer.actor.send('charged'); paidLate++; }
else if (outcome === 'failed') answeredAfterGivingUp++;
}
await host.idle();
}
assert.ok(requests.length <= 3, `seed ${seed}: charged ${requests.length} times`);
assert.equal(new Set(requests).size, 1, `seed ${seed}: the attempts carry different keys`);
assert.ok(outcome === 'paid' || requests.length === 3, `seed ${seed}: gave up early`);
host.close();
}
console.log('1000 seeds: never more than three charges, one key for all of them, never giving up early');
console.log(`${paidLate} paid by an answer that came after the next charge`);
console.log(`${answeredAfterGivingUp} answered after the chart gave up: reconcile those with the provider`);
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;
};
}
```
```text title="output"
1000 seeds: never more than three charges, one key for all of them, never giving up early
312 paid by an answer that came after the next charge
51 answered after the chart gave up: reconcile those with the provider
```
- **Durable Objects' tests run in the Workers runtime**: Cloudflare's Vitest integration runs tests inside the Workers runtime, with the objects' bindings and storage. `runDurableObjectAlarm()` fires a scheduled alarm at once instead of waiting for its timer. Source: [Cloudflare, "Testing Durable Objects"](https://developers.cloudflare.com/durable-objects/examples/testing-with-durable-objects/)
- **A simulated clock moves when tests move it**: The test above is a host, a clock and a stand-in object. Every timer of every actor waits for `clock.increment()`. Source: [Testing, "Replace the chart's services and its clock"](https://tinyactors.dev/guides/testing-recipes/index.md#three-tools)
## Ship new rules to running sessions
You deploy a turn limit while thousands of sessions are mid-conversation. Each one must keep the turns it already counted.
- **A deploy resets an active object**: By default an active object keeps its old code until it hibernates, or for up to 300 seconds. Then it resets and adopts the new code. Hibernation discards in-memory state, so what carries over is what the object stored. Source: [Cloudflare, "Durable Objects code updates"](https://developers.cloudflare.com/durable-objects/deployments/durable-objects-code-updates/) · [Cloudflare, "Durable Object lifecycle"](https://developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/)
- **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 title="session-v2.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
```
Every session kept its count through the move. So each one ended at the limit instead of asking the model again.
A Durable Object that stores its count keeps it across a deploy too, and its new code reads it back. The difference is the rest: a migration also carries each session's states, queue and timers, with no code that reads them back.
## A crash keeps what was written down
A machine dies halfway through a session. Both answers start from storage; they differ in who owns it.
- **An object's writes are stored all or none**: If a machine fails, either all of a write's changes reached disk or none did. Point-in-time recovery restores an object's database to any moment of the past 30 days. Source: [Cloudflare, "SQLite-backed Durable Object Storage"](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/)
- **A crash keeps what your program saved**: Actors live in your process's memory, so a crash stops them all. Hibernated actors in your store and the last snapshot come back. Inputs after that snapshot return when your program journaled them. 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)
Here Durable Objects keep more by default: every write an object stores survives. With tinyactors, what your program did not save or journal is lost with the process.
## Choose tinyactors for sessions inside your backend
- **A backend on the cloud you chose**: The host is a library in your Node.js, Bun or Python process, so the sessions deploy with the code that calls them.
- **Deploys that keep each session's place**: A [migration](https://tinyactors.dev/guides/migration/index.md) moves running sessions to new rules with their states, queues and timers.
- **Tests that reach every timeout**: A simulated clock jumps to each deadline, so one program checks a thousand sessions.
- **Logic an agent can write and you can read**: Each session is one [SCXML chart](https://tinyactors.dev/guides/charts/index.md), and an uploaded chart runs in [the QuickJS sandbox](https://tinyactors.dev/guides/quickjs/index.md).
## Choose Durable Objects for sessions reached from anywhere
- **Clients all over the world**: Each object has a globally unique name and is placed near its first request. tinyactors leaves [placement and failover between hosts](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) to your program.
- **Storage you don't operate**: Each object has its own SQLite database, [restorable to any point of the past 30 days](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/).
- **Connections that outlive memory**: [WebSocket Hibernation](https://developers.cloudflare.com/durable-objects/best-practices/websockets/) keeps clients connected while the object is out of memory, and duration charges stop meanwhile.
- **An application already on Workers**: A Durable Object is a Worker, so it shares the platform, bindings and deploys of the rest of the application. One object can also hold a tinyactors host, which keeps Cloudflare and adds statecharts ([Run actors in a Cloudflare Worker](https://tinyactors.dev/guides/workers/index.md)).
[Hibernate idle sessions](https://tinyactors.dev/guides/hibernation/index.md) · [Upgrade running actors](https://tinyactors.dev/guides/migration/index.md) · [See when to use tinyactors](https://tinyactors.dev/when-to-use/index.md)
---
# tinyactors compared with Rivet
Kind: pitch. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).
> Who places an actor, what a sleeping one keeps, how its tests move time, what a deploy does to running actors, and when Rivet Actors are the better choice.
Rivet runs actors in your Node.js or Bun backend, for agents, realtime apps and per-tenant databases, placed by Rivet Cloud or a control plane you deploy. tinyactors runs each session as a statechart in your process, with nothing beside it. Choose Rivet when actors must move between machines on their own.
[Upgrade running sessions](https://tinyactors.dev/compare/rivet/index.md#deploy) · [See when Rivet fits](https://tinyactors.dev/compare/rivet/index.md#choose-rivet)
## Rivet places actors; your program places hosts
Both run your actors in your backend's process. The difference is what runs beside it. And who decides where an actor lives.
- **Rivet's control plane places each actor**: Rivet calls its actors isolated, durable processes that run in your backend. You deploy the control plane yourself, or use Rivet Cloud. The platform may move an actor to another node, for example when its node stops during a deploy. In development, Rivet runs a local control plane for you and keeps actor data on your machine. Source: [Rivet, "Actors"](https://rivet.dev/docs/actors) · [Rivet, "Lifecycle"](https://rivet.dev/actors/docs/lifecycle/) · [Rivet, "Node.js and Bun quickstart"](https://rivet.dev/actors/docs/quickstart/backend/)
- **A tinyactors actor stays in its host**: `new Host(charts, options)` runs the actors inside the process that imports the package. An actor stays in the host that spawned it. A chart reaches the model's API or your database only through handlers you give the host. Source: [Architecture, "Actors run SCXML charts inside your process"](https://tinyactors.dev/architecture/index.md#what) · [Other systems, "Give each host a system name"](https://tinyactors.dev/guides/other-systems/index.md#systems)
There's nothing to operate. There's also nothing that moves an actor for you: which host runs where, and how a message reaches another host, is your program's code.
## A sleeping actor keeps what was stored
Most sessions sit idle between a user's messages. Their state must survive until the next one, without holding memory meanwhile.
- **A Rivet actor keeps its SQLite database**: After 30 seconds without activity an actor sleeps, and the next request wakes it. Its `c.vars` are never saved. What must survive goes in `c.db`, a SQLite database per actor whose every committed write is replicated before it's acknowledged. `c.state`, which Rivet saved on a throttle, is deprecated since Rivet 3.0. Source: [Rivet, "Lifecycle"](https://rivet.dev/actors/docs/lifecycle/) · [Rivet, "State"](https://rivet.dev/actors/docs/state/) · [Rivet, "State (deprecated)"](https://rivet.dev/actors/docs/deprecated/state/)
- **A hibernated actor goes to your store whole**: Give the host a store and a bound, and it writes the actors past the bound into the store: variables, active states and all. The next event wakes one. A blob wakes only in the host that made it, or in one restored from that host's snapshot. Source: [Hibernation, "Cap how many actors stay in memory"](https://tinyactors.dev/guides/hibernation/index.md#a-store-and-a-bound) · [Hibernation, "Wake each blob where it was made"](https://tinyactors.dev/guides/hibernation/index.md#what-a-blob-holds)
Two million actors ran with at most 1000 in memory and the rest in SQLite ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md#at-scale)). An actor's data your business must keep belongs in your own database, as with any process.
## Test a thousand timeouts in one program
A session's bugs hide in what happens when an answer is late. This payment charges a card, charges again after 30 seconds without an answer and gives up after three charges:
```scxml title="payment.scxml"
```
The test's stand-in provider answers at once, 45 seconds late or never. A simulated clock jumps to each timeout, so a thousand payments run in one Node.js process:
```javascript title="simulate.mjs"
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') }]);
let paidLate = 0;
let answeredAfterGivingUp = 0;
for (let seed = 1; seed <= 1000; seed++) {
const random = mulberry32(seed);
const clock = new SimulatedClock();
const requests = [];
const late = []; // answers the provider sends 45 seconds after the charge
let outcome;
const host = new Host(compiled, {
system: 'simulation',
clock,
ioProcessors: {
'urn:payments': {
receive(send) {
requests.push(send.data.key);
const roll = random();
if (roll < 0.3) send.answer('charged'); // at once
else if (roll < 0.6) late.push({ at: clock.now + 45_000, actor: send.sender }); // after the next charge
}, // otherwise it never answers
},
},
onDone: (actor, donedata) => { outcome = donedata.outcome; },
});
host.spawn('payment');
await host.idle();
while (outcome === undefined || late.length > 0) {
const nextLate = late.length > 0 ? Math.min(...late.map((answer) => answer.at)) - clock.now : Infinity;
clock.increment(Math.min(host.nextDeadline ?? Infinity, nextLate)); // jump to what comes next: no waiting
for (const answer of late.filter((answer) => answer.at <= clock.now)) {
late.splice(late.indexOf(answer), 1);
if (outcome === undefined) { answer.actor.send('charged'); paidLate++; }
else if (outcome === 'failed') answeredAfterGivingUp++;
}
await host.idle();
}
assert.ok(requests.length <= 3, `seed ${seed}: charged ${requests.length} times`);
assert.equal(new Set(requests).size, 1, `seed ${seed}: the attempts carry different keys`);
assert.ok(outcome === 'paid' || requests.length === 3, `seed ${seed}: gave up early`);
host.close();
}
console.log('1000 seeds: never more than three charges, one key for all of them, never giving up early');
console.log(`${paidLate} paid by an answer that came after the next charge`);
console.log(`${answeredAfterGivingUp} answered after the chart gave up: reconcile those with the provider`);
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;
};
}
```
```text title="output"
1000 seeds: never more than three charges, one key for all of them, never giving up early
312 paid by an answer that came after the next charge
51 answered after the chart gave up: reconcile those with the provider
```
- **Rivet's tests wait for real schedules**: `setupTest` starts your registry in test mode. Rivet's docs say Vitest's fake timers don't advance RivetKit's scheduler. They recommend a short schedule and polling the result with `expect.poll`. Source: [Rivet, "Testing"](https://rivet.dev/actors/docs/testing/)
- **A simulated clock moves when tests move it**: The test above is a host, a clock and a stand-in object. Every timer of every actor waits for `clock.increment()`. Source: [Testing, "Replace the chart's services and its clock"](https://tinyactors.dev/guides/testing-recipes/index.md#three-tools)
## Ship new rules to running sessions
You deploy a turn limit while thousands of sessions are mid-conversation. Each one must keep the turns it already counted.
- **A Rivet deploy stops actors on old nodes**: Each deploy sets a version that only increases. Once a newer node connects, the old deploy gets no new actors. With draining on, old actors stop as in a node shutdown, each with up to 15 seconds to save its state. Each deploy must read the state the last one wrote. Source: [Rivet, "Versions and Upgrades"](https://rivet.dev/actors/docs/versions/)
- **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 title="session-v2.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)).
No process restarted. Every session kept its count, so each one ended at the limit instead of asking the model again.
## A crash keeps what was written down
A machine dies halfway through a session. What comes back is what reached storage, and Rivet operates more of that storage for you.
- **Rivet keeps the database, not the memory**: The database survives the actor moving to another node. The sleep hook may not run in a crash, and a snapshot to SQLite on an interval loses what came after it. A `run` workflow resumes from its last completed step after a crash. Source: [Rivet, "State"](https://rivet.dev/actors/docs/state/) · [Rivet, "Lifecycle"](https://rivet.dev/actors/docs/lifecycle/)
- **A crash keeps what your program saved**: Actors live in your process's memory, so a crash stops them all. Hibernated actors in your store and the last snapshot come back. Inputs after that snapshot return when your program journaled them. 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)
## Run more processes by naming each host
One host runs in one process. To spread actors over several, you write the part Rivet's control plane does:
- **A system name per host**: The `system` option names each process's host, and every address starts with it, as in `tinyactors://eu-1/@order-7` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md#systems)).
- **Routing by name**: Your code decides which process spawns each name, and sends to an actor by its address ([Other systems](https://tinyactors.dev/guides/other-systems/index.md#address-targets)).
- **A transport**: The host hands each send for another system to your `transport` handler, which writes it on a connection; the other side passes it to `host.send` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md#over-a-socket)).
That code is yours to write and run: the connections, their reconnects and which process owns which names. When a process dies, its actors come back only where your program restores them.
## Choose tinyactors for one process you understand
- **Nothing to operate beside your backend**: The host is a library in your Node.js, Bun or Python process, so tests and production create it the same way.
- **Deploys that keep each session's place**: A [migration](https://tinyactors.dev/guides/migration/index.md) moves running sessions to new rules with their states, queues and timers.
- **Tests that reach every timeout**: A simulated clock jumps to each deadline, so one program checks a thousand sessions.
- **Logic an agent can write and you can read**: Each session is one [SCXML chart](https://tinyactors.dev/guides/charts/index.md), and an uploaded chart runs in [the QuickJS sandbox](https://tinyactors.dev/guides/quickjs/index.md).
## Choose Rivet when actors must move between machines
- **Placement and failover you don't write**: The control plane places each actor and moves it when its node stops. tinyactors leaves [placement and failover between hosts](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) to your program.
- **A replicated database per actor**: Each actor's SQLite writes are [replicated before they're acknowledged](https://rivet.dev/actors/docs/state/), and the database follows the actor to another node.
- **A managed service**: [Rivet Cloud](https://rivet.dev/) runs the control plane on AWS and Google Cloud, or in your own VPC on AWS, Google Cloud or Azure.
- **Actors as ordinary code**: A Rivet actor is a set of actions in TypeScript or Rust ([Rivet, "Actors"](https://rivet.dev/docs/actors)), with no chart format to learn.
[Hibernate idle sessions](https://tinyactors.dev/guides/hibernation/index.md) · [Upgrade running actors](https://tinyactors.dev/guides/migration/index.md) · [See when to use tinyactors](https://tinyactors.dev/when-to-use/index.md)
---
# 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)
## 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.
## 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
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"
```
Browsers:
```javascript title="browser.mjs"
import { compileCharts, Host } from '@tinyactors/wasm';
let charges = 0;
const payments = {
receive(send) { // the chart's
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"
```
Python:
```python title="main.py"
import asyncio
import json
import tinyactors
class Payments:
charges = 0
def receive(self, send): # the chart's
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"
```
C:
```c title="main.c"
/* cc main.c host.c -ltinyactors_datamodel_ecmascript -ltinyactors_runtime -ltinyactors -lm */
#include
#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 */
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 */
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 : 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
#include
#include
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
#include
#include
/* 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"
```
```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
```
## 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)).
## 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 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)
## 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 title="session-v2.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.
## 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.
## 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)
---
# A million ants in your browser
Kind: pitch. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).
> Two anthills in a browser tab, where every ant and queen is a tinyactors actor running on WebAssembly.
Two colonies share this field, and every ant and queen is an actor running in your browser.
## Drop food and squash ants
Tap the field to use the tool you picked, and pinch to zoom in on a fight. Follow an ant to keep it in view beside its chart, lit in the state the ant is in.
Two anthills on a field. Workers carry food home to their queen, and workers of the two colonies fight where they meet.
## An ant is a statechart
An egg becomes a larva and then a worker, which forages until an event ends it. The world sends `die` when the ant grows old.
```scxml title="ant.scxml"
```
## So is a queen
Once a second she lays an egg for every two pieces of food her workers brought home.
```scxml title="queen.scxml"
```
## Charts send messages to the world
The ant's chart sends `forage` to the world and waits for `arrive` or `found`. The world is a JavaScript object on this page that picks each destination.
```javascript title="world.mjs"
const slot = free[--freeTop];
if (session >= slotOf.length) {
const grown = new Int32Array(Math.max(session + 1, slotOf.length * 2)).fill(-1);
grown.set(slotOf);
slotOf = grown;
}
slotOf[session] = slot;
sessionOf[slot] = session;
stage[slot] = BROOD; carrying[slot] = 0;
phase[slot] = ((slot * .61803398875) % 1) * 2;
t0[slot] = t1[slot] = 0;
placeInHill(slot);
counts.brood++; counts.born++;
touch(slot);
}
```
This page runs each colony as a host in its own Web Worker, so the browser can use two CPU cores.
## Messages decide how many ants keep up
An ant uses the CPU only while it handles a message. While it walks or rests, it waits in memory and your GPU draws it.
The rest slider sets how long ants stay in the hill between outings, so shorter rests mean more messages a second. The time per message stays level as you add ants, and the real-time chart shows whether your device keeps up.
## The same world runs in Node.js
With a simulated clock and a fixed seed, every run prints the same five minutes of both colonies.
```javascript title="main.mjs"
const chart = (name) => readFileSync(new URL(`./${name}.scxml`, import.meta.url), 'utf8');
const charts = { ant: chart('ant'), queen: chart('queen') };
const colonies = await Promise.all([0, 1].map((colony) => createColony(tinyactors, { charts, population: 1500, colony, seed: 7 })));
for (const colony of colonies) await colony.populate();
let messages = [null, null];
for (let minute = 1; minute <= 5; minute++) {
for (let frame = 0; frame < 60_000 / FRAME; frame++) {
messages = await Promise.all(colonies.map((colony, i) => colony.step(messages[1 - i])));
}
const stats = colonies.map((colony) => colony.stats());
const shown = stats.map(({ colony: c }, i) => `hill ${i + 1}: ${c.workers} workers, ${c.brood} brood, ${c.stored} food home, ${c.born} born, ${c.deaths} died`);
console.log(`minute ${minute}: ${shown.join('; ')}; ${stats[0].fights + stats[1].fights} fights`);
}
```
```text title="output"
minute 1: hill 1: 1500 workers, 0 brood, 1093 food home, 1500 born, 0 died; hill 2: 1499 workers, 1 brood, 1106 food home, 1501 born, 1 died; 29 fights
minute 2: hill 1: 1499 workers, 1 brood, 2322 food home, 1501 born, 1 died; hill 2: 1500 workers, 0 brood, 2345 food home, 1501 born, 1 died; 36 fights
minute 3: hill 1: 1490 workers, 10 brood, 3537 food home, 1511 born, 11 died; hill 2: 1493 workers, 7 brood, 3568 food home, 1509 born, 9 died; 58 fights
minute 4: hill 1: 1479 workers, 21 brood, 4748 food home, 1534 born, 34 died; hill 2: 1484 workers, 16 brood, 4753 food home, 1526 born, 26 died; 63 fights
minute 5: hill 1: 1456 workers, 44 brood, 5947 food home, 1584 born, 84 died; hill 2: 1465 workers, 35 brood, 5984 food home, 1568 born, 68 died; 65 fights
```
---
# Property testing a statechart
Kind: tutorial. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Tutorial](https://tinyactors.dev/voices/tutorial.xml).
> Replace unit tests with properties: generate worlds from seeds, find the run that breaks the chart, shrink it, and read its trace. In your browser.
A unit test checks one run you thought of. A property holds for every run. Generate the runs, find the one that breaks, and shrink it. Everything on this page runs in your browser.
- Browsers: `npm install @tinyactors/wasm` (@tinyactors/wasm 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#wasm-0-4-0) · [Browsers guide](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/docs/guide/browser.md))
- Node.js and Bun: `npm install @tinyactors/node` (@tinyactors/node 0.4.0, 19 November 2026 · [What changed](https://tinyactors.dev/changelog/index.md#node-0-4-0) · [Node.js and Bun guide](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/docs/guide/testing.md))
[Start](https://tinyactors.dev/property-testing/index.md#chart) · [Get the code](https://github.com/tinyactors-dev/tinyactors/tree/main/website/examples/property)
## 1. Write the chart
A payment charges a card, retries after 30 seconds of silence, and gives up after three attempts.
```scxml title="payment.scxml"
```
## 2. Make the world data
The chart only sees events. So a world is an array: does the service answer charge 1, charge 2, and so on.
```javascript title="property.mjs"
// A run: the chart against a world. The world is data: answers[n] says
// whether the payment service answers the chart's charge number n. Nothing
// else decides what happens, so the same answers make the same run.
export async function run(compiled, answers, { trace = false } = {}) {
const clock = new SimulatedClock();
const charges = [];
const requests = [];
let outcome;
const host = new Host(compiled, {
system: 'property',
clock,
config: { system: { ticksPerSecond: 1000 }, ...(trace ? { telemetry: { resource: { 'service.name': 'payment' } } } : {}) },
...(trace ? { telemetry: (signal, data) => signal === 'traces' && requests.push(data) } : {}),
ioProcessors: {
'urn:payments': {
receive(send) {
const n = charges.push(clock.now) - 1;
if (answers[n]) send.answer('charged');
},
},
},
onDone: (actor, donedata) => { outcome = donedata.outcome; },
});
host.spawn('payment');
await host.idle();
while (outcome === undefined) {
clock.increment(host.nextDeadline); // the next timeout, at once
await host.idle();
}
host.close(); // the last traces go to the telemetry handler here
return { answers, charges, outcome, spans: requests.flatMap((data) => decodeTraces(data)) };
}
```
Run `[silence, answer]` with tracing on. Select a row to see its transitions.
[Run it](https://tinyactors.dev/property-testing/#world) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)
## 3. State the properties
Whatever the service does, the payment charges at most three times and gives up only after the third charge. It is paid only when the service answered.
```javascript title="property.mjs"
// Properties: what must hold for every run, whatever the world did.
export const properties = {
'never more than three charges': (r) => r.charges.length <= 3,
'gives up only after three charges': (r) => r.outcome === 'paid' || r.charges.length === 3,
'paid only when the service answered': (r) => r.outcome === 'failed' || r.answers.slice(0, r.charges.length).some(Boolean),
};
export const broken = (r) => Object.keys(properties).filter((name) => !properties[name](r));
```
## 4. Search a thousand worlds
A seed makes a world. The search runs seeds until one breaks a property, and the seed reproduces it.
```javascript title="property.mjs"
// A generator: a world from a seed, three to eight answers, each yes with
// probability 0.4. The seed reproduces it.
export function generate(seed) {
const random = mulberry32(seed);
return Array.from({ length: 3 + Math.floor(random() * 6) }, () => random() < 0.4);
}
// The search: worlds from seeds 1 to `seeds`, until one breaks a property.
export async function search(compiled, seeds) {
for (let seed = 1; seed <= seeds; seed++) {
const r = await run(compiled, generate(seed));
if (broken(r).length) return { seed, run: r };
}
return null;
}
```
[Search](https://tinyactors.dev/property-testing/#search) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)
## 5. Plant a bug
Retry while `attempts < 4`. A unit test that answers the first charge still passes.
```javascript title="main.mjs"
const buggy = compile(chart.replace('attempts < 3', 'attempts < 4')); // one retry too many
const failure = await search(buggy, 1000);
console.log(`seed ${failure.seed}: ${show(failure.run.answers)} breaks ${broken(failure.run).join(', ')}`);
```
[Search](https://tinyactors.dev/property-testing/#bug) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)
## 6. Shrink the failure
Try smaller worlds until none still fails. What is left is the bug and nothing else.
```javascript title="property.mjs"
// The shrinker: a smaller world that still breaks a property, until no
// smaller one does. Smaller is one answer fewer, or a yes turned into
// silence.
export async function shrink(compiled, answers) {
let smallest = answers;
for (let changed = true; changed; ) {
changed = false;
for (const candidate of smaller(smallest)) {
if (broken(await run(compiled, candidate)).length) {
smallest = candidate;
changed = true;
break;
}
}
}
return smallest;
}
function* smaller(answers) {
for (let n = 0; n < answers.length; n++) yield answers.toSpliced(n, 1);
for (let n = 0; n < answers.length; n++) if (answers[n]) yield answers.with(n, false);
}
```
[Shrink and trace](https://tinyactors.dev/property-testing/#shrink) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)
The smallest world is empty: the service never answers. The trace shows a fourth charge at 90 seconds.
## 7. Run it in CI
The same module runs in Node.js and Bun. A failure names its seed.
```javascript title="main.mjs"
// The guide's runs, in Node.js. Run: node main.mjs
import { readFileSync } from 'node:fs';
import { broken, compile, run, search, shrink } from './property.mjs';
const chart = readFileSync(new URL('./payment.scxml', import.meta.url), 'utf8');
const show = (answers) => `[${answers.map((yes) => (yes ? 'answer' : 'silence')).join(', ')}]`;
const correct = compile(chart);
const found = await search(correct, 1000);
console.log(found ? `seed ${found.seed} breaks ${broken(found.run).join(', ')}` : '1000 worlds: every property held');
const buggy = compile(chart.replace('attempts < 3', 'attempts < 4')); // one retry too many
const failure = await search(buggy, 1000);
console.log(`seed ${failure.seed}: ${show(failure.run.answers)} breaks ${broken(failure.run).join(', ')}`);
const smallest = await shrink(buggy, failure.run.answers);
const replay = await run(buggy, smallest, { trace: true });
console.log(`shrunk to ${show(smallest)}: ${replay.charges.length} charges, ${replay.outcome}`);
console.log(`its trace: ${replay.spans.filter((span) => span.name.startsWith('scxml.macrostep')).map((span) => span.name.replace('scxml.macrostep ', '')).join(' → ')}`);
correct.close();
buggy.close();
```
```text title="output"
1000 worlds: every property held
seed 10: [silence, silence, silence, silence, silence, answer] breaks never more than three charges, gives up only after three charges
shrunk to []: 4 charges, failed
its trace: bootstrap → timeout → timeout → timeout → timeout
```
## Go further
There is no library to install. The world, the properties, the generator, the search and the shrinker are 76 lines of your own code.
- **Richer worlds**: Late, duplicate and reordered answers are more entries in the array.
- **More actors**: Generate the [team chat](https://tinyactors.dev/chat/index.md)'s inputs. Every online member sees every post.
- **Trace properties**: Spans are data. Assert on how a run got there, not only where it ended.
[Read the testing guide](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/docs/guide/testing.md) · [Build a team chat](https://tinyactors.dev/chat/index.md)
---
# Telemetry: every step is a span
Kind: pitch. For: [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).
> tinyactors reports what its actors do as OpenTelemetry: a span for each step, logs and metrics, with W3C trace context across actors and systems.
A host reports what its actors did as OpenTelemetry: a span for each step, logs, and metrics. It does no I/O itself. Your exporter sends the bytes.
[See a trace](https://tinyactors.dev/telemetry/index.md#read) · [Turn it on](https://tinyactors.dev/telemetry/index.md#on)
## Read a trace
This payment charges a card, retries after 30 seconds of silence, and gives up after three attempts.
```scxml title="payment.scxml"
```
Run it, traced, while the service is silent once and then answers. Each row is a step under the step that caused it, and selecting one shows its transitions and sends.
[Run it](https://tinyactors.dev/telemetry/#read) · [live.mjs](https://tinyactors.dev/examples/property/live.mjs)
## Turn it on
Give the host an encoder in its config and a handler for the requests it writes. The handler gets OTLP bytes to post to a collector, and this one reads the spans back.
```javascript title="telemetry.mjs"
import { compileCharts, decodeTraces, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'order.scxml', text: `
` }]);
const requests = [];
const clock = new SimulatedClock();
const host = new Host(compiled, {
system: 'shop',
config: {
system: { ticksPerSecond: 1000 }, // the host's clock in milliseconds
telemetry: { flushInterval: 1000, resource: { 'service.name': 'shop' } }, // a request at most a second after its first record
},
clock,
telemetry: (signal, data) => {
// A real exporter posts the bytes, from a promise so the host goes on:
// fetch(`${collector}/v1/${signal}`, { method: 'POST', headers: { 'content-type': 'application/x-protobuf' }, body: data })
requests.push([signal, data]);
},
});
compiled.close();
const caller = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01'; // a W3C traceparent, from an HTTP header
host.spawn('order').send('pay', undefined, { traceparent: caller });
await host.idle();
console.log('requests before the flush interval:', requests.length);
clock.increment(1000);
await host.idle();
console.log('signals:', requests.map(([signal]) => signal).sort().join(', '));
// Read the spans back (for a test; a collector does this for you).
for (const [signal, data] of requests) {
if (signal !== 'traces') continue;
const spans = decodeTraces(data);
const ours = spans.filter((span) => span.trace === '0af7651916cd43dd8448eb211c80319c');
console.log('spans in the caller\'s trace:', ours.map((span) => span.name).sort().join(', '));
const step = ours.find((span) => span.name === 'scxml.macrostep pay');
console.log('the step\'s parent is the caller\'s span:', step.parent === 'b7ad6b7169203331');
}
host.close();
```
```text title="output"
requests before the flush interval: 0
signals: logs, traces
spans in the caller's trace: scxml.destroyed, scxml.finished, scxml.macrostep pay, scxml.microstep pay
the step's parent is the caller's span: true
```
## Tune the encoder
| Key | Default | What it does |
|---|---|---|
| `flushInterval` | 0 | a request is ready this long after its first record, in the host's clock ticks (`system.ticksPerSecond`); 0 means only when the staging is full, or at close |
| `resource` | none | attributes on every request, such as `service.name` (at most 32, text to text) |
| `logs` | `true` | `` lines and failed actions as log records |
| `values` | `false` | event data and assigned values in the spans; they may hold personal data, so turn this on knowingly |
| `linkParents` | `false` | an actor's step is a root span linked to its cause, instead of its child |
| `stagingBytes` | 1048576 | the encoder's staging memory |
## Follow a request
A `traceparent` passed with an input is the parent of the step it starts. A send carries the sender's trace to the next actor, or to another system.
```javascript title="context.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'c.scxml', text: `
` }]);
const host = new Host(compiled, {
system: 'demo',
ioProcessors: {
'urn:example:api': {
receive(send) {
const [, trace] = send.traceparent.split('-');
console.log('the outgoing request continues trace', trace);
// fetch(url, { headers: { traceparent: send.traceparent } })
},
},
},
});
compiled.close();
host.spawn('c').send('go', undefined, {
traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
});
await host.idle();
host.close();
```
```text title="output"
the outgoing request continues trace 4bf92f3577b34da6a3ce929d0e0e4736
```
## Choose what is traced
Set the detail for every actor, or watch one chart closely for a while.
```javascript title="watch.mjs"
import { Host } from '@tinyactors/node';
const host = new Host([], { system: 'shop', config: { telemetry: {} } });
await host.traceConfigure({ detail: 'summary', sample: 0.01 });
console.log('1 trace in 100, summarized');
const watch = await host.traceWatch({ rules: [{ chart: 'checkout', sample: 'keep', detail: 'full' }], seconds: 60 });
console.log(`watch ${watch.id}: every checkout in full for a minute`);
host.close();
```
```text title="output"
1 trace in 100, summarized
watch 1: every checkout in full for a minute
```
---
# Memory, capacity and performance
Kind: reference. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> What a tinyactors actor costs in memory, how to size a host, how each operation's cost holds as the population doubles, and its conformance to SCXML.
A started actor takes about 530 bytes and a hibernated one about 120. Four million fit in one process, and each operation costs about the same at four million actors as at two.
[Measure your device](https://tinyactors.dev/performance/index.md#lab) · [See the costs](https://tinyactors.dev/performance/index.md#actors) · [See the scaling](https://tinyactors.dev/performance/index.md#scale)
## Measure it on your device
Pick a scenario and a population, and one host runs it in a Worker on this page.
A host on this device runs a colony of cells that eat, give food to neighbours, divide and die, or a fixed population of up to four million actors that wait, get events, message each other, sleep in a store or hold timers. Charts follow the actors alive, births and deaths, events a second, time per event and memory over the whole run.
Every cell in the colony runs this chart, and dies in one of its two final states.
```scxml title="cell.scxml"
```
## An actor takes about 530 bytes
Each cell is the memory one more actor, message or delayed send adds to a process holding a million.
| runtime, datamodel | actor, started | actor, after an event | actor, hibernated | message waiting | delayed send pending |
|---|---|---|---|---|---|
| node, native | 532 B | 673 B | 118 B | 309 B | 353 B |
| bun, native | 601 B | 781 B | 93 B | 386 B | 448 B |
| node, quickjs | 1036 B | 1634 B | 92 B | 309 B | 358 B |
| bun, quickjs | 1041 B | 1645 B | 90 B | 313 B | 356 B |
Measured 2026-11-25 on an Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5 and Bun 1.4.1. A counter chart with one variable, messages of `{"text": "hello"}`, tracing on.
A host's fixed costs spread over its actors, so an actor costs less in a larger population.
| | 10,000 | 100,000 | 1,000,000 | 2,000,000 | 4,000,000 |
|---|---|---|---|---|---|
| per actor, started | 803 B | 720 B | 532 B | 510 B | 495 B |
| per actor, after an event | 1446 B | 870 B | 673 B | 654 B | 639 B |
| per actor, hibernated | 637 B | 269 B | 118 B | 100 B | 91 B |
| per message waiting | 602 B | 392 B | 309 B | 293 B | 285 B |
| per delayed send pending | 737 B | 489 B | 353 B | 338 B | 331 B |
Node.js on the native datamodel, the same run.
## Size a host
A host grows on its own, but each growth copies its memory. A host that will hold a known population is better sized for it.
```javascript title="size.mjs"
import { Host } from '@tinyactors/node';
const N = 2_000_000; // actors
const R = 1000; // resident at most
const room = 64;
const host = new Host([], { system: 'big', config: { system: {
maxActors: N + room, maxEvents: 4096,
instanceBytes: 2048 * (R + room), stringBytes: 16384 + 64 * (R + room),
} } });
console.log((await host.hostConfig()).system.maxActors);
host.close();
```
```text title="output"
2000064
```
`hostStats` reports each pool's capacity, what it uses and its high water mark:
```javascript title="stats.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'idle.scxml', text: `
` }]);
const image = compiled.image;
compiled.close();
for (const system of [{}, { maxActors: 1000 }]) {
const host = new Host(image, { system: 'demo', config: { system } });
const before = (await host.hostStats()).pools[0].actors;
for (let i = 0; i < 1000; i++) host.spawn('idle');
const after = (await host.hostStats()).pools[0].actors;
console.log(`maxActors ${system.maxActors ?? 'default'}: capacity ${before.capacity}, ` +
`then ${after.used} used, high water ${after.highWater}, grown: ${after.capacity > before.capacity}`);
host.addImage(image);
console.log('segments reported:', (await host.hostStats()).pools.map((pool) => pool.segment).join(', '));
host.close();
}
```
```text title="output"
maxActors default: capacity 64, then 1000 used, high water 1000, grown: true
segments reported: 0, 1
maxActors 1000: capacity 1000, then 1000 used, high water 1000, grown: false
segments reported: 0, 1
```
## Twice the actors, the same cost
Each row times one operation of the API on two million actors and on four million. Each cell gives both costs and their ratio, and a test fails when a ratio passes 1.5.
| operation | unit | node, native | node, quickjs | bun, native | bun, quickjs |
|---|---|---|---|---|---|
| populate (spawn and hibernate) | µs per actor | 10.88 → 10.56 (0.97) | 7.43 → 7.56 (1.02) | 7.52 → 7.81 (1.04) | 6.26 → 6.02 (0.96) |
| spawn | µs per call | 5.25 → 5.19 (0.99) | 2.62 → 2.60 (0.99) | 4.11 → 4.16 (1.01) | 2.43 → 2.45 (1.01) |
| terminate | µs per call | 0.867 → 0.786 (0.91) | 0.571 → 0.575 (1.01) | 0.952 → 0.893 (0.94) | 0.751 → 0.720 (0.96) |
| send | µs per call | 3.79 → 3.64 (0.96) | 1.90 → 1.77 (0.93) | 3.19 → 3.00 (0.94) | 2.12 → 2.06 (0.97) |
| sendMany | µs per event | 3.98 → 3.86 (0.97) | 2.18 → 2.04 (0.93) | 2.87 → 2.83 (0.99) | 2.01 → 1.85 (0.92) |
| send (hibernated: woken from the store) | µs per call | 32.27 → 27.93 (0.87) | 28.29 → 27.92 (0.99) | 24.71 → 25.96 (1.05) | 33.43 → 33.10 (0.99) |
| hibernate | µs per call | 5.41 → 4.93 (0.91) | 4.21 → 4.17 (0.99) | 3.56 → 3.44 (0.97) | 4.07 → 3.86 (0.95) |
| wake | µs per call | 6.94 → 6.38 (0.92) | 3.90 → 3.69 (0.95) | 6.91 → 7.27 (1.05) | 4.19 → 4.43 (1.06) |
| actor (by name) | µs per call | 3.96 → 4.01 (1.01) | 3.96 → 3.88 (0.98) | 1.32 → 1.20 (0.91) | 1.13 → 1.12 (0.99) |
| actorState | µs per call | 4.26 → 4.01 (0.94) | 4.15 → 4.11 (0.99) | 3.90 → 3.73 (0.96) | 3.66 → 3.58 (0.98) |
| hostStats | µs per call | 25.65 → 25.05 (0.98) | 24.49 → 23.49 (0.96) | 19.35 → 19.60 (1.01) | 18.96 → 18.23 (0.96) |
| I/O processor round trip | µs per call | 10.11 → 10.16 (1.01) | 6.81 → 6.73 (0.99) | 7.09 → 6.87 (0.97) | 5.77 → 5.54 (0.96) |
| transport round trip | µs per call | 30.55 → 31.31 (1.02) | 25.92 → 26.36 (1.02) | 25.19 → 26.15 (1.04) | 22.05 → 23.06 (1.05) |
| delayed send and its timer | µs per call | 6.28 → 6.19 (0.98) | 3.09 → 3.01 (0.97) | 4.95 → 5.15 (1.04) | 3.35 → 3.37 (1.01) |
| invoked service round trip | µs per call | 13.52 → 13.93 (1.03) | 10.33 → 10.12 (0.98) | 10.13 → 10.66 (1.05) | 9.15 → 9.79 (1.07) |
| sweep (every actor) | µs per actor | 0.006 → 0.005 (0.87) | 0.006 → 0.005 (0.87) | 0.006 → 0.006 (0.95) | 0.006 → 0.006 (0.91) |
| migrate (one session) | µs per call | 24.09 → 25.32 (1.05) | 16.51 → 16.95 (1.03) | 35.62 → 20.64 (0.58) | 16.90 → 16.30 (0.96) |
| snapshot | µs per actor | 0.100 → 0.092 (0.92) | 0.079 → 0.084 (1.07) | 0.081 → 0.087 (1.08) | 0.101 → 0.092 (0.92) |
| restore (and its first turn) | µs per actor | 0.291 → 0.298 (1.02) | 0.217 → 0.215 (0.99) | 0.223 → 0.217 (0.98) | 0.198 → 0.192 (0.97) |
| close | µs per actor | 0.114 → 0.128 (1.13) | 0.120 → 0.157 (1.31) | 0.126 → 0.127 (1.01) | 0.120 → 0.139 (1.16) |
Most actors hibernated in SQLite, at most 1000 resident. Measured 2026-11-20 on an Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5 and Bun 1.4.1. Microseconds.
## Correct by the standard
The core passes the [W3C's SCXML test suite](https://www.w3.org/Voice/2013/scxml-irp/), and every binding runs it too.
- **All 191 automatic W3C tests pass**: That is 158 mandatory tests and 33 optional ones, BasicHTTP included. Source: [tinyactors-core, `docs/architecture.md`, section 15](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-core/docs/architecture.md#15-implementation-status-and-deviations-from-this-design)
- **Every binding runs the same suite**: The conformance suite runs the W3C tests and its own scenarios against each binding, on each of its datamodels. Source: [tinyactors-test, `README.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-test/README.md)
---
# Why tinyactors exists
Kind: explanation. For: [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Explanation](https://tinyactors.dev/voices/explanation.xml).
> Why tinyactors exists, who maintains it, its license, where its source is and how it is released.
tinyactors runs SCXML charts as actors inside programs that already chose their I/O, threads and memory. It is MIT licensed and maintained by [_dhamidi](https://x.com/_dhamidi) at [Amp](https://ampcode.com).
[Dario Hamidi](https://github.com/dhamidi)
## Give stateful logic one home
The state of a live websocket connection, with its retries, reconnects and timeouts, often has no clear home in a system. An actor models how one connection behaves, without the whole system in your head.
The core does no I/O, starts no threads and allocates no memory itself. So it embeds in a runtime that already decided all three.
- **The core uses no C library**: Your program gives it an allocator, performs its effects and tells it the time. Source: [tinyactors, `README.md`](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md)
## Maintained by _dhamidi at Amp
tinyactors is maintained by [_dhamidi](https://x.com/_dhamidi) at [Amp](https://ampcode.com). Its license names Dario Hamidi as the copyright holder.
## Use it under the MIT license
You may use, change and ship tinyactors in any program, keeping its copyright and permission notice.
- **Every package is MIT licensed**: The repository's license covers the C core, and the Node.js and Python packages declare MIT too. Source: [tinyactors, `LICENSE`](https://github.com/tinyactors-dev/tinyactors/blob/main/LICENSE) · [tinyactors-napi, `package.json`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-napi/package.json) · [tinyactors-cpython, `pyproject.toml`](https://github.com/tinyactors-dev/tinyactors/blob/main/tinyactors-cpython/pyproject.toml)
## Read the source and its tests
One repository holds the C core, the Node.js and Python packages, the conformance suite and this site. Every binding runs the same suite.
[Read the source](https://github.com/tinyactors-dev/tinyactors) · [See the test results](https://tinyactors.dev/performance/index.md#correctness)
## Follow each release in the changelog
Each package is released on its own. Its changelog says what changed in each release and how to upgrade.
The API is still changing: [the README](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#status) says breaking changes are made frequently to land on a good API.
[Read the changelog](https://tinyactors.dev/changelog/index.md)
---
# Testing recipes
Kind: how-to. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).
> Examples for testing chart timeouts, retries, and service replies with Tiny Actors.
Test retries and timeouts with a clock you control and handlers that answer when the test needs them to.
## Test a WebSocket reconnect
This case drops the connection, advances to the next timer, and reports a successful reply. It checks that the chart reconnects and clears its timers.
```javascript title="main.mjs"
lab.drop();
const waiting = await lab.read();
assert.deepEqual(waiting.timers.map(timer => timer.due), [2000, 30000]);
await lab.advance(waiting.timers[0]);
assert.equal((await lab.read()).pending, 1);
lab.reply(true);
const reopened = await lab.read();
assert.equal(reopened.value, 'online');
assert.deepEqual(reopened.timers, []);
```
[Try the WebSocket reconnect lab](https://tinyactors.dev/guides/testing/index.md#reconnect-lab).
## Replace the chart's services and its clock
A chart reaches the world only through sends. The host passes each send to a handler you give it, an I/O processor.
- **The test's handlers stand in for the services.**: They record what the chart sent and answer when the case needs it, with an error, or never.
- **A `SimulatedClock` moves only when the test moves it.**: A timeout of an hour takes no time.
- **`await host.idle()` returns when the host has nothing left to do.**: Assertions after it see everything the inputs before it did by the clock's time.
To check properties over generated runs instead of single cases, read [Property testing a statechart](https://tinyactors.dev/property-testing/index.md).
## Check each step of a retrying payment
This chart charges a card, retries when no answer comes within 30 seconds, and gives up after the third attempt. Its test moves the clock 30 seconds at a time and checks each charge.
```javascript title="payment.test.mjs"
import assert from 'node:assert/strict';
import { compileCharts, Host, SimulatedClock, StaleError } from '@tinyactors/node';
const chart = `
`;
/** A host running the chart on a simulated clock, recording its charges. */
function setup() {
const compiled = compileCharts([{ name: 'payment.scxml', text: chart }]);
const clock = new SimulatedClock();
const charges = [];
const logs = [];
const host = new Host(compiled, {
system: 'test',
clock,
ioProcessors: { 'urn:example:payments': { receive: (send) => charges.push({ at: clock.now, target: send.target }) } },
log: (entry) => logs.push(entry.text),
});
compiled.close();
return { host, clock, charges, logs };
}
/** The actor's state value, read with a typed method. */
const state = async (actor) => (await actor.state()).value;
// It retries every 30 seconds and gives up after three attempts.
{
const { host, clock, charges, logs } = setup();
const payment = host.spawn('payment', { name: 'payment' });
await host.idle();
assert.deepEqual(charges, [{ at: 0, target: 'card' }]);
assert.equal(await state(payment), 'charging');
clock.increment(30_000);
await host.idle();
clock.increment(30_000);
await host.idle();
assert.deepEqual(charges.map((charge) => charge.at), [0, 30_000, 60_000]);
clock.increment(30_000);
await host.idle();
assert.deepEqual(logs, ['gave up after 3']);
assert.throws(() => host.actor('payment'), StaleError, 'a final state ends the actor');
host.close();
console.log('ok: retries, then gives up');
}
// An answer before the timeout ends it, and no timer is left.
{
const { host, clock, charges } = setup();
const payment = host.spawn('payment', { name: 'payment' });
await host.idle();
payment.send('charged');
await host.idle();
assert.throws(() => host.actor('payment'), StaleError);
assert.equal(host.nextDeadline, undefined, 'the timer was cancelled');
clock.increment(60_000);
await host.idle();
assert.equal(charges.length, 1);
host.close();
console.log('ok: an answer ends it');
}
```
```text title="output"
ok: retries, then gives up
ok: an answer ends it
```
The second case answers with `payment.send('charged')`, as the handler's `send.answer('charged')` would, without the `sendid`. A handler may answer just as well.
Read the actor's state with `actor.state()` after an `idle()`: it reads the host as it is when called ([Inspecting a host](https://tinyactors.dev/guides/inspection/index.md)).
Give the actor a name to see it end: a final state frees the name, so `host.actor(name)` throws `StaleError`.
## Step to each deadline to see every tick
`clock.increment(ms)` moves the clock once. What is due by then runs once, at the new time, and a delay it starts counts from there.
So a chart that ticks every second ticks once for an `increment(3500)`, and its next tick is due a second later. Stepping by `host.nextDeadline`, the milliseconds to the next deadline, logs every tick:
```javascript title="ticker.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'ticker.scxml', text: `
` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, { system: 'test', clock, log: (entry) => console.log(entry.text, 'at', clock.now) });
compiled.close();
host.spawn('ticker');
await host.idle();
clock.increment(3500); // one jump: one tick
await host.idle();
while (clock.now < 6500) { // step deadline by deadline
clock.increment(host.nextDeadline);
await host.idle();
}
host.close();
```
```text title="output"
tick 1 at 3500
tick 2 at 4500
tick 3 at 5500
tick 4 at 6500
```
## Await idle before you move the clock
`actor.send` returns before the actor handles the event, which it does later, at the clock's time then. Until then `host.nextDeadline` holds no deadline the event starts.
So an event sent just before an `increment` runs after the clock moved, and a delay it starts counts from there:
```javascript title="hold.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'hold.scxml', text: `
` }]);
const clock = new SimulatedClock();
const host = new Host(compiled, { system: 'test', clock, log: (entry) => console.log(entry.text, 'at', clock.now) });
compiled.close();
const actor = host.spawn('hold');
await host.idle();
actor.send('reserve');
console.log('nextDeadline right after the input:', host.nextDeadline);
clock.increment(59_000); // the input runs now, at 59000: the hold is due at 119000
await host.idle();
actor.send('reserve');
await host.idle(); // the input runs at 59000, before the step
clock.increment(60_000);
await host.idle();
host.close();
```
```text title="output"
nextDeadline right after the input: undefined
reserved at 59000
reserved at 59000
expired at 119000
expired at 119000
```
Both holds came due at 119000, though the first was sent at 0. Await `idle()` after each event whose effect the next step or assertion needs.
## On the real clock, await the actor's result
On the real clock, `await host.idle()` returns while a timeout is still pending. It waits only for work due now and for promises your handlers returned.
`await actor.done` waits instead for the actor's top-level final state, and settles with its ``. `await actor.ask(event, data)` sends an event and settles with the chart's reply:
```javascript title="job.mjs"
import { compileCharts, Host } from '@tinyactors/node';
const compiled = compileCharts([{ name: 'job.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'test' });
compiled.close();
const job = host.spawn('job');
const [event, data] = await job.ask('how');
console.log('asked:', event, data);
await host.idle();
console.log('after idle():', (await host.actors()).length === 0 ? 'ended' : 'still running');
console.log('done:', await job.done);
host.close();
```
```text title="output"
asked: progress 0
after idle(): still running
done: all done
```
`ask` gives the event an origin the host answers itself. The chart replies with ``, as to another actor, and the promise settles with the reply's event name and data.
To give up on an ask, pass an `AbortSignal` as `ask(event, data, { signal })`. The ask rejects with the signal's reason, and a later reply is dropped.
A host closed while an ask waits leaves it pending for ever, as it leaves the promise of `actor.state()`.
## Wait until any condition holds
This helper checks a condition every 10 ms of the real clock and awaits `host.idle()` between checks. Here it waits for a lamp to be lit:
```javascript title="lamp.mjs"
import { compileCharts, Host } from '@tinyactors/node';
/** Turns the host until `condition()` holds, checking every 10 ms. */
async function until(host, condition, ms = 5000) {
for (const end = Date.now() + ms; !(await condition()); ) {
if (Date.now() > end) throw new Error('timed out');
await new Promise((resolve) => setTimeout(resolve, 10));
await host.idle();
}
}
const compiled = compileCharts([{ name: 'lamp.scxml', text: `
` }]);
const host = new Host(compiled, { system: 'test' });
compiled.close();
const lamp = host.spawn('lamp');
await until(host, async () => (await lamp.state()).value === 'lit');
console.log('lit');
host.close();
```
```text title="output"
lit
```
## Start each test from a snapshot
Set up a host once and take `host.snapshot()`. Each test then starts with `Host.restore` of it, the same actors in the same states ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).
## Run the tests in QuickJS too
When production runs your charts in QuickJS, run each test a second time with `datamodel: 'quickjs'` on the host ([The quickjs sandbox](https://tinyactors.dev/guides/quickjs/index.md)).
## Fail the test on a handler's error
A handler that throws makes the next `await host.idle()` reject, which fails the test ([Errors](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#errors)).
A host given `onHandlerError` reports the error there instead. Collect what it receives and assert the list is empty.
## Close every host in teardown
Call `host.close()` in a `finally` or the test framework's teardown. A forgotten host on a `SimulatedClock` lets the process exit, but holds its memory until collected.
---
# tinyactors compile
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Compile charts or a system manifest into an image.
Compile charts or a system manifest into an image.
## Usage
```shell
tinyactors compile [options] INPUT...
```
Compiles SCXML charts or one system manifest into a `.tai` image. The first chart is the image's default boot chart. Each static src is read relative to the file that names it, then in each `-I` directory. The answer lists the diagnostics and what the image holds. With `-o` -, the image goes to standard output and the answer to standard error.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-o, --output FILE`**: Write the image to `FILE`, or to standard output when `FILE` is -.
- **`-e, --emit KIND`**: Write the image as `KIND`. Values: image (the image's bytes) or c (an 8-aligned C array). Default: image.
- **`-s, --symbol NAME`**: Name the C array `NAME` with `--emit` c; `NAME` is a C identifier. Default: tinyactors_image.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors compile order.scxml payment.scxml -o order.tai
```
```text title="output"
# Compile
- **Compiled**: yes
- **Output**: order.tai
- **Emit**: image
- **Bytes**: 3552
- **Hash**: b256b6cbfab69138
- **Charts**: 2
- **Boot actors**: 1
## Diagnostics
_none_
```
Compile two charts into one image.
```shell
tinyactors compile system.xml -o system.tai
```
```text title="output"
# Compile
- **Compiled**: yes
- **Output**: system.tai
- **Emit**: image
- **Bytes**: 3568
- **Hash**: 1c8ca2cc7138f14e
- **Charts**: 2
- **Boot actors**: 1
## Diagnostics
_none_
```
Compile a system manifest into an image.
```shell
tinyactors compile order.scxml --emit c --symbol order_image -o order_image.c
```
```text title="output"
# Compile
- **Compiled**: yes
- **Output**: order_image.c
- **Emit**: c
- **Bytes**: 2720
- **Hash**: 5e66ab57693504aa
- **Charts**: 1
- **Boot actors**: 1
## Diagnostics
_none_
```
Write the image as a C array named order_image.
```shell
tinyactors compile order.scxml -o - | tinyactors inspect -
```
```text title="output"
# Inspect
- **From**: image
- **Bytes**: 2720
- **Format**: 1
- **Hash**: 5e66ab57693504aa
- **Charts**: 1
- **Boot actors**: 1
- **Event names**: 18
## Sections
| Section | Offset | Bytes | Records |
| --- | --- | --- | --- |
| strings | 272 | 748 | 748 |
| charts | 1024 | 96 | 1 |
| states | 1120 | 384 | 6 |
| transitions | 1504 | 256 | 8 |
| words | 1760 | 136 | 34 |
| code | 1896 | 108 | 27 |
| expressions | 2008 | 224 | 14 |
| captures | 2232 | 40 | 2 |
| sends | 2272 | 112 | 2 |
| invokes | 2384 | 0 | 0 |
| data | 2384 | 36 | 3 |
| eventNames | 2424 | 288 | 18 |
| bootActors | 2712 | 8 | 1 |
## Charts
| Index | Name | Source | Datamodel | Binding | States | Transitions | Data | Expressions | Sends | Invokes | Code words |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | order | order.scxml | ecmascript | early | 6 | 8 | 3 | 14 | 2 | 0 | 27 |
## Boot actors
| Name | Chart |
| --- | --- |
| order | order |
# Compile
- **Compiled**: yes
- **Output**: -
- **Emit**: image
- **Bytes**: 2720
- **Hash**: 5e66ab57693504aa
- **Charts**: 1
- **Boot actors**: 1
## Diagnostics
_none_
```
Compile to standard output and inspect the image.
## Exit status
- **`1`**: An input is refused: it does not compile, or it is of an unknown format.
- **`3`**: An input cannot be read, the image cannot be written or memory runs out.
## Related pages
- **[`tinyactors check`](https://tinyactors.dev/cli/commands/check/index.md)**: Check that charts compile or that an image verifies.
- **[`tinyactors lint`](https://tinyactors.dev/cli/commands/lint/index.md)**: Find what cannot work as written in charts.
- **[`tinyactors fmt`](https://tinyactors.dev/cli/commands/fmt/index.md)**: Rewrite charts and system manifests in the canonical layout.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors check
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Check that charts compile or that an image verifies.
Check that charts compile or that an image verifies.
## Usage
```shell
tinyactors check [options] INPUT...
```
Compiles the inputs, or verifies an image or every image of a snapshot. Writes nothing but whether they are valid and the diagnostics.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors check charts/*.scxml
```
```text title="output"
# Check
## Inputs
- charts/order.scxml
- charts/payment.scxml
- **Valid**: yes
- **Bytes**: 3568
- **Hash**: a5b071eec6fba4c8
- **Charts**: 2
- **Boot actors**: 1
## Diagnostics
_none_
```
Check that every chart in a directory compiles.
```shell
tinyactors check -W --format json order.scxml
```
```text title="output"
{
"inputs": [
"order.scxml"
],
"valid": true,
"bytes": 2720,
"hash": "5e66ab57693504aa",
"charts": 1,
"bootActors": 1,
"diagnostics": []
}
```
Refuse a chart with a warning and answer in JSON.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors compile`](https://tinyactors.dev/cli/commands/compile/index.md)**: Compile charts or a system manifest into an image.
- **[`tinyactors lint`](https://tinyactors.dev/cli/commands/lint/index.md)**: Find what cannot work as written in charts.
- **[`tinyactors fmt`](https://tinyactors.dev/cli/commands/fmt/index.md)**: Rewrite charts and system manifests in the canonical layout.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors inspect
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Show what an image, a snapshot or a blob holds.
Show what an image, a snapshot or a blob holds.
## Usage
```shell
tinyactors inspect [options] INPUT...
```
Shows an image's sections, charts and boot actors; it reads its inputs as the other commands do. Shows a snapshot's format, system, time, segments with their images and actors. Shows the datamodels' state of a snapshot too, decoded when it is CBOR. Shows the session a hibernation or export blob holds, the image it was written with and who can wake it. Shows a blob's datamodel state, and its chart and configuration when the image follows it: an image, charts or a snapshot.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors inspect order.tai
```
```text title="output"
# Inspect
- **From**: image
- **Bytes**: 3552
- **Format**: 1
- **Hash**: b256b6cbfab69138
- **Charts**: 2
- **Boot actors**: 1
- **Event names**: 22
## Sections
| Section | Offset | Bytes | Records |
| --- | --- | --- | --- |
| strings | 272 | 860 | 860 |
| charts | 1136 | 192 | 2 |
| states | 1328 | 704 | 11 |
| transitions | 2032 | 416 | 13 |
| words | 2448 | 192 | 48 |
| code | 2640 | 108 | 27 |
| expressions | 2752 | 240 | 15 |
| captures | 2992 | 40 | 2 |
| sends | 3032 | 112 | 2 |
| invokes | 3144 | 0 | 0 |
| data | 3144 | 48 | 4 |
| eventNames | 3192 | 352 | 22 |
| bootActors | 3544 | 8 | 1 |
## Charts
| Index | Name | Source | Datamodel | Binding | States | Transitions | Data | Expressions | Sends | Invokes | Code words |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | order | order.scxml | ecmascript | early | 6 | 8 | 3 | 14 | 2 | 0 | 27 |
| 1 | payment | payment.scxml | ecmascript | early | 5 | 5 | 1 | 1 | 0 | 0 | 0 |
## Boot actors
| Name | Chart |
| --- | --- |
| order | order |
```
Show what an image holds.
```shell
tinyactors inspect system.xml
```
```text title="output"
# Inspect
- **From**: system manifest
- **Bytes**: 3568
- **Format**: 1
- **Hash**: 1c8ca2cc7138f14e
- **Charts**: 2
- **Boot actors**: 1
- **Event names**: 22
## Sections
| Section | Offset | Bytes | Records |
| --- | --- | --- | --- |
| strings | 272 | 876 | 876 |
| charts | 1152 | 192 | 2 |
| states | 1344 | 704 | 11 |
| transitions | 2048 | 416 | 13 |
| words | 2464 | 192 | 48 |
| code | 2656 | 108 | 27 |
| expressions | 2768 | 240 | 15 |
| captures | 3008 | 40 | 2 |
| sends | 3048 | 112 | 2 |
| invokes | 3160 | 0 | 0 |
| data | 3160 | 48 | 4 |
| eventNames | 3208 | 352 | 22 |
| bootActors | 3560 | 8 | 1 |
## Charts
| Index | Name | Source | Datamodel | Binding | States | Transitions | Data | Expressions | Sends | Invokes | Code words |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | order | order.scxml | ecmascript | early | 6 | 8 | 3 | 14 | 2 | 0 | 27 |
| 1 | payment | payment.scxml | ecmascript | early | 5 | 5 | 1 | 1 | 0 | 0 | 0 |
## Boot actors
| Name | Chart |
| --- | --- |
| first-order | order |
```
Compile a system manifest and show its image.
```shell
tinyactors inspect --format json order.scxml
```
```text title="output"
{
"from": "charts",
"bytes": 2720,
"format": 1,
"hash": "5e66ab57693504aa",
"charts": 1,
"bootActors": 1,
"eventNames": 18,
"sections": [
{
"section": "strings",
"offset": 272,
"bytes": 748,
"records": 748
},
{
"section": "charts",
"offset": 1024,
"bytes": 96,
"records": 1
},
{
"section": "states",
"offset": 1120,
"bytes": 384,
"records": 6
},
{
"section": "transitions",
"offset": 1504,
"bytes": 256,
"records": 8
},
{
"section": "words",
"offset": 1760,
"bytes": 136,
"records": 34
},
{
"section": "code",
"offset": 1896,
"bytes": 108,
"records": 27
},
{
"section": "expressions",
"offset": 2008,
"bytes": 224,
"records": 14
},
{
"section": "captures",
"offset": 2232,
"bytes": 40,
"records": 2
},
{
"section": "sends",
"offset": 2272,
"bytes": 112,
"records": 2
},
{
"section": "invokes",
"offset": 2384,
"bytes": 0,
"records": 0
},
{
"section": "data",
"offset": 2384,
"bytes": 36,
"records": 3
},
{
"section": "eventNames",
"offset": 2424,
"bytes": 288,
"records": 18
},
{
"section": "bootActors",
"offset": 2712,
"bytes": 8,
"records": 1
}
],
"charts": [
{
"index": 0,
"name": "order",
"source": "order.scxml",
"datamodel": "ecmascript",
"binding": "early",
"states": 6,
"transitions": 8,
"data": 3,
"expressions": 14,
"sends": 2,
"invokes": 0,
"codeWords": 27
}
],
"bootActors": [
{
"name": "order",
"chart": "order"
}
]
}
```
Compile a chart and show its image as JSON.
```shell
tinyactors inspect shop.snapshot
```
```text title="output"
# Inspect
- **From**: snapshot
- **Bytes**: 626112
- **Format**: 4
- **Host format**: 4
- **Library**: 0.5.0
- **Layout ID**: 2eeec427153eedc3
- **This layout**: yes
- **System ID**: shop
- **Time**: 10000
- **Ticks per second**: 1000
- **Identity**: 000000007952af3e
- **Restored**: yes
## Segments
| Index | Live | Image hash | Image bytes | Charts | Actors | Hibernated |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | yes | 1c8ca2cc7138f14e | 3568 | order, payment | 15 | 1 |
| 1 | yes | fbce6399f9cf5b5b | 2984 | order | 1 | 0 |
- **Actors**: 16
- **Hibernated**: 1
## Datamodel state
- **Label**: tinyactors-run
- **Bytes**: 2479
- **Encoding**: cbor
- **Value**: `{"quickjs":h'1c87eae1f11901026901145f73657373696f6e6964010a5f6e616d65011a5f696f70726f636573736f7273015e687474703a2f2f7777772e77332e6f72672f54522f7363786d6c2f235343584d4c4576656e7450726f636573736f7201106c6f636174696f6e010a7363786d6c01107061796d656e7473010a746f74616c0110617474656d707473010c636861726765010c5f6576656e74ba010874797065010c73656e646964010c6f726967696e01146f726967696e747970650110696e766f6b6569640108646174610106736b75010a7072696365010c726566756e64010270010274010272080402090f09060506072031633863613263633731333866313465050008070407023306070e6f726465722d330808030a08010c073674696e796163746f72733a2f2f73686f702f235f7363786d6c5f330e14051008010c07001205d80414050216070a63685f38331808071a07126368617267652e6f6b1c071065787465726e616c1e070670617920022202240226080116070a63685f383302050009060508072031633863613263633731333866313465050008070407023406070e6f726465722d340808030a08010c073674696e796163746f72733a2f2f73686f702f235f7363786d6c5f340e140c1008010c07001205a00614050216070a63685f38341808071a07126368617267652e6f6b1c071065787465726e616c1e070670617920022202240226080116070a63685f38340205000906050a072031633863613263633731333866313465050008070407023506070e6f726465722d350808030a08010c073674696e796163746f72733a2f2f73686f702f235f7363786d6c5f350e14131008010c07001205e80714050216070a63685f38351808071a07126368617267652e6f6b1c071065787465726e616c1e070670617920022202240226080116070a63685f38350205000906050c072031633863613263633731333866313465050008070407023606070e6f726465722d360808030a08010c073674696e796163746f72733a2f2f73686f702f235f7363786d6c5f360e141a1008010c07001205b00914050216011808071a0710636865636b6f75741c071065787465726e616c1e0220022202240226020205000906050e072031633863613263633731333866313465050008070407023706070e6f726465722d370808030a08010c073674696e796163746f72733a2f2f73686f702f235f7363786d6c5f370e14201008010c07001205f80a14050216011808071a0710636865636b6f75741c071065787465726e616c1e02200222022402260202050009060510072031633863613263633731333866313465050008070407023806070e6f726465722d380808030a08010c073674696e796163746f72733a2f2f73686f702f235f7363786d6c5f380e14261008010c07001205c00c14050216011808071a0710636865636b6f75741c071065787465726e616c1e02200222022402260202050009060512072031633863613263633731333866313465050008070407023906070e6f726465722d390808030a08010c073674696e796163746f72733a2f2f73686f702f235f7363786d6c5f390e142c1008010c07001205880e14050216011808071a0710636865636b6f75741c071065787465726e616c1e022002220224022602020500090605140720316338636132636337313338663134650500080704070431300607106f726465722d31300808030a08010c073874696e796163746f72733a2f2f73686f702f235f7363786d6c5f31300e14321008010c07001205d00f14050216011808071a0710636865636b6f75741c071065787465726e616c1e022002220224022602020500090605160720316338636132636337313338663134650500080704070431310607106f726465722d31310808030a08010c073874696e796163746f72733a2f2f73686f702f235f7363786d6c5f31310e14381008010c07001205981114050016011808071a07146974656d2e61646465641c071065787465726e616c1e0220022202240226080228070670656e2a059811020500090605180720316338636132636337313338663134650500080704070431320607106f726465722d31320808030a08010c073874696e796163746f72733a2f2f73686f702f235f7363786d6c5f31320e143f1008010c07001205e01214050016011808071a07146974656d2e61646465641c071065787465726e616c1e0220022202240226080228070670656e2a05e0120205000906051a0720316338636132636337313338663134650500080704070431330607106f726465722d31330808030a08010c073874696e796163746f72733a2f2f73686f702f235f7363786d6c5f31330e14461008010c07001205a81414050016011808071a07146974656d2e61646465641c071065787465726e616c1e0220022202240226080228070670656e2a05a8140205000906051c0720316338636132636337313338663134650500080704070431340607106f726465722d31340808030a08010c073874696e796163746f72733a2f2f73686f702f235f7363786d6c5f31340e144d1008010c07001205f01514050016011808071a07146974656d2e61646465641c071065787465726e616c1e0220022202240226080228070670656e2a05f0150205000906051e0720316338636132636337313338663134650500080704070431350607106f726465722d31350808030a08010c073874696e796163746f72733a2f2f73686f702f235f7363786d6c5f31350e14541008010c07001205b81714050016011808071a07146974656d2e61646465641c071065787465726e616c1e0220022202240226080228070670656e2a05b817020500090605200720316338636132636337313338663134650500080704070431360607106f726465722d31360808030a08010c073874696e796163746f72733a2f2f73686f702f235f7363786d6c5f31360e145b1008010c07001205801914050016011808071a07146974656d2e61646465641c071065787465726e616c1e0220022202240226080228070670656e2a0580190205000906052807206662636536333939663963663562356205000807040714343239343936373239370607106f726465722d32310808030a08010c074874696e796163746f72733a2f2f73686f702f235f7363786d6c5f343239343936373239370e14621008010c070012050014050016012c010205022e09090903050e05021408090305100502140f0903051205021416090305160502143b09030518050214420903051a050214490903051c050214500903051e05021457090305200502145e300900320a09c15c0289ec2d0a9100',"wallNs":10000000000}`
```
Show what a snapshot holds.
```shell
tinyactors inspect order-17.blob shop.snapshot
```
```text title="output"
# Inspect
- **From**: hibernation blob
- **Bytes**: 290
- **Format**: 5
- **Readable**: yes
- **Session**: 17
- **Image hash**: 1c8ca2cc7138f14e
- **Image matches**: yes
- **Identity**: 000000007952af3e
- **Wakes**: only in the host that hibernated it, or a host restored from its snapshot: one of this identity, running this image
- **Wakes in that snapshot**: yes
## Sessions
### Session 1: order
- **Session**: 17
- **Chart index**: 0
- **Chart**: order
- **Macrosteps**: 2
#### Configuration
- open
#### Delayed
_none_
#### Datamodel
- **Bytes**: 166
- **Encoding**: opaque
- **Note**: not one CBOR item: the datamodel's own encoding (the ECMAScript datamodel's is quickjs's), which only that datamodel reads
```
Show a blob with its chart and configuration from a snapshot.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- [Offline snapshots](https://tinyactors.dev/cli/guides/snapshots/index.md)
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors actors`](https://tinyactors.dev/cli/commands/actors/index.md)**: List every actor of a snapshot with its state and queues.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors states
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> List each chart's states as a tree in document order.
List each chart's states as a tree in document order.
## Usage
```shell
tinyactors states [options] INPUT...
```
Lists each chart's states as a tree in document order: id, kind, parent, depth and initial targets. Counts each state's transitions, invokes and data. Reads one image (`.tai`), one snapshot, one system manifest or SCXML charts, compiled together into one image first. `--segment` picks a snapshot's image, and - reads standard input.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors states order.scxml
```
```text title="output"
# States
## Charts
### Chart 1: order
- **Name**: order
#### States
| Index | ID | Kind | Parent | Depth | Initial | Transitions | Invokes | Data | On entry | On exit | Done event |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | /scxml | compound | | 0 | open | 0 | 0 | 3 | no | no | |
| 1 | open | atomic | /scxml | 1 | | 3 | 0 | 0 | no | no | |
| 2 | paying | atomic | /scxml | 1 | | 3 | 0 | 0 | yes | yes | |
| 3 | paid | atomic | /scxml | 1 | | 1 | 0 | 0 | no | no | |
| 4 | shipped | final | /scxml | 1 | | 0 | 0 | 0 | no | no | |
| 5 | cancelled | final | /scxml | 1 | | 0 | 0 | 0 | no | no | |
```
List the states of a chart.
```shell
tinyactors states --chart payment system.tai
```
```text title="output"
# States
## Charts
### Chart 1: payment
- **Name**: payment
#### States
| Index | ID | Kind | Parent | Depth | Initial | Transitions | Invokes | Data | On entry | On exit | Done event |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | /scxml | compound | | 0 | pending | 0 | 0 | 1 | no | no | |
| 1 | pending | atomic | /scxml | 1 | | 2 | 0 | 0 | no | no | |
| 2 | authorized | atomic | /scxml | 1 | | 2 | 0 | 0 | no | no | |
| 3 | settled | final | /scxml | 1 | | 0 | 0 | 0 | no | no | |
| 4 | declined | final | /scxml | 1 | | 0 | 0 | 0 | no | no | |
```
List the states of one chart of an image.
```shell
tinyactors states --segment 1 shop.snapshot
```
```text title="output"
# States
## Charts
### Chart 1: order
- **Name**: order
#### States
| Index | ID | Kind | Parent | Depth | Initial | Transitions | Invokes | Data | On entry | On exit | Done event |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | /scxml | compound | | 0 | open | 0 | 0 | 4 | no | no | |
| 1 | open | atomic | /scxml | 1 | | 3 | 0 | 0 | no | no | |
| 2 | paying | atomic | /scxml | 1 | | 3 | 0 | 0 | yes | yes | |
| 3 | paid | atomic | /scxml | 1 | | 2 | 0 | 0 | no | no | |
| 4 | shipped | final | /scxml | 1 | | 0 | 0 | 0 | no | no | |
| 5 | refunded | final | /scxml | 1 | | 0 | 0 | 0 | no | no | |
| 6 | cancelled | final | /scxml | 1 | | 0 | 0 | 0 | no | no | |
```
List the states in the image of a snapshot's segment 1.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors transitions
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> List each chart's transitions with events, conditions and targets.
List each chart's transitions with events, conditions and targets.
## Usage
```shell
tinyactors transitions [options] INPUT...
```
Lists each chart's transitions: kind, source, events, condition, targets, type and whether each has actions. Reads one image (`.tai`), one snapshot, one system manifest or SCXML charts, compiled together into one image first. `--segment` picks a snapshot's image, and - reads standard input.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors transitions order.scxml
```
```text title="output"
# Transitions
## Charts
### Chart 1: order
- **Name**: order
#### Transitions
| Index | Kind | Source | Events | Condition | Targets | Type | Actions |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | transition | open | item.added | _event.data.price > 0 | | external | yes |
| 1 | transition | open | checkout | total > 0 | paying | external | no |
| 2 | transition | open | cancel | | cancelled | external | no |
| 3 | transition | paying | charge.ok | | paid | external | yes |
| 4 | transition | paying | charge.declined error.communication payment.timeout | `attempts < 3` | paying | external | no |
| 5 | transition | paying | charge.declined error.communication payment.timeout | | cancelled | external | no |
| 6 | transition | paid | shipped | | shipped | external | no |
| 7 | initial | /scxml | | | open | external | no |
```
List the transitions of a chart.
```shell
tinyactors transitions -f json order.tai
```
```text title="output"
{
"charts": [
{
"name": "order",
"transitions": [
{
"index": 0,
"kind": "transition",
"source": "open",
"events": "item.added",
"condition": "_event.data.price > 0",
"targets": "",
"type": "external",
"actions": true
},
{
"index": 1,
"kind": "transition",
"source": "open",
"events": "checkout",
"condition": "total > 0",
"targets": "paying",
"type": "external",
"actions": false
},
{
"index": 2,
"kind": "transition",
"source": "open",
"events": "cancel",
"condition": "",
"targets": "cancelled",
"type": "external",
"actions": false
},
{
"index": 3,
"kind": "transition",
"source": "paying",
"events": "charge.ok",
"condition": "",
"targets": "paid",
"type": "external",
"actions": true
},
{
"index": 4,
"kind": "transition",
"source": "paying",
"events": "charge.declined error.communication payment.timeout",
"condition": "attempts < 3",
"targets": "paying",
"type": "external",
"actions": false
},
{
"index": 5,
"kind": "transition",
"source": "paying",
"events": "charge.declined error.communication payment.timeout",
"condition": "",
"targets": "cancelled",
"type": "external",
"actions": false
},
{
"index": 6,
"kind": "transition",
"source": "paid",
"events": "shipped",
"condition": "",
"targets": "shipped",
"type": "external",
"actions": false
},
{
"index": 7,
"kind": "initial",
"source": "/scxml",
"events": "",
"condition": "",
"targets": "open",
"type": "external",
"actions": false
}
]
},
{
"name": "payment",
"transitions": [
{
"index": 0,
"kind": "transition",
"source": "pending",
"events": "authorize",
"condition": "",
"targets": "authorized",
"type": "external",
"actions": false
},
{
"index": 1,
"kind": "transition",
"source": "pending",
"events": "decline",
"condition": "",
"targets": "declined",
"type": "external",
"actions": false
},
{
"index": 2,
"kind": "transition",
"source": "authorized",
"events": "capture",
"condition": "",
"targets": "settled",
"type": "external",
"actions": false
},
{
"index": 3,
"kind": "transition",
"source": "authorized",
"events": "void",
"condition": "",
"targets": "declined",
"type": "external",
"actions": false
},
{
"index": 4,
"kind": "initial",
"source": "/scxml",
"events": "",
"condition": "",
"targets": "pending",
"type": "external",
"actions": false
}
]
}
]
}
```
List the transitions of an image as JSON.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors events
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> List every event name and the transitions, raises and sends using it.
List every event name and the transitions, raises and sends using it.
## Usage
```shell
tinyactors events [options] INPUT...
```
Lists every event name the charts use. Counts the transitions that handle each one and the raises and sends that make it by name. Reads one image (`.tai`), one snapshot, one system manifest or SCXML charts, compiled together into one image first. `--segment` picks a snapshot's image, and - reads standard input.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors events system.xml
```
```text title="output"
# Events
## Events
| Name | Transitions | Raises | Sends |
| --- | --- | --- | --- |
| authorize | 1 | 0 | 0 |
| cancel | 1 | 0 | 0 |
| capture | 1 | 0 | 0 |
| charge | 0 | 0 | 1 |
| charge.declined | 2 | 0 | 0 |
| charge.ok | 1 | 0 | 0 |
| checkout | 1 | 0 | 0 |
| decline | 1 | 0 | 0 |
| error.communication | 2 | 0 | 0 |
| item.added | 1 | 0 | 0 |
| payment.timeout | 2 | 0 | 1 |
| shipped | 1 | 0 | 0 |
| void | 1 | 0 | 0 |
```
List the events of a system manifest's charts.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors data
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> List each chart's data declarations.
List each chart's data declarations.
## Usage
```shell
tinyactors data [options] INPUT...
```
Lists each chart's data declarations: id, the state declaring it, its expression and its line. Reads one image (`.tai`), one snapshot, one system manifest or SCXML charts, compiled together into one image first. `--segment` picks a snapshot's image, and - reads standard input.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors data order.scxml
```
```text title="output"
# Data
## Charts
### Chart 1: order
- **Name**: order
#### Data
| ID | State | Expression | Line |
| --- | --- | --- | --- |
| total | /scxml | 0 | 3 |
| attempts | /scxml | 0 | 4 |
| charge | /scxml | null | 5 |
```
List the data declarations of a chart.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors expressions
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> List each chart's expressions and scripts with where they are.
List each chart's expressions and scripts with where they are.
## Usage
```shell
tinyactors expressions [options] INPUT...
```
Lists each chart's expressions and scripts: kind, line, column and text. Reads one image (`.tai`), one snapshot, one system manifest or SCXML charts, compiled together into one image first. `--segment` picks a snapshot's image, and - reads standard input.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
- **`-k, --kind KIND`**: Keep only the expressions of `KIND`. Repeatable. Values: `condition`, `value`, `location`, `script`, `string`, `content`, `item`, `global-script`.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors expressions --kind condition order.scxml
```
```text title="output"
# Expressions
## Charts
### Chart 1: order
- **Name**: order
#### Expressions
| Index | Kind | Line | Column | Source |
| --- | --- | --- | --- | --- |
| 3 | condition | 8 | 5 | _event.data.price > 0 |
| 6 | condition | 11 | 5 | total > 0 |
| 9 | condition | 28 | 5 | `attempts < 3` |
```
List the conditions of a chart.
```shell
tinyactors expressions -f xml order.tai
```
```text title="output"
```
List the expressions of an image as XML.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors disassemble
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> List each chart's executable content instruction by instruction.
List each chart's executable content instruction by instruction.
## Usage
```shell
tinyactors disassemble [options] INPUT...
```
Lists each chart's executable content as instructions: their place, the entry points starting there and their operands. Reads one image (`.tai`), one snapshot, one system manifest or SCXML charts, compiled together into one image first. `--segment` picks a snapshot's image, and - reads standard input.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors disassemble --chart order order.tai
```
```text title="output"
# Disassemble
## Charts
### Chart 1: order
- **Name**: order
#### Instructions
| Pc | Label | Opcode | Operands |
| --- | --- | --- | --- |
| 0 | transition 0: open on item.added | block | to 5 |
| 2 | | assign | `total` = `total + _event.data.price` |
| 5 | | end | |
| 6 | transition 3: paying on charge.ok | block | to 11 |
| 8 | | assign | `charge` = `_event.data.charge` |
| 11 | | end | |
| 12 | onentry paying | block | to 21 |
| 14 | | assign | `attempts` = `attempts + 1` |
| 17 | | send | event charge to charges type payments |
| 19 | | send | event payment.timeout to itself after 30s |
| 21 | | end | |
| 22 | onexit paying | block | to 26 |
| 24 | | cancel | sendid deadline |
| 26 | | end | |
```
Disassemble one chart of an image.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors graph
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Draw each chart, or list its boxes and edges.
Draw each chart, or list its boxes and edges.
## Usage
```shell
tinyactors graph [options] INPUT...
```
Lays each chart out as nested boxes for its states and orthogonal routes for its transitions. With `-f` svg it writes the picture; the other formats list each box and edge. Reads one image (`.tai`), one snapshot, one system manifest or SCXML charts, compiled together into one image first. `--segment` picks a snapshot's image, and - reads standard input.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
- **`--direction DIRECTION`**: Lay the states out in `DIR`ECTION. Values: down (top to bottom) or right (left to right). Default: down.
- **`--theme THEME`**: Draw the colours of `THEME` with `-f` svg. Values: auto (the reader's preference), light or dark. Default: auto.
- **`--highlight STATE`**: Mark the box of `STATE`. Repeatable.
- **`--path`**: Mark the path the path command finds to `--to` from `--from`, its steps numbered.
- **`-t, --to STATE`**: End the path of `--path` at `STATE`.
- **`--from STATE`**: Start the path of `--path` at `STATE`. Default: the initial configuration.
- **`-d, --depth N`**: Fold every compound or parallel state nested deeper than N levels into one box.
- **`--fold STATE`**: Fold the compound or parallel state `STATE` into one box. Repeatable.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors graph -f svg order.scxml > order.svg
```
Draw a chart as SVG.

```shell
tinyactors graph -f svg --chart payment shop.tai > payment.svg
```
Draw one chart of an image.

```shell
tinyactors graph -f svg --direction right --theme dark order.scxml > order.svg
```
Draw a chart left to right in dark colours.

```shell
tinyactors graph -f svg --path --to shipped --highlight cancelled order.scxml > shipping.svg
```
Mark the path to shipped and highlight cancelled.

```shell
tinyactors graph -f svg --depth 1 --fold checkout shop.scxml > overview.svg
```
Fold states nested deeper than one level, and checkout.

```shell
tinyactors graph -f json order.tai
```
```text title="output"
{
"charts": [
{
"name": "order",
"width": 821,
"height": 432,
"boxes": [
{
"state": "/scxml",
"kind": "compound",
"parent": "",
"drawnAs": "root",
"x": 0,
"y": 0,
"width": 821,
"height": 432
},
{
"state": "open",
"kind": "atomic",
"parent": "/scxml",
"drawnAs": "atomic",
"x": 508,
"y": 40,
"width": 276,
"height": 58
},
{
"state": "paying",
"kind": "atomic",
"parent": "/scxml",
"drawnAs": "atomic",
"x": 278,
"y": 160,
"width": 480,
"height": 34
},
{
"state": "paid",
"kind": "atomic",
"parent": "/scxml",
"drawnAs": "atomic",
"x": 413,
"y": 298,
"width": 78,
"height": 34
},
{
"state": "shipped",
"kind": "final",
"parent": "/scxml",
"drawnAs": "final",
"x": 414,
"y": 384,
"width": 77,
"height": 34
},
{
"state": "cancelled",
"kind": "final",
"parent": "/scxml",
"drawnAs": "final",
"x": 592,
"y": 298,
"width": 92,
"height": 34
}
],
"edges": [
{
"source": "open",
"target": "paying",
"events": "checkout",
"condition": "total > 0",
"drawnAs": "forward",
"route": "518,98 518,160"
},
{
"source": "open",
"target": "cancelled",
"events": "cancel",
"condition": "",
"drawnAs": "forward",
"route": "726,98 726,150 781,150 781,288 667,288 667,298"
},
{
"source": "paying",
"target": "paid",
"events": "charge.ok",
"condition": "",
"drawnAs": "forward",
"route": "398,194 398,278 452,278 452,298"
},
{
"source": "paying",
"target": "paying",
"events": "charge.declined error.communication payment.timeout",
"condition": "attempts < 3",
"drawnAs": "self",
"route": "463,194 463,210 573,210 573,194"
},
{
"source": "paying",
"target": "cancelled",
"events": "charge.declined error.communication payment.timeout",
"condition": "",
"drawnAs": "forward",
"route": "638,194 638,298"
},
{
"source": "paid",
"target": "shipped",
"events": "shipped",
"condition": "",
"drawnAs": "forward",
"route": "452,332 452,384"
}
],
"inside": [
{
"state": "open",
"events": "item.added",
"condition": "_event.data.price > 0",
"targets": ""
}
],
"problems": [
{
"kind": "labelOnEdge",
"subject": "paying → paying on charge.declined error.communication payment.timeout",
"touches": "paying → paid on charge.ok"
},
{
"kind": "labelOnEdge",
"subject": "paying → cancelled on charge.declined error.communication payment.timeout",
"touches": "open → cancelled on cancel"
}
]
},
{
"name": "payment",
"width": 242,
"height": 290,
"boxes": [
{
"state": "/scxml",
"kind": "compound",
"parent": "",
"drawnAs": "root",
"x": 0,
"y": 0,
"width": 242,
"height": 290
},
{
"state": "pending",
"kind": "atomic",
"parent": "/scxml",
"drawnAs": "atomic",
"x": 64,
"y": 40,
"width": 164,
"height": 34
},
{
"state": "authorized",
"kind": "atomic",
"parent": "/scxml",
"drawnAs": "atomic",
"x": 37,
"y": 136,
"width": 130,
"height": 34
},
{
"state": "settled",
"kind": "final",
"parent": "/scxml",
"drawnAs": "final",
"x": 14,
"y": 242,
"width": 77,
"height": 34
},
{
"state": "declined",
"kind": "final",
"parent": "/scxml",
"drawnAs": "final",
"x": 109,
"y": 242,
"width": 85,
"height": 34
}
],
"edges": [
{
"source": "pending",
"target": "authorized",
"events": "authorize",
"condition": "",
"drawnAs": "forward",
"route": "102,74 102,136"
},
{
"source": "pending",
"target": "declined",
"events": "decline",
"condition": "",
"drawnAs": "forward",
"route": "189,74 189,126 190,126 190,232 177,232 177,242"
},
{
"source": "authorized",
"target": "settled",
"events": "capture",
"condition": "",
"drawnAs": "forward",
"route": "53,170 53,242"
},
{
"source": "authorized",
"target": "declined",
"events": "void",
"condition": "",
"drawnAs": "forward",
"route": "138,170 138,242"
}
],
"inside": [],
"problems": []
}
]
}
```
List the boxes and edges of an image's charts as JSON.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`1`**: With `--path`, no path reaches the `--to` state in any chart drawn.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors path`](https://tinyactors.dev/cli/commands/path/index.md)**: Find the shortest path to a state: events, conditions and transitions.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors diff
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Compare two versions and show what changes for running actors.
Compare two versions and show what changes for running actors.
## Usage
```shell
tinyactors diff [options] OLD NEW
```
Compares two images chart by chart, matching charts by name. Each version is an image, a system manifest or one chart. Compares data by id, states by id and transitions by source and events. Compares invokes, executable content as decoded instructions and the events each state handles. Marks each change as breaking for actors running the old version, or as a change of behaviour. A state removed, moved or of another kind is breaking. So are data removed, another datamodel and an event a state no longer handles. The answer says what a migration does to running actors.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
- **`--exit-code`**: Exit with 1 when the two differ, as git diff `--exit-code` does; with `--breaking`, when a change breaks running actors.
- **`--breaking`**: List only the changes that break actors running the old version.
- **`--all`**: List the charts that did not change too.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors diff order-v1.tai order-v2.scxml
```
```text title="output"
# Diff
## Old
- **Path**: order-v1.tai
- **Hash**: 7264231f9a5f18b3
- **Charts**: 1
## New
- **Path**: order-v2.scxml
- **Hash**: fbce6399f9cf5b5b
- **Charts**: 1
- **Identical**: no
## Summary
- **Charts added**: 0
- **Charts removed**: 0
- **Charts changed**: 1
- **Charts unchanged**: 0
- **Differences**: 17
- **Breaking**: 0
## Charts
### Chart 1: order
- **Name**: order
- **Change**: changed
- **Datamodel**: ecmascript
- **Binding**: early
#### States
| State | Change | Breaking | Before | After |
| --- | --- | --- | --- | --- |
| paying | onentry changed, onexit changed | no | atomic in /scxml | atomic in /scxml |
| refunded | added | no | | final in /scxml |
| cancelled | added | no | | final in /scxml |
#### Transitions
| Source | Events | Change | Breaking | Before | After |
| --- | --- | --- | --- | --- | --- |
| open | checkout | condition changed | no | → paying (external) | cond `total > 0` → paying (external) |
| paying | charge.declined | removed | no | → open (external) | |
| open | cancel | added | no | | → cancelled (external) |
| paying | charge.declined error.communication payment.timeout | added | no | | cond `attempts < 3` → paying (external) |
| paying | charge.declined error.communication payment.timeout | added | no | | → cancelled (external) |
| paid | refund | added | no | | → refunded (external) |
#### Data
| ID | Change | Breaking | Before | After |
| --- | --- | --- | --- | --- |
| attempts | added | no | | `0` in /scxml |
| refund | added | no | | `null` in /scxml |
#### Actions
| Where | Change | Before | After |
| --- | --- | --- | --- |
| onentry paying | changed | send event charge to charges type payments id pay with amount=`total` | assign `attempts` = `attempts + 1`; send event charge to charges type payments id pay with amount=`total`; send event payment.timeout to itself id deadline after 30s |
| onexit paying | added | | cancel deadline |
#### Invokes
_none_
#### Events
| State | Event | Change |
| --- | --- | --- |
| open | cancel | newly handled |
| paying | error.communication | newly handled |
| paying | payment.timeout | newly handled |
| paid | refund | newly handled |
## Events added
- cancel
- error.communication
- payment.timeout
- refund
## Events removed
_none_
```
Compare an image with a newer version of its chart.
```shell
tinyactors diff --breaking --exit-code deployed.tai order.scxml
```
```text title="output"
# Diff
## Old
- **Path**: deployed.tai
- **Hash**: 7264231f9a5f18b3
- **Charts**: 1
## New
- **Path**: order.scxml
- **Hash**: 5e66ab57693504aa
- **Charts**: 1
- **Identical**: no
## Summary
- **Charts added**: 0
- **Charts removed**: 0
- **Charts changed**: 1
- **Charts unchanged**: 0
- **Differences**: 13
- **Breaking**: 0
## Charts
_none_
## Events added
- cancel
- error.communication
- payment.timeout
## Events removed
_none_
```
Fail if a change breaks running actors.
```shell
tinyactors diff -f json --chart order old.tai new.tai
```
```text title="output"
{
"old": {
"path": "old.tai",
"hash": "7264231f9a5f18b3",
"charts": 1
},
"new": {
"path": "new.tai",
"hash": "5e66ab57693504aa",
"charts": 1
},
"identical": false,
"summary": {
"chartsAdded": 0,
"chartsRemoved": 0,
"chartsChanged": 1,
"chartsUnchanged": 0,
"differences": 13,
"breaking": 0
},
"charts": [
{
"name": "order",
"change": "changed",
"datamodel": "ecmascript",
"binding": "early",
"states": [
{
"state": "paying",
"change": "onentry changed, onexit changed",
"breaking": false,
"before": "atomic in /scxml",
"after": "atomic in /scxml"
},
{
"state": "cancelled",
"change": "added",
"breaking": false,
"before": "",
"after": "final in /scxml"
}
],
"transitions": [
{
"source": "open",
"events": "checkout",
"change": "condition changed",
"breaking": false,
"before": "→ paying (external)",
"after": "cond `total > 0` → paying (external)"
},
{
"source": "paying",
"events": "charge.declined",
"change": "removed",
"breaking": false,
"before": "→ open (external)",
"after": ""
},
{
"source": "open",
"events": "cancel",
"change": "added",
"breaking": false,
"before": "",
"after": "→ cancelled (external)"
},
{
"source": "paying",
"events": "charge.declined error.communication payment.timeout",
"change": "added",
"breaking": false,
"before": "",
"after": "cond `attempts < 3` → paying (external)"
},
{
"source": "paying",
"events": "charge.declined error.communication payment.timeout",
"change": "added",
"breaking": false,
"before": "",
"after": "→ cancelled (external)"
}
],
"data": [
{
"id": "attempts",
"change": "added",
"breaking": false,
"before": "",
"after": "`0` in /scxml"
}
],
"actions": [
{
"where": "onentry paying",
"change": "changed",
"before": "send event charge to charges type payments id pay with amount=`total`",
"after": "assign `attempts` = `attempts + 1`; send event charge to charges type payments id pay with amount=`total`; send event payment.timeout to itself id deadline after 30s"
},
{
"where": "onexit paying",
"change": "added",
"before": "",
"after": "cancel deadline"
}
],
"invokes": [],
"events": [
{
"state": "open",
"event": "cancel",
"change": "newly handled"
},
{
"state": "paying",
"event": "error.communication",
"change": "newly handled"
},
{
"state": "paying",
"event": "payment.timeout",
"change": "newly handled"
}
]
}
],
"eventsAdded": [
"cancel",
"error.communication",
"payment.timeout"
],
"eventsRemoved": []
}
```
Compare one chart of two images as JSON.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`1`**: With `--exit-code`, the two versions differ; with `--breaking` too, a change breaks running actors.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- [CI checks](https://tinyactors.dev/cli/guides/ci/index.md)
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors lint
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Find what cannot work as written in charts.
Find what cannot work as written in charts.
## Usage
```shell
tinyactors lint [options] INPUT...
```
Reads the charts' states, transitions, raises and sends without running them. Reports what cannot do what it is written for, by rule. unreachable: a state no path enters. dead-end: a state an actor never leaves. never-ends: a state from which no final state is reachable. shadowed: a transition an earlier one always takes first. eventless-loop: an eventless transition taken without end. unhandled-event: raised or sent to a chart of the image that handles it nowhere. unsent-event: with several charts, handled but sent by nothing in the image. unknown-events: a computed event may arrive, so unsent-event is not checked. send-target: a static target no send can reach. search-limit: the search stopped at its limit, so never-ends is not checked.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
- **`-d, --deny RULE`**: Exit with 1 when `RULE` finds something; all names every rule. Repeatable.
- **`-a, --allow RULE`**: Leave out the findings of `RULE`; all leaves out every rule's. Repeatable.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors lint order.scxml
```
```text title="output"
# Lint
- **Warnings**: 0
- **Notes**: 0
- **Denied**: 0
## Findings
_none_
```
Lint a chart.
```shell
tinyactors lint --deny all --allow unsent-event system.xml
```
```text title="output"
# Lint
- **Warnings**: 0
- **Notes**: 0
- **Denied**: 0
## Findings
_none_
```
Fail on a finding of every rule but unsent-event.
```shell
tinyactors lint -f json --chart payment shop.tai
```
```text title="output"
{
"warnings": 0,
"notes": 4,
"denied": 0,
"findings": [
{
"rule": "unsent-event",
"severity": "note",
"chart": "payment",
"state": "pending",
"transition": "authorize → authorized",
"event": "authorize",
"line": 0,
"message": "nothing in the image raises or sends it to payment: only the application can"
},
{
"rule": "unsent-event",
"severity": "note",
"chart": "payment",
"state": "pending",
"transition": "decline → declined",
"event": "decline",
"line": 0,
"message": "nothing in the image raises or sends it to payment: only the application can"
},
{
"rule": "unsent-event",
"severity": "note",
"chart": "payment",
"state": "authorized",
"transition": "capture → settled",
"event": "capture",
"line": 0,
"message": "nothing in the image raises or sends it to payment: only the application can"
},
{
"rule": "unsent-event",
"severity": "note",
"chart": "payment",
"state": "authorized",
"transition": "void → declined",
"event": "void",
"line": 0,
"message": "nothing in the image raises or sends it to payment: only the application can"
}
]
}
```
Lint one chart of an image as JSON.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`1`**: A rule given to `--deny` finds something.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- [CI checks](https://tinyactors.dev/cli/guides/ci/index.md)
- **[`tinyactors compile`](https://tinyactors.dev/cli/commands/compile/index.md)**: Compile charts or a system manifest into an image.
- **[`tinyactors check`](https://tinyactors.dev/cli/commands/check/index.md)**: Check that charts compile or that an image verifies.
- **[`tinyactors fmt`](https://tinyactors.dev/cli/commands/fmt/index.md)**: Rewrite charts and system manifests in the canonical layout.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors path
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Find the shortest path to a state: events, conditions and transitions.
Find the shortest path to a state: events, conditions and transitions.
## Usage
```shell
tinyactors path [options] INPUT...
```
Searches a chart's configurations breadth first for one holding the `--to` state. It starts from the initial configuration, or from the `--from` state. Any transition whose source is active may be taken: events come in any order and conditions may hold. So each step lists the events that take it and the condition it needs. The chart is the first one, or the one `--chart` names.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: Read the image that segment N of a snapshot runs. Default: the newest live segment.
- **`-t, --to STATE`**: Search for a configuration that holds `STATE`.
- **`--from STATE`**: Start in `STATE`, entered with its defaults. Default: the initial configuration.
- **`-u, --unreachable`**: Succeed only when no path exists, and exit with 1 otherwise.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors path order.scxml --to shipped
```
```text title="output"
# Path
- **Chart**: order
- **From**:
- **To**: shipped
- **Result**: found
- **Meaning**: the steps below reach it, if their events come and their conditions hold
- **Transitions**: 3
- **Explored**: 5
- **Start**: open
## Steps
| Step | Events | Eventless | Condition | Source | Targets | Active |
| --- | --- | --- | --- | --- | --- | --- |
| 1 | checkout | no | total > 0 | open | paying | paying |
| 2 | charge.ok | no | | paying | paid | paid |
| 3 | shipped | no | | paid | shipped | shipped |
```
Find the shortest path to shipped.
```shell
tinyactors path order.scxml --from cancelled --to paid --unreachable
```
```text title="output"
# Path
- **Chart**: order
- **From**: cancelled
- **To**: paid
- **Result**: unreachable
- **Meaning**: no sequence of transitions reaches it, whatever events come and conditions hold
- **Transitions**: 0
- **Explored**: 1
- **Start**: cancelled
## Steps
_none_
```
Fail if paid can be reached from cancelled.
```shell
tinyactors path -f json --chart payment shop.tai --to settled
```
```text title="output"
{
"chart": "payment",
"from": "",
"to": "settled",
"result": "found",
"meaning": "the steps below reach it, if their events come and their conditions hold",
"transitions": 2,
"explored": 4,
"start": "pending",
"steps": [
{
"step": 1,
"events": "authorize",
"eventless": false,
"condition": "",
"source": "pending",
"targets": "authorized",
"active": "authorized"
},
{
"step": 2,
"events": "capture",
"eventless": false,
"condition": "",
"source": "authorized",
"targets": "settled",
"active": "settled"
}
]
}
```
Find a path in one chart of an image as JSON.
## Exit status
- **`1`**: An input is refused: it does not compile or verify, or it is damaged or of an unknown format.
- **`1`**: Without `--unreachable`, no path exists or the search stops at its limit.
- **`1`**: With `--unreachable`, a path exists, or the search stops at its limit.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- **[`tinyactors states`](https://tinyactors.dev/cli/commands/states/index.md)**: List each chart's states as a tree in document order.
- **[`tinyactors transitions`](https://tinyactors.dev/cli/commands/transitions/index.md)**: List each chart's transitions with events, conditions and targets.
- **[`tinyactors events`](https://tinyactors.dev/cli/commands/events/index.md)**: List every event name and the transitions, raises and sends using it.
- **[`tinyactors data`](https://tinyactors.dev/cli/commands/data/index.md)**: List each chart's data declarations.
- **[`tinyactors expressions`](https://tinyactors.dev/cli/commands/expressions/index.md)**: List each chart's expressions and scripts with where they are.
- **[`tinyactors graph`](https://tinyactors.dev/cli/commands/graph/index.md)**: Draw each chart, or list its boxes and edges.
- **[`tinyactors disassemble`](https://tinyactors.dev/cli/commands/disassemble/index.md)**: List each chart's executable content instruction by instruction.
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors fmt
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Rewrite charts and system manifests in the canonical layout.
Rewrite charts and system manifests in the canonical layout.
## Usage
```shell
tinyactors fmt [options] FILE...
```
Writes each chart or system manifest in one canonical layout. It indents two spaces per element level and writes one element, comment or processing instruction per line. Attributes stay in the order written. Only the whitespace between elements changes: comments stay where they are and attribute values as written. Script, data, content and assign elements keep their content byte for byte. So do elements of other namespaces and mixed content. Each file's canonical text must compile to the image its original gives, lines and columns aside, or the file is refused. One file goes to standard output. `-w` rewrites the files in place, each whole or not at all. `--check` writes nothing. With `-w` or `--check` the answer lists the files and whether each changed.
## Options
- **`-w, --write`**: Rewrite each file in place, whole or not at all.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`--check`**: Write nothing, and exit with 1 when a file is not in canonical form.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors fmt order.scxml
```
```text title="output"
```
Write a chart's canonical text to standard output.
```shell
tinyactors fmt -w charts/*.scxml system.xml
```
```text title="output"
# Fmt
- **Mode**: write
- **Files**: 3
- **Changed**: 0
- **Refused**: 0
## Results
| File | Changed | Refused | Image |
| --- | --- | --- | --- |
| charts/order.scxml | no | no | same |
| charts/payment.scxml | no | no | same |
| system.xml | no | no | same |
## Diagnostics
_none_
```
Rewrite charts and a system manifest in place.
```shell
tinyactors fmt --check charts/*.scxml
```
```text title="output"
# Fmt
- **Mode**: check
- **Files**: 2
- **Changed**: 0
- **Refused**: 0
## Results
| File | Changed | Refused | Image |
| --- | --- | --- | --- |
| charts/order.scxml | no | no | same |
| charts/payment.scxml | no | no | same |
## Diagnostics
_none_
```
Fail if a chart is not in canonical form.
```shell
tinyactors fmt --check -f json -I shared order.scxml
```
```text title="output"
{
"mode": "check",
"files": 1,
"changed": 0,
"refused": 0,
"results": [
{
"file": "order.scxml",
"changed": false,
"refused": false,
"image": "same"
}
],
"diagnostics": []
}
```
Check a chart that includes files from shared, in JSON.
## Exit status
- **`1`**: A file is refused: it is no XML fmt can rewrite, or its canonical text gives another image.
- **`1`**: With `--check`, a file is not in canonical form.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- [CI checks](https://tinyactors.dev/cli/guides/ci/index.md)
- **[`tinyactors compile`](https://tinyactors.dev/cli/commands/compile/index.md)**: Compile charts or a system manifest into an image.
- **[`tinyactors check`](https://tinyactors.dev/cli/commands/check/index.md)**: Check that charts compile or that an image verifies.
- **[`tinyactors lint`](https://tinyactors.dev/cli/commands/lint/index.md)**: Find what cannot work as written in charts.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors actors
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> List every actor of a snapshot with its state and queues.
List every actor of a snapshot with its state and queues.
## Usage
```shell
tinyactors actors [options] SNAPSHOT
```
Restores the snapshot in memory, without its datamodels, and runs nothing. Lists each actor of each live segment: its session, name, chart, segment and state. Lists its parent, its running invocations and its configuration, the active states in document order. A hibernated actor's configuration is in its blob. Lists the events queued in its mailbox and its pending delayed sends with when they are due. `--chart`, `--segment` and `--session` narrow the list.
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`-c, --chart NAME`**: Look at the chart named `NAME` only. Repeatable.
- **`-s, --segment N`**: List the actors of segment N only. Default: every live segment.
- **`--session ID`**: Look at session ID only. Repeatable.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors actors shop.snapshot
```
```text title="output"
# Actors
- **Snapshot**: shop.snapshot
- **System ID**: shop
- **Time**: 10000
## Actors
### Actor 1: order-3
- **Session**: 3
- **Name**: order-3
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paid
#### Mailbox
_none_
#### Delayed
_none_
### Actor 2: order-4
- **Session**: 4
- **Name**: order-4
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paid
#### Mailbox
_none_
#### Delayed
_none_
### Actor 3: order-5
- **Session**: 5
- **Name**: order-5
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paid
#### Mailbox
_none_
#### Delayed
_none_
### Actor 4: order-6
- **Session**: 6
- **Name**: order-6
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paying
#### Mailbox
_none_
#### Delayed
| Event | Sendid | Due | In |
| --- | --- | --- | --- |
| payment.timeout | deadline | 30000 | 20s |
### Actor 5: order-7
- **Session**: 7
- **Name**: order-7
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paying
#### Mailbox
_none_
#### Delayed
| Event | Sendid | Due | In |
| --- | --- | --- | --- |
| payment.timeout | deadline | 30000 | 20s |
### Actor 6: order-8
- **Session**: 8
- **Name**: order-8
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paying
#### Mailbox
_none_
#### Delayed
| Event | Sendid | Due | In |
| --- | --- | --- | --- |
| payment.timeout | deadline | 30000 | 20s |
### Actor 7: order-9
- **Session**: 9
- **Name**: order-9
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paying
#### Mailbox
_none_
#### Delayed
| Event | Sendid | Due | In |
| --- | --- | --- | --- |
| payment.timeout | deadline | 30000 | 20s |
### Actor 8: order-10
- **Session**: 10
- **Name**: order-10
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- paying
#### Mailbox
_none_
#### Delayed
| Event | Sendid | Due | In |
| --- | --- | --- | --- |
| payment.timeout | deadline | 30000 | 20s |
### Actor 9: order-11
- **Session**: 11
- **Name**: order-11
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- open
#### Mailbox
_none_
#### Delayed
_none_
### Actor 10: order-12
- **Session**: 12
- **Name**: order-12
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- open
#### Mailbox
_none_
#### Delayed
_none_
### Actor 11: order-13
- **Session**: 13
- **Name**: order-13
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- open
#### Mailbox
_none_
#### Delayed
_none_
### Actor 12: order-14
- **Session**: 14
- **Name**: order-14
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- open
#### Mailbox
_none_
#### Delayed
_none_
### Actor 13: order-15
- **Session**: 15
- **Name**: order-15
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- open
#### Mailbox
_none_
#### Delayed
_none_
### Actor 14: order-16
- **Session**: 16
- **Name**: order-16
- **Chart**: order
- **Segment**: 0
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- open
#### Mailbox
_none_
#### Delayed
_none_
### Actor 15: order-17
- **Session**: 17
- **Name**: order-17
- **Chart**: order
- **Segment**: 0
- **State**: hibernated
- **Invocations**: 0
- **Queued**: 0
- **Note**: hibernated: its configuration and datamodel are in its blob, in the host's store (tinyactors inspect BLOB SNAPSHOT reads it)
#### Configuration
_none_
#### Mailbox
_none_
#### Delayed
_none_
### Actor 16: order-21
- **Session**: 4294967297
- **Name**: order-21
- **Chart**: order
- **Segment**: 1
- **State**: idle
- **Invocations**: 0
- **Queued**: 0
#### Configuration
- open
#### Mailbox
_none_
#### Delayed
_none_
```
List every actor of a snapshot.
```shell
tinyactors actors --chart order --session 17 shop.snapshot
```
```text title="output"
# Actors
- **Snapshot**: shop.snapshot
- **System ID**: shop
- **Time**: 10000
## Actors
### Actor 1: order-17
- **Session**: 17
- **Name**: order-17
- **Chart**: order
- **Segment**: 0
- **State**: hibernated
- **Invocations**: 0
- **Queued**: 0
- **Note**: hibernated: its configuration and datamodel are in its blob, in the host's store (tinyactors inspect BLOB SNAPSHOT reads it)
#### Configuration
_none_
#### Mailbox
_none_
#### Delayed
_none_
```
Show session 17 if it runs the order chart.
```shell
tinyactors actors -f json shop.snapshot
```
```text title="output"
{
"snapshot": "shop.snapshot",
"systemID": "shop",
"time": 10000,
"actors": [
{
"session": 3,
"name": "order-3",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paid"
],
"mailbox": [],
"delayed": []
},
{
"session": 4,
"name": "order-4",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paid"
],
"mailbox": [],
"delayed": []
},
{
"session": 5,
"name": "order-5",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paid"
],
"mailbox": [],
"delayed": []
},
{
"session": 6,
"name": "order-6",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paying"
],
"mailbox": [],
"delayed": [
{
"event": "payment.timeout",
"sendid": "deadline",
"due": 30000,
"in": "20s"
}
]
},
{
"session": 7,
"name": "order-7",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paying"
],
"mailbox": [],
"delayed": [
{
"event": "payment.timeout",
"sendid": "deadline",
"due": 30000,
"in": "20s"
}
]
},
{
"session": 8,
"name": "order-8",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paying"
],
"mailbox": [],
"delayed": [
{
"event": "payment.timeout",
"sendid": "deadline",
"due": 30000,
"in": "20s"
}
]
},
{
"session": 9,
"name": "order-9",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paying"
],
"mailbox": [],
"delayed": [
{
"event": "payment.timeout",
"sendid": "deadline",
"due": 30000,
"in": "20s"
}
]
},
{
"session": 10,
"name": "order-10",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"paying"
],
"mailbox": [],
"delayed": [
{
"event": "payment.timeout",
"sendid": "deadline",
"due": 30000,
"in": "20s"
}
]
},
{
"session": 11,
"name": "order-11",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"open"
],
"mailbox": [],
"delayed": []
},
{
"session": 12,
"name": "order-12",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"open"
],
"mailbox": [],
"delayed": []
},
{
"session": 13,
"name": "order-13",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"open"
],
"mailbox": [],
"delayed": []
},
{
"session": 14,
"name": "order-14",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"open"
],
"mailbox": [],
"delayed": []
},
{
"session": 15,
"name": "order-15",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"open"
],
"mailbox": [],
"delayed": []
},
{
"session": 16,
"name": "order-16",
"chart": "order",
"segment": 0,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"open"
],
"mailbox": [],
"delayed": []
},
{
"session": 17,
"name": "order-17",
"chart": "order",
"segment": 0,
"state": "hibernated",
"invocations": 0,
"queued": 0,
"note": "hibernated: its configuration and datamodel are in its blob, in the host's store (tinyactors inspect BLOB SNAPSHOT reads it)",
"configuration": [],
"mailbox": [],
"delayed": []
},
{
"session": 4294967297,
"name": "order-21",
"chart": "order",
"segment": 1,
"state": "idle",
"invocations": 0,
"queued": 0,
"configuration": [
"open"
],
"mailbox": [],
"delayed": []
}
]
}
```
List every actor of a snapshot as JSON.
## Exit status
- **`1`**: The snapshot cannot be restored: it is damaged or of another format.
- **`3`**: A file cannot be read or written, or memory runs out.
## Related pages
- [Offline snapshots](https://tinyactors.dev/cli/guides/snapshots/index.md)
- **[`tinyactors inspect`](https://tinyactors.dev/cli/commands/inspect/index.md)**: Show what an image, a snapshot or a blob holds.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors run
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Serve one host over JSON-RPC 2.0 on standard input and output.
Serve one host over JSON-RPC 2.0 on standard input and output.
## Usage
```shell
tinyactors run [options] [INPUT...]
```
Experimental: the protocol may change in any release until a second client uses it. Makes one host with quickjs and adds the inputs' image: charts, a system manifest or an image. Without inputs, the client adds images. Reads JSON-RPC 2.0 messages, one per line, from standard input and answers on standard output. run.* methods are the host's calls (run.spawn, run.send, run.advanceTime, run.turn, run.addImage, ...). Every other method is core's control plane (actor.state, host.stats, ...). What actors do comes back as effect.* notifications. Each is written before the response to the request that caused it. The clock is simulated: it moves only with run.advanceTime. The end of input ends the server. run `--schema` writes the protocol's JSON Schema (`docs/cli.md`, Run).
## Options
- **`-W, --warnings-as-errors`**: Refuse a chart that compiles with a warning.
- **`-I, --include DIR`**: Search `DIR` for a src that is not beside the file naming it, in the order given. Repeatable.
- **`--config FILE`**: Read the host config from `FILE` as JSON (`docs/host-config.md`), its ioProcessors a map of type to {location}. Default: every key core's.
- **`--system ID`**: Set the config's systemID to ID. Default: tinyactors-run.
- **`--io-processor TYPE[=LOCATION]`**: Add an I/O processor of `TYPE`, at `LOCATION` when given, that the client serves after the config's. Repeatable.
- **`--boot`**: Spawn the boot actors of the inputs' system manifest before the first message.
- **`--wall-start NS`**: Start the wall clock at `NS` nanoseconds since the Unix epoch. Default: 0.
- **`--seed N`**: Seed Math.random with N; 0 takes the engine's own seed, new on every run. Default: 1.
- **`--max-ops N`**: Allow quickjs N interrupt checks per evaluation. Default: quickjs's.
- **`--memory-limit BYTES`**: Limit quickjs's heap to `BYTES`. Default: quickjs's.
- **`--realm REALM`**: Set how the charts share quickjs realms to `REALM`. Values: auto (shared unless globals are declared) or isolated (one per session). Default: auto.
- **`--max-message BYTES`**: Take input lines of at most `BYTES`. Default: 64 MiB.
- **`--schema`**: Write the protocol's JSON Schema and exit.
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors run order.scxml
```
Serve a host running one chart.
```shell
tinyactors run --config shop.json order.scxml payment.scxml
```
Serve two charts with a host config.
```shell
tinyactors run --io-processor payments --system shop order.scxml < requests.jsonl
```
```text title="output"
{"jsonrpc":"2.0","id":1,"result":{"session":1,"address":"tinyactors://shop/#_scxml_1"}}
{"jsonrpc":"2.0","id":2,"result":{}}
{"jsonrpc":"2.0","id":3,"result":{}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":1,"index":0,"session":1,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":1200},"traceparent":"00-bba5ad4a1f842e59ffef8375d9ebcaca-94e8a8f3181c87c4-03","waiting":true}}
{"jsonrpc":"2.0","id":4,"result":{"status":"held","runs":1,"fuel":19,"time":0,"nextDeadline":null}}
{"jsonrpc":"2.0","id":5,"result":{}}
{"jsonrpc":"2.0","id":6,"result":{"status":"idle","runs":1,"fuel":14,"time":0,"nextDeadline":null}}
{"jsonrpc":"2.0","id":7,"result":{"value":"paid","history":{}}}
{"jsonrpc":"2.0","id":8,"result":{}}
{"jsonrpc":"2.0","method":"effect.done","params":{"batch":3,"index":0,"session":1,"name":"order-1","final":"shipped","data":{"charge":"ch_81"}}}
{"jsonrpc":"2.0","id":9,"result":{"status":"idle","runs":1,"fuel":6,"time":0,"nextDeadline":null}}
{"jsonrpc":"2.0","id":10,"result":{"session":2,"address":"tinyactors://shop/#_scxml_2"}}
{"jsonrpc":"2.0","id":11,"result":{}}
{"jsonrpc":"2.0","id":12,"result":{}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":4,"index":0,"session":2,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":450},"traceparent":"00-7efdaa95605dfc9c4bde97c0a78eaab8-63c3721caf3ede87-03","waiting":true}}
{"jsonrpc":"2.0","id":13,"result":{"status":"idle","runs":2,"fuel":22,"time":0,"nextDeadline":30000000000}}
{"jsonrpc":"2.0","id":14,"result":{"time":30000000000,"wallNs":30000000000}}
{"jsonrpc":"2.0","method":"effect.send","params":{"batch":5,"index":0,"session":2,"type":"payments","target":"charges","event":"charge","sendid":"pay","data":{"amount":450},"traceparent":"00-7efdaa95605dfc9c4bde97c0a78eaab8-9f49d57c96da3d8f-03","waiting":true}}
{"jsonrpc":"2.0","id":15,"result":{"status":"idle","runs":2,"fuel":14,"time":30000000000,"nextDeadline":60000000000}}
{"jsonrpc":"2.0","id":16,"result":{"session":2,"segment":0,"chart":"order","parent":null,"mailbox":0,"invocations":0,"timers":[{"sendid":"deadline","event":"payment.timeout","due":60000000000}],"timersPending":1}}
```
Serve system shop with a payments I/O processor, requests from a file.
```shell
tinyactors run --schema > run.schema.json
```
Write the protocol's JSON Schema to a file.
## Exit status
- **`0`**: Standard input ends, or `--schema` has written the schema.
- **`1`**: An input or the config is refused at startup.
- **`3`**: An input or standard input cannot be read, standard output cannot be written or memory runs out.
## Related pages
- [JSON-RPC scripting](https://tinyactors.dev/cli/guides/scripting/index.md)
- [The protocol's JSON Schema](https://tinyactors.dev/cli/commands/run.schema.json)
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors help
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Describe a command or the program.
Describe a command or the program.
## Usage
```shell
tinyactors help [COMMAND]
```
Describes the program and its commands, or one command: its usage, options, examples and exit status.
## Options
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors help
```
```text title="output"
# Help
- **Name**: tinyactors
- **Summary**: Compile, check, run and inspect charts, images, snapshots and blobs
- **Usage**: `tinyactors [options] [options] [arguments]`
## Commands
| Command | Summary |
| --- | --- |
| compile | Compile charts or a system manifest into an image |
| check | Check that charts compile or that an image verifies |
| inspect | Show what an image, a snapshot or a blob holds |
| states | List each chart's states as a tree in document order |
| transitions | List each chart's transitions with events, conditions and targets |
| events | List every event name and the transitions, raises and sends using it |
| data | List each chart's data declarations |
| expressions | List each chart's expressions and scripts with where they are |
| disassemble | List each chart's executable content instruction by instruction |
| graph | Draw each chart, or list its boxes and edges |
| diff | Compare two versions and show what changes for running actors |
| lint | Find what cannot work as written in charts |
| path | Find the shortest path to a state: events, conditions and transitions |
| fmt | Rewrite charts and system manifests in the canonical layout |
| actors | List every actor of a snapshot with its state and queues |
| run | Serve one host over JSON-RPC 2.0 on standard input and output |
| help | Describe a command or the program |
| version | Print the versions of the program and its library |
## Program options
| Option | Description | Values |
| --- | --- | --- |
| -f, --format FORMAT | Write the answer in FORMAT; only graph answers in svg. Default: markdown. | markdown, json, xml, svg |
| -h, --help | Describe the command or the program. | |
| --version | Print the version as the version command does. | |
- **More**: `tinyactors help describes a command`
```
List the commands.
```shell
tinyactors help compile
```
```text title="output"
# Help
- **Name**: compile
- **Summary**: Compile charts or a system manifest into an image
- **Usage**: tinyactors compile [options] INPUT...
- **Description**: Compiles SCXML charts or one system manifest into a .tai image. The first chart is the image's default boot chart. Each static src is read relative to the file that names it, then in each -I directory. The answer lists the diagnostics and what the image holds. With -o -, the image goes to standard output and the answer to standard error.
## Options
| Option | Description | Values |
| --- | --- | --- |
| -W, --warnings-as-errors | Refuse a chart that compiles with a warning. | |
| -I, --include DIR | Search DIR for a src that is not beside the file naming it, in the order given. Repeatable. | |
| -o, --output FILE | Write the image to FILE, or to standard output when FILE is -. | |
| -e, --emit KIND | Write the image as KIND. Values: image (the image's bytes) or c (an 8-aligned C array). Default: image. | image, c |
| -s, --symbol NAME | Name the C array NAME with --emit c; NAME is a C identifier. Default: tinyactors_image. | |
## Program options
| Option | Description | Values |
| --- | --- | --- |
| -f, --format FORMAT | Write the answer in FORMAT; only graph answers in svg. Default: markdown. | markdown, json, xml, svg |
| -h, --help | Describe the command or the program. | |
| --version | Print the version as the version command does. | |
## Examples
| Caption | Command |
| --- | --- |
| Compile two charts into one image: | tinyactors compile order.scxml payment.scxml -o order.tai |
| Compile a system manifest into an image: | tinyactors compile system.xml -o system.tai |
| Write the image as a C array named order_image: | tinyactors compile order.scxml --emit c --symbol order_image -o order_image.c |
| Compile to standard output and inspect the image: | tinyactors compile order.scxml -o - \| tinyactors inspect - |
## Exit status
| Code | Meaning |
| --- | --- |
| 1 | An input is refused: it does not compile, or it is of an unknown format. |
| 3 | An input cannot be read, the image cannot be written or memory runs out. |
```
Describe the compile command.
```shell
tinyactors help -f json inspect
```
```text title="output"
{
"name": "inspect",
"summary": "Show what an image, a snapshot or a blob holds",
"usage": "tinyactors inspect [options] INPUT...",
"description": "Shows an image's sections, charts and boot actors; it reads its inputs as the other commands do. Shows a snapshot's format, system, time, segments with their images and actors. Shows the datamodels' state of a snapshot too, decoded when it is CBOR. Shows the session a hibernation or export blob holds, the image it was written with and who can wake it. Shows a blob's datamodel state, and its chart and configuration when the image follows it: an image, charts or a snapshot.",
"options": [
{
"option": "-W, --warnings-as-errors",
"description": "Refuse a chart that compiles with a warning.",
"values": ""
},
{
"option": "-I, --include DIR",
"description": "Search DIR for a src that is not beside the file naming it, in the order given. Repeatable.",
"values": ""
},
{
"option": "-c, --chart NAME",
"description": "Look at the chart named NAME only. Repeatable.",
"values": ""
},
{
"option": "-s, --segment N",
"description": "Read the image that segment N of a snapshot runs. Default: the newest live segment.",
"values": ""
}
],
"programOptions": [
{
"option": "-f, --format FORMAT",
"description": "Write the answer in FORMAT; only graph answers in svg. Default: markdown.",
"values": "markdown, json, xml, svg"
},
{
"option": "-h, --help",
"description": "Describe the command or the program.",
"values": ""
},
{
"option": "--version",
"description": "Print the version as the version command does.",
"values": ""
}
],
"examples": [
{
"caption": "Show what an image holds:",
"command": "tinyactors inspect order.tai"
},
{
"caption": "Compile a system manifest and show its image:",
"command": "tinyactors inspect system.xml"
},
{
"caption": "Compile a chart and show its image as JSON:",
"command": "tinyactors inspect --format json order.scxml"
},
{
"caption": "Show what a snapshot holds:",
"command": "tinyactors inspect shop.snapshot"
},
{
"caption": "Show a blob with its chart and configuration from a snapshot:",
"command": "tinyactors inspect order-17.blob shop.snapshot"
}
],
"exitStatus": [
{
"code": 1,
"meaning": "An input is refused: it does not compile or verify, or it is damaged or of an unknown format."
},
{
"code": 3,
"meaning": "A file cannot be read or written, or memory runs out."
}
]
}
```
Describe the inspect command in JSON.
## Related pages
- **[`tinyactors version`](https://tinyactors.dev/cli/commands/version/index.md)**: Print the versions of the program and its library.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)
---
# tinyactors version
Kind: reference. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).
> Print the versions of the program and its library.
Print the versions of the program and its library.
## Usage
```shell
tinyactors version
```
Prints the program's version and its library's version, ABI and image format version.
## Options
Configure output formats like `-f json` using the [shared options on the command reference](https://tinyactors.dev/cli/commands/index.md#program-options).
## Examples
```shell
tinyactors version
```
```text title="output"
# Version
- **Program**: tinyactors
- **Version**: 0.5.0
- **Library**: 0.5.0
- **ABI**: 1
- **Image format**: 1
```
Print the versions.
```shell
tinyactors version -f json
```
```text title="output"
{
"program": "tinyactors",
"version": "0.5.0",
"library": "0.5.0",
"abi": 1,
"imageFormat": 1
}
```
Print the versions as JSON.
## Related pages
- **[`tinyactors help`](https://tinyactors.dev/cli/commands/help/index.md)**: Describe a command or the program.
## Commands
- [tinyactors compile](https://tinyactors.dev/cli/commands/compile/)
- [tinyactors check](https://tinyactors.dev/cli/commands/check/)
- [tinyactors inspect](https://tinyactors.dev/cli/commands/inspect/)
- [tinyactors states](https://tinyactors.dev/cli/commands/states/)
- [tinyactors transitions](https://tinyactors.dev/cli/commands/transitions/)
- [tinyactors events](https://tinyactors.dev/cli/commands/events/)
- [tinyactors data](https://tinyactors.dev/cli/commands/data/)
- [tinyactors expressions](https://tinyactors.dev/cli/commands/expressions/)
- [tinyactors disassemble](https://tinyactors.dev/cli/commands/disassemble/)
- [tinyactors graph](https://tinyactors.dev/cli/commands/graph/)
- [tinyactors diff](https://tinyactors.dev/cli/commands/diff/)
- [tinyactors lint](https://tinyactors.dev/cli/commands/lint/)
- [tinyactors path](https://tinyactors.dev/cli/commands/path/)
- [tinyactors fmt](https://tinyactors.dev/cli/commands/fmt/)
- [tinyactors actors](https://tinyactors.dev/cli/commands/actors/)
- [tinyactors run](https://tinyactors.dev/cli/commands/run/)
- [tinyactors help](https://tinyactors.dev/cli/commands/help/)
- [tinyactors version](https://tinyactors.dev/cli/commands/version/)