<!-- https://tinyactors.dev/docs/python/ -->
# Python API · 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).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).

> Every class, function and constant of the tinyactors package for Python, each with its signature and what it does.

`tinyactors 0.4.0`

Run SCXML statecharts as actors in a host, with charts in Python or ECMAScript.

A Host holds actors and runs each one's chart when events reach it. It does no I/O: what an actor asks of the outside world reaches a handler you give the host, and the handler does the work.

## Contents

- **[Charts](#charts)**: [`compile_charts`](#compile_charts), [`compile_dir`](#compile_dir), [`Compiled`](#Compiled)
- **[Host](#host)**: [`Host`](#Host), [`ChartRef`](#ChartRef), [`Migrated`](#Migrated)
- **[Actors](#actors)**: [`Actor`](#Actor)
- **[Driving](#driving)**: [`SimulatedClock`](#SimulatedClock)
- **[Handlers](#handlers)**: [`Spawner`](#Spawner), [`Invocation`](#Invocation), [`Send`](#Send), [`LogEntry`](#LogEntry)
- **[Memory](#memory)**: [`SQLiteStore`](#SQLiteStore), [`MemoryStore`](#MemoryStore)
- **[Values](#values)**: [`Address`](#Address), [`UNDEFINED`](#UNDEFINED)
- **[Errors](#errors)**: [`TinyactorsError`](#TinyactorsError), [`StaleError`](#StaleError), [`StateError`](#StateError), [`CompileError`](#CompileError), [`Diagnostic`](#Diagnostic), [`InvalidError`](#InvalidError), [`UnsupportedError`](#UnsupportedError), [`ResolveError`](#ResolveError)
- **[Operating a host](#operating-a-host)**: [`compile_system`](#compile_system)
- **[Wire format](#wire-format)**: [`encode`](#encode), [`decode`](#decode), [`decode_traces`](#decode_traces)
- **[More of the module](#others)**: [`Event`](#Event)

<a id="the-application-api"></a>

## The application API

<a id="charts"></a>

### Charts

compile_dir() compiles a directory of charts and their helper files into an image; compile_charts() compiles SCXML documents (Compiled.image).

<a id="compile_charts"></a>

#### `compile_charts` (function)

```python
compile_charts(sources, resolver=None)
```

Compile SCXML documents into one image, the form a Host runs.

`sources` is a list of (name, text) pairs: each text is one SCXML document, named for diagnostics and for src= references between them; the first is the image's default boot chart. Use one call per image: all the charts a host should run as one segment together (a chart and the charts it invokes), and a later call for a new version.

`resolver`, a callable resolver(base, source) -> str, is called at compile time for each static src= that is not among the sources (a <script src>, an <invoke src>, a .py file of methods); it returns the text, or refuses by raising ResolveError, which the compiler reports at the line and column it names. It lives only for this call.

Returns a Compiled: pass Compiled.image to Host.add_image, then close it (or use it as a context manager); its diagnostics are the warnings and notes. A compilation with an error raises CompileError, with every diagnostic, after freeing the result.

<a id="compile_dir"></a>

#### `compile_dir` (function)

```python
compile_dir(path, *, resolver=None)
```

Compile every *.scxml file under the directory `path` into one image, and return the Compiled, as compile_charts does.

Keep an application's charts and their helper files (a .py file a chart reads with <script src>, a chart it invokes with <invoke src>) in one directory, compile it once at startup or in a build step, and give the result to any number of hosts. The charts are named by their path under `path` (sorted; the first is the image's default boot chart), and a src is read from under `path`, relative to the document that names it: a path that leaves `path`, symbolic links included, is refused (ResolveError, so CompileError). Give `resolver` to read the src files yourself instead. A chart file whose real path leaves `path` raises ValueError; an error in a chart raises CompileError.

<a id="Compiled"></a>

#### `Compiled` (class)

```python
class Compiled
```

The result of compile_charts or compile_system: an image and the compilation's notes.

Hold it only as long as you need the image: Host.add_image copies the bytes, so close it right after adding (a `with` block does), or keep it to add the same image to several hosts. To compile once and run many times (at build time, in CI), write `compiled.image` to a .tai file and give its bytes to add_image later: no compiler at run time.

<a id="Compiled.close"></a>

##### `Compiled.close`

```python
close()
```

Free the compile result. The image is stale afterwards; the diagnostics stay. A `with` block calls it on exit, and the collector as a fallback.

<a id="Compiled.enter"></a>

##### `Compiled.enter`

```python
__enter__()
```

Enter a `with` block: returns the result, and close() runs at the block's end.

<a id="Compiled.exit"></a>

##### `Compiled.exit`

```python
__exit__(...)
```

Leave the `with` block: close() the result, so the image is freed.

<a id="Compiled.image"></a>

##### `Compiled.image`

```python
image
```

The image's bytes, copied out of the compile result at the first read.

Pass them to Host.add_image or write them to a .tai file. Once read, they stay valid after close(); a first read after close() raises TinyactorsError (TA_ERROR_STALE), since the result is freed.

<a id="Compiled.diagnostics"></a>

##### `Compiled.diagnostics`

```python
diagnostics
```

The warnings and notes of a compilation that succeeded, a list of Diagnostic (errors raise CompileError instead).

<a id="host"></a>

### Host

Host(charts, system=...) creates one and runs each image as a segment, one actor system with its own memory.

<a id="Host"></a>

#### `Host` (class)

```python
class Host
Host(charts, *, system, io_processors=None, config=None, clock=None, log=None, telemetry=None, services=None, transport=None, on_done=None, on_error=None, on_handler_error=None, migrated=None, migration_done=None, store=None, resident=None)
```

A host: the object that holds actors and runs their charts, many actor systems as one.

`charts` is what it runs: a Compiled, an image's bytes, or a list of them, each added as a segment in order (add_image adds a new version later). `system` is the system id, the authority of its actors' addresses (tinyactors://<system>/...). `config` is the rest of the host's configuration as a dict (system limits such as maxActors and instanceBytes, migrateQuantum, telemetry; see the core's host-config documentation). Without system.traceSeed the host draws a random one, so each host starts its own trace ids; set it to reproduce them. Everything else is your side of the host, all optional:

- io_processors: {type: processor}, one object per external system an actor talks to with <send type=...>, each with receive(send) (an async def allowed) and an optional `location`; the config's ioProcessors are made from it, in its order.
- transport: handler(send) for every send to another system's address (tinyactors://<other system>/...), as a Send: your transport, which needs no config. Without one, each such send fails (error.communication).
- services: {type: handler(invocation)} for the services your application runs; an <invoke type=...> starts one with an Invocation, and the handler returns the service object (see Invocation).
- log: handler(entry) for <log> lines (LogEntry).
- on_done: handler(actor, donedata) when a top-level actor reaches a final state; on_error: handler(actor, error) when one faults.
- on_handler_error: handler(error, effect) when one of your handlers raises (effect: the Send, LogEntry, Invocation or Migrated it handled, or None); without it the driver raises the error after the turn. A send whose processor raised is failed either way.
- store: an object with save(session, blob), load(session) and delete(session) (MemoryStore, SQLiteStore, or yours): where hibernated actors' blobs go. When an event comes for a hibernated actor the host loads its blob and wakes it, and deletes the blob.
- resident: with a store, the most actors kept in memory: after a turn the host hibernates the coldest ones past it into the store.
- migrated: handler(migrated) for each actor a migration moved.
- migration_done: handler(result) when a migration (Host.migrate) ends, with its counts and the sessions it left behind.
- telemetry: handler(signal, data) with OTLP bytes, signal "traces" or "logs".
- clock: a SimulatedClock, for tests; the real clock otherwise.

Handlers get no host: each view and record has `.host`. A plain function handler gets a thin view, valid until the batch is acknowledged; an async def handler gets a record and needs the asyncio driver (`async with`).

A typical program: compile_dir() the charts, Host(compiled, system="shop", io_processors={"db": Database()}), spawn("order") an actor, send() it events, and let the host turn; your processors do the I/O the actors ask for.

Drive the host with run_until_idle() (until nothing is runnable now), or `await host.idle()` under asyncio, where timers fire on the loop. Inputs (spawn, send, terminate, ...) apply at the call; their effects reach your handlers in the next turn. A host is used from the thread that created it.

<a id="Host.add_image"></a>

##### `Host.add_image`

```python
add_image(image, /)
```

Run an image as a new segment of the host, and return the segment.

`image` is any buffer: Compiled.image, or the bytes of a .tai file; the host copies it during the call. Each call makes one segment, even for the same bytes. A chart whose name the host already runs gets a new current version here: new spawns run it, the running actors stay on the old one until Host.migrate moves them, and a segment left with no actors and only older versions is freed.

Part of operating a host (the README's "Operating a host").

<a id="Host.chart"></a>

##### `Host.chart`

```python
chart(name, /)
```

The current version of the chart `name`, as a ChartRef for spawn.

Spawning goes through a ChartRef rather than a name because a host can run several versions of a chart at once (one per add_image of an image that has it): the reference pins the version that was current when you asked. Ask again after add_image of a new version, so new actors start on it; actors already running stay where they are until Host.migrate. Raises TinyactorsError when no image added has a chart of that name.

Part of operating a host (the README's "Operating a host").

<a id="Host.actor"></a>

##### `Host.actor`

```python
actor(which, /)
```

A live actor of the host as an Actor: `which` is its session id (an int), the name it was spawned with (newest segment first), or its local address (an Address, or text starting tinyactors://).

Names are how an application finds its long-lived actors again without keeping their session ids: spawn(chart, name="orders") registers one, and Host.boot registers each actor a <system> manifest declares under its name. Raises StaleError when no live actor answers to it.

<a id="Host.actors"></a>

##### `Host.actors`

```python
actors(chart=None)
```

An awaitable of the host's live actors, as a list of Actor, or of those whose chart is named `chart`.

It reads the typed method actor_list a page at a time, so it needs the asyncio driver (TypeError under `with`). Use it for an operator's view or a shutdown that terminates a kind of actor; a program that needs its actors often keeps their names instead.

<a id="Host.spawn"></a>

##### `Host.spawn`

```python
spawn(chart, name=None, params=None, traceparent=None)
```

Start an actor of `chart` and return it as an Actor.

`chart` is a chart's name (its current version, Host.chart) or a ChartRef (a version you pinned). This is how your program creates actors one at a time: one per order, per user, per device. `name` registers it so it can be found again (Host.actor(name), the address tinyactors://<system>/@<name>); `params` (a dict) sets its <datamodel>'s data of the same ids, the way an <invoke>'s params do; `traceparent` (W3C text) makes its first steps part of your caller's trace. The actor enters its initial states in the next turn. To start the actors an image declares, use Host.boot.

<a id="Host.send"></a>

##### `Host.send`

```python
send(target, event, data=None, *, sendid=None, traceparent=None, origin=None)
```

Give an actor the external event `event` with optional `data` (a value of the value table, as a Python object). `target` is its session (an int), or a local address (an Address, or a str: tinyactors://<this systemID>/#_scxml_<n> or .../@<name>), which the host resolves.

send(message) takes a message from another system, the dict the other side's send.message gave (decoded from your wire): its target, event, data, sendid, origin and traceparent; keys it does not know are ignored, and a sendid, origin or traceparent of UNDEFINED is absent, as None is. A failure is never part of a message: see Host.fail.

Applied at the call: the event waits in the actor's mailbox and runs in the next turn; a hibernated actor is loaded from the store first. `sendid` becomes _event.sendid (the sender's <send id>). `traceparent` continues your caller's trace. `origin` is the sender's address when the event comes from another system (what its transport handed over as send.origin): it becomes _event.origin, a chart's reply goes back there, and _event.origintype is SCXML's. Refused with TinyactorsError when the target does not exist (TA_ERROR_STALE), is another system's address (TA_ERROR_INVALID) or the host is full.

<a id="Host.fail"></a>

##### `Host.fail`

```python
fail(target, sendid=None)
```

Report that a send could not be delivered: the sending actor `target` (a session, or its local address, such as a message's origin) gets error.communication with `sendid`.

Use it when the other side of your transport says a send failed (the target did not exist, the connection broke), and only for failures you decide to believe: a peer that can make you call it can give your actors any error. Inside a transport or I/O processor handler, send.fail() does the same for that send.

Part of the wire format (the README's "Wire format").

<a id="Host.send_many"></a>

##### `Host.send_many`

```python
send_many(items, /)
```

Give events to actors in order, one call for many: each item is (target, event[, data[, traceparent]]), as send takes them.

Use it when events arrive in batches (a queue consumer, a replay, a load test): one call into the host for the batch instead of one per event. Returns how many were accepted, a prefix of `items`: on a refusal (a full host) the rest were not sent, so run the host to make room and send the rest again.

<a id="Host.terminate"></a>

##### `Host.terminate`

```python
terminate(session, /)
```

End the actor `session` from outside: it leaves its states (their <onexit> runs), its invocations are cancelled, and it is gone after the next turn.

An actor whose chart reaches a top-level <final> ends by itself; use terminate when your program decides an actor's work is over (a user deleted, an order cancelled from an admin tool) or to clean up after a boot that failed part way.

<a id="Host.boot"></a>

##### `Host.boot`

```python
boot(segment, /)
```

Spawn the boot actors of a segment add_image returned: the image's <system><actor> entries (compile_system), or its default boot chart (the first source given to compile_charts), each under its name, so Host.actor finds it. Use it to start an application from its image alone; spawn starts one actor of a chart you name. A boot that fails part way leaves the actors already spawned; a second boot spawns them all again.

Part of operating a host (the README's "Operating a host").

<a id="Host.metrics"></a>

##### `Host.metrics`

```python
metrics()
```

The host's counters now, as OTLP protobuf bytes (an ExportMetricsServiceRequest, for a collector's /v1/metrics).

Telemetry has two directions: traces and logs are pushed to your telemetry handler as the host records them, and metrics are pulled by you, on your schedule. Call it when your exporter scrapes or on a timer, and post the bytes as you post the handler's. host_stats answers with the counters as Python values instead. Raises TinyactorsError (TA_ERROR_STATE) when the config has no telemetry.

Part of operating a host (the README's "Operating a host").

<a id="Host.sweep"></a>

##### `Host.sweep`

```python
sweep(max_scan, limit, /)
```

The sessions to hibernate now: at most `limit` actors that did not run since the previous sweep and are at rest (the CLOCK sweep), looking at most at `max_scan` slots.

Hibernation keeps a large population in a small memory: most actors wait most of the time. Host(store=..., resident=N) runs the cycle for you; sweep, hibernate and wake are for an application with a policy of its own: when host_stats shows more actors resident than you want, sweep, hibernate() each session it returns and save the blobs in the host's store, which the host loads from when an event comes for one. Calling sweep regularly is what makes "did not run since the previous sweep" mean cold.

Part of operating a host (the README's "Operating a host").

<a id="Host.hibernate"></a>

##### `Host.hibernate`

```python
hibernate(session, /)
```

Take the actor `session` out of memory and return its blob (bytes) for you to store, e.g. in a database keyed by session.

The host keeps its record: events and timers for it still arrive, and the host loads it back from its store (save the blob there), or you call Host.wake. Raises TinyactorsError (TA_ERROR_STATE) when it is not at a stable point or runs an invocation; it stays resident then. A blob wakes only in the host that wrote it.

Part of operating a host (the README's "Operating a host").

<a id="Host.wake"></a>

##### `Host.wake`

```python
wake(session, blob, /)
```

Bring the hibernated actor `session` back from its `blob`: what the host does with its store's blob when an event comes for the actor, and what a host without a store leaves to you. Its waiting events run in the next turn; until then they wait. Only its latest blob: one of an earlier hibernation raises TinyactorsError TA_ERROR_STALE, another session's or another Host's TA_ERROR_INVALID (each Host draws its identity from os.urandom; a restored one keeps the snapshot's).

Part of operating a host (the README's "Operating a host").

<a id="Host.snapshot"></a>

##### `Host.snapshot`

```python
snapshot()
```

Copy the whole host into bytes: every segment's memory, both datamodels' state and the images.

What it is for: a copy of the whole application, every chart version at once. Restore it (Host.restore) to rehearse a deploy (add the new image, migrate, run the clock ahead, look), to give a developer the host as it was when something went wrong, to start each test from one prepared world, or to take a host out of the process for a while. It is valid for the same build of the library only: never a backup.

The host must be quiescent: not from a handler, with no typed method's reply or other effect pending (run the host first), and not while a migration runs (TinyactorsError, TA_ERROR_STATE). The hibernated actors' blobs are not in it: they stay in your store. The services you run are not in it either; Host.restore starts them again.

Part of operating a host (the README's "Operating a host").

<a id="Host.restore"></a>

##### `Host.restore`

```python
Host.restore(snapshot, charts, *, system, io_processors=None, config=None, clock=None, log=None, telemetry=None, services=None, transport=None, on_done=None, on_error=None, on_handler_error=None, migrated=None, migration_done=None, store=None, resident=None)
```

A new Host running a snapshot of Host.snapshot.

Pass what Host() takes: the system the snapshot was taken with (its id must match), its config, and the handlers. `charts` are the images you run now: those the snapshot holds already are kept, the others are added as new versions (Host.migrate moves actors to them). Its clock goes on from the snapshot's time. At its first run each invocation of a service that was running reaches your services= handler again, with invocation.restored true: pass your real handlers to go on, stand-ins for a copy that must not reach the real services, or leave a type out and its invokers get error.communication. A copy that hibernates actors needs its own copy of the store: it writes blobs too.

Part of operating a host (the README's "Operating a host").

<a id="Host.migrate"></a>

##### `Host.migrate`

```python
migrate(*, chart=None, session=None, wake=False, timeout=0)
```

Start a migration: move running actors to the current version of their chart, in the next runs. Returns the migration's id (an int).

Use it after add_image of a new version: all charts, the one named `chart`, or one `session`. Each actor moves at a stable point, keeping its session id, its states (matched by id) and its timers, and gets error.platform.upgrade with its old variables first. A busy actor is retried; a hibernated one waits until something wakes it, or, with `wake`, is loaded from the host's store (while fewer than `resident` actors are in memory, so a population moves a bound at a time). `timeout` (seconds of the host's clock, 0 for none) ends the migration anyway. A chart the host does not have raises TinyactorsError TA_ERROR_INVALID, a session that ended TA_ERROR_STALE.

The host's migration_done handler gets its end, with result {"migration", "migrated", "failed": [{"session", "reason"}, ...], "pending": [session, ...]}, failed naming the actors it could not move and why (core's status), pending those its timeout left behind; the migrated handler sees each actor that moved.

Part of operating a host (the README's "Operating a host").

<a id="Host.run_until_idle"></a>

##### `Host.run_until_idle`

```python
run_until_idle()
```

Turn until no actor is runnable at the current time: the synchronous driver's step.

Use it in scripts, tests and programs that run the host between other work: give inputs, then run_until_idle() to let the actors react and your handlers run. Handlers run inside it; a handler's exception, or a failure of the host, is raised after the turn it happened in. Timers due later stay pending: under asyncio the loop fires them, and with a SimulatedClock, increment() moves to them.

<a id="Host.idle"></a>

##### `Host.idle`

```python
idle()
```

asyncio: a future that completes when the host is idle.

Inside `async with Host(...)` the host turns on the event loop by itself, after each input and at each timer, beside your other tasks (a web server, a queue consumer). Await idle() when you need the effects of your inputs before going on: in a test, or before reading an answer a typed method's handler stored.

<a id="Host.close"></a>

##### `Host.close`

```python
close()
```

Free the host. The open spans end and the last traces and logs go to the telemetry handler, then the memory is released. Typed-method handlers still waiting for a reply are dropped without being called, and running services are dropped without stop(). `with` and `async with` call it on exit. The collector frees a host you did not close, but without the last telemetry.

<a id="Host.enter"></a>

##### `Host.enter`

```python
__enter__()
```

Enter the synchronous driver: returns the host; refuses an async def handler (use async with).

<a id="Host.exit"></a>

##### `Host.exit`

```python
__exit__(...)
```

Leave the synchronous driver: closes the host.

<a id="Host.aenter"></a>

##### `Host.aenter`

```python
__aenter__()
```

Enter the asyncio driver: the host turns on the running event loop.

<a id="Host.aexit"></a>

##### `Host.aexit`

```python
__aexit__(...)
```

Leave the asyncio driver: awaits the handlers' tasks, then closes the host.

<a id="Host.actor_state"></a>

##### `Host.actor_state`

```python
actor_state(handler, on_error=None, /, *, session)
```

Ask which states the actor `session` is in now.

The result is {"value": <state value>, "history": {...}}, the value in xstate's shape: an atomic state is its id ("idle"), a compound state {<its id>: <its active child>}, a parallel state {<its id>: {<region id>: ..., ...}}. "history" maps each history state the actor has recorded (at its parent's exit) to its parent as it would be entered again, in the same shape: where a transition to it returns. One that recorded nothing is absent. Use it to show an actor in a debugger or dashboard, or in a test to assert where a chart went after some events. Inside a chart, In(state) asks the same question. A hibernated actor is refused (reason "state"): wake it first.

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.actor_context"></a>

##### `Host.actor_context`

```python
actor_context(handler, on_error=None, /, *, session)
```

Ask for the actor `session`'s variables: each <data> of its chart.

The result is {"variables": {<data id>: <value>, ...}}, in the order the chart declares them, as values of the value table (what cannot be shown that way is None or UNDEFINED). On an ECMAScript chart a variable that holds undefined is UNDEFINED, apart from None for null. Before the actor's first run its <data> are not initialized, its spawn params included: they are bound when it first runs, so ask after a run. Use it to inspect an actor's data from outside, in a debugger, an admin page or a test, without the chart sending it anywhere. A hibernated actor is refused (reason "state"): wake it first.

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.actor_list"></a>

##### `Host.actor_list`

```python
actor_list(handler, on_error=None, /, *, limit=256, cursor=0)
```

Ask for the sessions of the host, a page at a time.

The result is {"sessions": [session, ...], "cursor": int or None}: pass the cursor back for the next page; None means every session was listed. `limit` is 1 to 512. Use it to enumerate actors for an admin page, a health check or a cleanup, then ask actor_get, actor_state or actor_context about each one.

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.actor_get"></a>

##### `Host.actor_get`

```python
actor_get(handler, on_error=None, /, *, session)
```

Ask for the summary of the actor `session`: where it runs and how busy it is.

The result is {"session", "segment", "chart" (its name), "parent" (the session that invoked it, or None for an actor you spawned), "mailbox" (events waiting), "invocations" (services it runs), "timers" (its pending delayed sends, earliest first, at most 32: each {"sendid" (None when it has none), "event", "due" (seconds on the host's clock, a float)}), "timersPending" (how many it has: more than "timers" holds when the list was cut)}. Use it to find which version an actor runs (its segment), to walk from a child to its parent, to spot an actor whose mailbox grows, or to say when a timeout will fire.

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.host_stats"></a>

##### `Host.host_stats`

```python
host_stats(handler, on_error=None, /)
```

Ask for the host's counters, and each chart's.

The result is {"host": {...}, "charts": [...]}. The host's: segments, actors, hibernated, runnable, migrations, regionBytes (core's memory for the live segments), delivered, routed, migrated, retired, fuelClock. Each chart's, summed over its versions: name, actors, hibernated, spawned, ended, turns, macrosteps, fuel, errorsExecution, errorsCommunication, errorsPlatform, faults. Use it for a dashboard or a health check, to decide when to sweep and hibernate, or in a test to count what happened; Host.metrics gives the host's counters as OTLP for a collector.

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.host_config"></a>

##### `Host.host_config`

```python
host_config(handler, on_error=None, /)
```

Ask for the configuration the host runs with: the config you gave Host(...), with every default filled in.

The result is a dict in the config's own shape (systemID, system, ioProcessors, migrateQuantum, telemetry), so a host made from it answers the same. Use it to log or show what a host was really given, or to make a second host like the first (a copy for Host.restore needs the same system id).

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.trace_configure"></a>

##### `Host.trace_configure`

```python
trace_configure(handler, on_error=None, /, *, detail='summary', values=False, sample=1, records=True, rules=[])
```

Set what the host traces, for every segment and the ones added later.

`detail` is "summary", "decisions", "full" or "off"; `values` puts data values in the spans; `sample` (0 to 1) is the share of new traces kept; `records` False keeps traceparents flowing but writes no spans; `rules` (at most 32) pick details per chart, actor, event or source (the core's requests documentation has their form). The result is {}. It replaces the last configuration; watches stay. Use it at startup to set the policy, and again to turn tracing up or down while the host runs; trace_watch is for a closer look for a while. Refused (reason "state") when the config has no telemetry.

Part of operating a host (the README's "Operating a host").

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.trace_watch"></a>

##### `Host.trace_watch`

```python
trace_watch(handler, on_error=None, /, *, rules, seconds=900)
```

Trace something in more detail for a while: rules put in front of the configured ones until `seconds` of the host's clock pass (None: until trace_unwatch).

Each rule picks actors (by chart, actor name, event, session or source) and a detail, e.g. {"chart": "checkout", "sample": "sample", "detail": "full"}. The result is {"id": int}, the watch's id for trace_unwatch. Use it to debug one chart or one kind of event in production without raising the detail for the whole host.

Part of operating a host (the README's "Operating a host").

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.trace_unwatch"></a>

##### `Host.trace_unwatch`

```python
trace_unwatch(handler, on_error=None, /, *, id)
```

End the watch `id` (from trace_watch's result) before its time is up.

The result is {}. A watch that already ended, or never was, is an error with reason "stale". Use it when the closer look is done, so tracing falls back to the configured policy.

Part of operating a host (the README's "Operating a host").

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.trace_end"></a>

##### `Host.trace_end`

```python
trace_end(handler, on_error=None, /)
```

End every open span now and hand what was recorded to the telemetry handler, before the reply.

The spans end at the last clock the host saw, marked incomplete. The result is {}. close() calls it for you; call it yourself to end the spans at a moment you choose, when your shutdown does other work before it closes the host. Refused (reason "state") when the config has no telemetry.

Part of operating a host (the README's "Operating a host").

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.trace_spans_decode"></a>

##### `Host.trace_spans_decode`

```python
trace_spans_decode(handler, on_error=None, /, *, traces)
```

Read the spans out of OTLP trace bytes, such as the data the telemetry handler got with signal "traces".

The result is {"spans": [...]}, each span a dict: trace and span ids as hex, parent (None for a root), name, kind, start and end (nanoseconds since the epoch), status, statusMessage, attributes and events. It reads only the bytes, not the host. Use it in tests and tools that check what an actor's steps traced without a collector or an OTLP library.

Part of operating a host (the README's "Operating a host").

How it works, as for every typed method (Host.actor_state, host_stats, trace_watch, ...): pass the params as keywords; core checks them. The call returns None at once and handler(result) runs at a later drain with the result as Python values, so a script drives the host once more (run_until_idle()) and asyncio code awaits host.idle(). An error goes to on_error(error), given second or as on_error=, as a TinyactorsError whose code, reason and path say what was wrong; without on_error the driver raises it after the turn. A closed or full host refuses at the call.

<a id="Host.system"></a>

##### `Host.system`

```python
system
```

The host's system id (the config's systemID), the authority of its actors' addresses.

<a id="Host.closed"></a>

##### `Host.closed`

```python
closed
```

True once the host was freed (close(), the end of a `with` block); every call refuses then.

<a id="Host.ticks_per_second"></a>

##### `Host.ticks_per_second`

```python
ticks_per_second
```

The host's clock rate, config's system.ticksPerSecond, read once at creation: delays in charts count in these ticks; the API takes and gives seconds (next_deadline, migrate's timeout, SimulatedClock).

<a id="Host.next_deadline"></a>

##### `Host.next_deadline`

```python
next_deadline
```

Seconds from now to the host's next deadline (a delayed send, a migration's timeout), as the last turn that went idle left it: 0.0 when it is due, None when there is none. With a SimulatedClock, which arms no timer, increment the clock by it to move straight to the next thing that happens.

<a id="ChartRef"></a>

#### `ChartRef` (class)

```python
class ChartRef
```

A chart in a host, from Host.chart(name): the segment that runs its current version and its index in that segment's image. Pass it to Host.spawn. It names one version: after add_image of a new one, ask Host.chart again.

<a id="ChartRef.segment"></a>

##### `ChartRef.segment`

```python
segment
```

The segment (one actor system of the host) that runs this version: the int add_image returned for its image.

<a id="ChartRef.chart"></a>

##### `ChartRef.chart`

```python
chart
```

The chart's index in that segment's image; with the segment, it names one version of one chart.

<a id="Migrated"></a>

#### `Migrated` (class)

```python
class Migrated
```

An actor that a migration moved to its chart's current version, given to the migrated handler.

Use the handler to follow a deploy actor by actor (a progress count, a log of who moved) or to update what your application keeps about an actor's version; migration_done reports the whole migration's end. A thin view, valid until the batch's ack (see Host.migrate).

Part of operating a host (the README's "Operating a host").

<a id="Migrated.session"></a>

##### `Migrated.session`

```python
session
```

The actor's session id (int); it is the same after the move.

<a id="Migrated.segment"></a>

##### `Migrated.segment`

```python
segment
```

The segment it now runs in: the current version's.

<a id="Migrated.chart"></a>

##### `Migrated.chart`

```python
chart
```

The name of the chart it runs, the same before and after.

<a id="Migrated.migration"></a>

##### `Migrated.migration`

```python
migration
```

The migration (Host.migrate's return value) that moved it.

<a id="Migrated.host"></a>

##### `Migrated.host`

```python
host
```

The Host this came from: the handlers get no host, so use this one to make inputs.

<a id="actors"></a>

### Actors

Host.spawn(chart) starts an actor and returns it as an Actor: send() it events, ask() it and await the reply, await its state() or done. Host.actor() finds a live one by session, name or address.

<a id="Actor"></a>

#### `Actor` (class)

```python
class Actor
Actor(host, id)
```

An actor of a host: what Host.spawn and Host.actor return, what send.sender and on_done get. It is a small immutable value made where the API returns one, compared and hashed by its session; keeping one keeps nothing alive in the host, and one whose actor ended refuses what needs the actor (StaleError).

Use it to talk to the actor: send() an event, ask() a question and await the reply, await state(), context() or get() to inspect it, terminate() it, or await done for its donedata. The awaitable ones need the asyncio driver (async with Host(...)).

<a id="Actor.address"></a>

##### `Actor.address`

```python
address
```

The actor's address, tinyactors://<system>/#_scxml_<id>, the full form: what another system sends to. A chart sees this actor's sends' _event.origin either in it or as its fragment, #_scxml_<id>, so compare by the fragment.

<a id="Actor.send"></a>

##### `Actor.send`

```python
send(event, data=None, *, sendid=None, traceparent=None)
```

Give the actor an event (Host.send to its session): applied at the call, run at the host's next turn. `data` becomes _event.data; `traceparent` continues a W3C trace.

<a id="Actor.terminate"></a>

##### `Actor.terminate`

```python
terminate()
```

End the actor (Host.terminate): it leaves its states, whose <onexit> runs, in the next turn, and sends no done event; a hibernated actor is woken from the host's store to end, and its blob deleted.

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

##### `Actor.state`

```python
state()
```

An awaitable of the actor's active states (the typed method actor_state): {"configuration": [...], ...} as core answers it.

<a id="Actor.context"></a>

##### `Actor.context`

```python
context()
```

An awaitable of the actor's datamodel variables (the typed method actor_context), as values of the value table.

<a id="Actor.get"></a>

##### `Actor.get`

```python
get()
```

An awaitable of what the host knows about the actor (the typed method actor_get): its chart, its state, its mailbox and timers.

<a id="Actor.ask"></a>

##### `Actor.ask`

```python
ask(event, data=None)
```

Send the actor `event` with `data` and return an awaitable of its reply, an (event, data) pair: the chart answers with <send targetexpr="_event.origin" event="..."/>. The event's origin is an address of the host's own (system tinyactors-ask), so the reply comes back here and never reaches your transport. There is no timeout of its own: use asyncio.wait_for, whose cancel drops the ask; asks pending when the host closes never complete. Needs the asyncio driver (TypeError under `with`).

<a id="Actor.done"></a>

##### `Actor.done`

```python
done
```

An awaitable of the actor's donedata, settled when it reaches a top-level final state (or raising the error it ended with). Await it under asyncio; an actor that ended already raises StaleError.

<a id="Actor.host"></a>

##### `Actor.host`

```python
host
```

<a id="Actor.id"></a>

##### `Actor.id`

```python
id
```

<a id="driving"></a>

### Driving

Inputs (spawn, send, ...) apply at the call; the actors run when the host turns. Use run_until_idle(), a SimulatedClock in tests, or `async with Host(...)` and `await host.idle()` under asyncio.

<a id="SimulatedClock"></a>

#### `SimulatedClock` (class)

```python
class SimulatedClock
SimulatedClock()
```

A clock that moves only when told, for tests and simulations.

Pass it as Host(..., clock=clock). Delayed sends (<send delay>), watch ends and migration timeouts fall due when increment() moves past them, so a test of a 30-day timeout takes no time and gives the same result every run; a host on a simulated clock never sleeps. To jump to the next thing that happens: clock.increment(host.next_deadline). One clock can drive several hosts, which then share its time.

<a id="SimulatedClock.increment"></a>

##### `SimulatedClock.increment`

```python
increment(seconds, /)
```

Move the clock on by `seconds` (an int or a float, as next_deadline gives) and turn every host made with it until idle, so the timers due by then run.

<a id="SimulatedClock.now"></a>

##### `SimulatedClock.now`

```python
now
```

The simulated time in seconds (a float) since the clock was made (it starts at 0.0).

<a id="handlers"></a>

### Handlers

Host(...) takes io_processors for <send> (objects whose receive gets a Send; Spawner spawns for a chart), services for <invoke> (an Invocation), log for <log> (a LogEntry), on_done and on_error for actors that end. A plain function handler gets a thin view, valid until its batch is acknowledged; an async def handler gets a record it can keep.

<a id="Spawner"></a>

#### `Spawner` (class)

```python
class Spawner
```

An I/O processor that spawns actors for charts: give it to the host under a type you name, io_processors={"spawn": tinyactors.Spawner()}, and a chart spawns with <send type="spawn" event="spawn"> whose data is {"chart": name, "name": name or None, "params": dict or None}.

The new actor runs the chart's current version (Host.spawn) under the name. The sender gets `spawned` with {"name", "address"} (the new actor's session address) and the send's sendid, so a <send id> matches its answer; an unknown chart, data of another shape or a spawn the host refuses gives the sender error.communication instead. A type no processor serves stays error.execution, as SCXML has it.

It spawns; it does not look names up. A name has one owner, the collection actor that decides which actors of a kind exist, and that actor records the spawns it asked for, so it never asks twice for a name. Spawning under a name an older version's actor holds, after add_image of a new version, is how an application updates.

<a id="Spawner.receive"></a>

##### `Spawner.receive`

```python
receive(send)
```

Spawn what send.data asks for and answer `spawned`, or fail the send (error.communication) when the host cannot.

<a id="Invocation"></a>

#### `Invocation` (class)

```python
class Invocation
```

A service your application runs, as one actor invoked it.

An <invoke type=T> in a state starts it: the services= handler for T gets this record and returns the service object, which may have receive(send) for the sends to it (to #_<invokeid>, or autoforwarded events) and stop() for when the invoker leaves the state. Keep the record to answer: send_back() gives the invoker an event, done() ends the service with done.invoke.<invokeid>. Once it is done, cancelled or failed, answers raise TinyactorsError (TA_ERROR_STALE). A service that fails to start or whose receive raises gives its invoker error.communication.

<a id="Invocation.send_back"></a>

##### `Invocation.send_back`

```python
send_back(event, data=None, *, traceparent=invocation.traceparent)
```

Give the invoking actor an event from the service, with its invokeid set. Call it whenever the service has something to say, as long as it runs.

<a id="Invocation.done"></a>

##### `Invocation.done`

```python
done(data=None, *, traceparent=invocation.traceparent)
```

End the service: the invoker gets done.invoke.<invokeid> with `data`, and the service is dropped (not stopped). Later answers raise.

<a id="Invocation.session"></a>

##### `Invocation.session`

```python
session
```

The invoking actor's session id (int).

<a id="Invocation.invokeid"></a>

##### `Invocation.invokeid`

```python
invokeid
```

The <invoke>'s id: events from the service carry it as _event.invokeid.

<a id="Invocation.type"></a>

##### `Invocation.type`

```python
type
```

The <invoke>'s type: the key of the services= handler that started it.

<a id="Invocation.src"></a>

##### `Invocation.src`

```python
src
```

The <invoke>'s src (str or None), e.g. a URL the service should use.

<a id="Invocation.data"></a>

##### `Invocation.data`

```python
data
```

The <invoke>'s params (a dict) or content, as a Python value.

<a id="Invocation.traceparent"></a>

##### `Invocation.traceparent`

```python
traceparent
```

The invoking step's trace as W3C text, or None: answers keep it by default.

<a id="Invocation.running"></a>

##### `Invocation.running`

```python
running
```

True until the service is done, cancelled, failed or the host closed.

<a id="Invocation.restored"></a>

##### `Invocation.restored`

```python
restored
```

True when the host was restored (Host.restore) with this invocation running: the handler starts the service again, with the same invokeid, src and params. A copy that must not reach the real service registers a stand-in for the type.

<a id="Invocation.host"></a>

##### `Invocation.host`

```python
host
```

The Host this came from: the handlers get no host, so use this one to make inputs.

<a id="Send"></a>

#### `Send` (class)

```python
class Send
```

A <send> to one of your I/O processors, given to its receive(send).

Read what you need (event, data, target), do the I/O, and answer the sending actor with answer(), or report a failure with fail(); sender is the sending Actor and host the Host. A plain function gets a thin view: its fields are read on first use and valid until the host acknowledges the batch, so answer before returning or copy what you need. An async def handler gets a record whose answer() and fail() work later. A send to an invoked service (to #_<invokeid>) reaches the service's receive(send) as the same view, its type None.

<a id="Send.answer"></a>

##### `Send.answer`

```python
answer(event, data=None, *, traceparent=send.traceparent, origin=None,
       raw=None)
```

Give the sending actor an event in reply, with this send's sendid and the processor's type as origintype. The reply keeps the send's trace; pass traceparent=None to start a new one. `origin` (a str) becomes _event.origin, where the actor replies to. `raw` (a str) becomes _event.raw, the message as the transport carried it: an HTTP processor passes the request it read. To answer after the batch is acknowledged, write the handler as async def, which gets a record.

Returns True when the reply was delivered, and False when the sending actor ended meanwhile: nobody is told, and nothing raises. Any other refusal raises TinyactorsError.

<a id="Send.fail"></a>

##### `Send.fail`

```python
fail()
```

Report that the send could not be delivered: the sending actor gets error.communication with this send's sendid. A handler that raises before answering is failed this way for you.

Returns True when the failure was delivered, and False when the sending actor ended meanwhile, as answer() does.

<a id="Send.session"></a>

##### `Send.session`

```python
session
```

The sending actor's session id (int).

<a id="Send.sendid"></a>

##### `Send.sendid`

```python
sendid
```

The <send>'s sendid (str or None): answers and failures carry it back.

<a id="Send.event"></a>

##### `Send.event`

```python
event
```

The event's name (str).

<a id="Send.target"></a>

##### `Send.target`

```python
target
```

The <send>'s target: for the transport, another system's Address (its .system names the connection to use); for an I/O processor, the text the chart wrote (str or None).

<a id="Send.data"></a>

##### `Send.data`

```python
data
```

The event's data as a Python value: for a "python" chart the value itself (no copy), for quickjs decoded on first read.

<a id="Send.traceparent"></a>

##### `Send.traceparent`

```python
traceparent
```

The sending step's trace as W3C text, None when untraced: put it in your outgoing request's traceparent header to continue the trace.

<a id="Send.type"></a>

##### `Send.type`

```python
type
```

The I/O processor's type from the config (None for the transport or an invoked service).

<a id="Send.origin"></a>

##### `Send.origin`

```python
origin
```

The sending actor's Address, tinyactors://<systemID>/#_scxml_<session>: what a transport hands the other system, whose Host.send takes it as origin so a reply finds its way back.

<a id="Send.message"></a>

##### `Send.message`

```python
message
```

The outgoing half of a send to another system, as a dict: target, event, data, sendid, origin and traceparent. Encode it for your wire (tinyactors.encode, or your own) and give it to the other host's Host.send(message) unchanged: no field is lost on the way, and the keys are the same in every binding. Read it inside the handler: a thin view's fields end at the batch's ack, the dict does not.

Part of the wire format (the README's "Wire format").

<a id="Send.sender"></a>

##### `Send.sender`

```python
sender
```

The sending actor, an Actor of send.session: answer it later with sender.send(), or keep it to reach the actor again.

<a id="Send.host"></a>

##### `Send.host`

```python
host
```

The Host this came from: the handlers get no host, so use this one to make inputs.

<a id="LogEntry"></a>

#### `LogEntry` (class)

```python
class LogEntry
```

A <log> line of an actor, given to the log handler.

A chart's <log label="..." expr="..."/> is how it reports what it does; the handler decides where that goes: Python's logging module, stdout, a test's list. Read session, label and text inside the handler: it is a thin view, valid until the batch's ack.

<a id="LogEntry.session"></a>

##### `LogEntry.session`

```python
session
```

The logging actor's session id (int).

<a id="LogEntry.label"></a>

##### `LogEntry.label`

```python
label
```

The <log>'s label (str, empty when none).

<a id="LogEntry.text"></a>

##### `LogEntry.text`

```python
text
```

The <log>'s evaluated expression, as text.

<a id="LogEntry.host"></a>

##### `LogEntry.host`

```python
host
```

The Host this came from: the handlers get no host, so use this one to make inputs.

<a id="memory"></a>

### Memory

Host(store=SQLiteStore(path), resident=N) keeps at most N actors in memory and the rest hibernated in the store, woken when an event comes for one. The store is not durability: keeping data is your database's job.

<a id="SQLiteStore"></a>

#### `SQLiteStore` (class)

```python
class SQLiteStore
SQLiteStore(path)
```

A store of hibernated actors' blobs in an SQLite database file, one row per actor in the table tinyactors_blobs (session, blob): what Host(store=..., resident=N) uses to keep at most N actors in memory and the rest on disk.

`path` is the database file (":memory:" for none). It is a cache of the host's actors, not their durability: a host's blobs wake only in that host or a host restored from its snapshot, so keep the file with the snapshot when you keep one. Call close() when the host is closed.

<a id="SQLiteStore.save"></a>

##### `SQLiteStore.save`

```python
save(session, blob)
```

Keep `blob`, the hibernated actor `session`'s bytes, replacing an earlier one (one row per session).

<a id="SQLiteStore.load"></a>

##### `SQLiteStore.load`

```python
load(session)
```

The blob saved for `session`; KeyError when there is none (the host reports it, and the actor stays hibernated).

<a id="SQLiteStore.delete"></a>

##### `SQLiteStore.delete`

```python
delete(session)
```

Forget `session`'s blob: the actor was woken, or it ended. One that is not there is nothing to do.

<a id="SQLiteStore.close"></a>

##### `SQLiteStore.close`

```python
close()
```

Close the database connection; the file keeps the blobs saved.

<a id="SQLiteStore.connection"></a>

##### `SQLiteStore.connection`

```python
connection
```

<a id="MemoryStore"></a>

#### `MemoryStore` (class)

```python
class MemoryStore
MemoryStore()
```

A store of hibernated actors' blobs in a dict: Host(store=...) saves an actor's blob here when it hibernates the actor, loads it when an event comes for it, and deletes it once the actor is back or ended.

Use it in tests, and where the host's memory, not the process's, is what must stay small: the blobs are bytes in this process. For blobs that leave memory use SQLiteStore, or your own object with the same three methods.

<a id="MemoryStore.save"></a>

##### `MemoryStore.save`

```python
save(session, blob)
```

Keep `blob`, the hibernated actor `session`'s bytes, replacing an earlier one.

<a id="MemoryStore.load"></a>

##### `MemoryStore.load`

```python
load(session)
```

The blob saved for `session`; KeyError when there is none (the host reports it, and the actor stays hibernated).

<a id="MemoryStore.delete"></a>

##### `MemoryStore.delete`

```python
delete(session)
```

Forget `session`'s blob: the actor was woken, or it ended. One that is not there is nothing to do.

<a id="MemoryStore.blobs"></a>

##### `MemoryStore.blobs`

```python
blobs
```

<a id="values"></a>

### Values

Actors exchange int, float, str, bytes, list, dict with str keys, bool, None, UNDEFINED and Address, as Python objects.

<a id="Address"></a>

#### `Address` (class)

```python
class Address
Address(text, /)
```

An actor's address as a value (CBOR tag 32), kept apart from plain text.

Charts and other programs pass addresses as data (a reply-to, a subscriber list); when such a value comes from an ECMAScript chart or another process it arrives as an Address, and an Address you put in data reaches them as one. Host.send and Host.fail take one as a target. `text` must be an exact str of valid UTF-8; the constructor does not check it. Use .text or str(value) to read it, and .system, .session and .name for its parts, which core's address parser reads. Equality and hashing use the text, among Address values only; subclasses are refused.

Part of the wire format (the README's "Wire format").

<a id="Address.from_name"></a>

##### `Address.from_name`

```python
Address.from_name(system, name)
```

The Address of the actor named `name` in system `system`: "tinyactors://<system>/@<name>", the name percent-encoded, so any name ("rooms/acme", "café") is one address and .name gives it back. A chart that targets the actor writes this text; ValueError for an invalid system id or an empty name.

<a id="Address.from_session"></a>

##### `Address.from_session`

```python
Address.from_session(system, session)
```

The Address of session `session` (an int from 1) in system `system`: "tinyactors://<system>/#_scxml_<session>", the full form (a chart sees that session's _event.origin in it or as its fragment, #_scxml_<session>, so compare by the fragment); ValueError for an invalid system id.

<a id="Address.text"></a>

##### `Address.text`

```python
text
```

The address text (read-only).

<a id="Address.system"></a>

##### `Address.system`

```python
system
```

The system id of tinyactors://<system>/...: which system, so which connection of your transport (None when the text is no address).

<a id="Address.session"></a>

##### `Address.session`

```python
session
```

The session id of a .../#_scxml_<id> address (an int), or None.

<a id="Address.name"></a>

##### `Address.name`

```python
name
```

The decoded name of a .../@<name> address (a str), or None.

<a id="UNDEFINED"></a>

#### `UNDEFINED` (const)

```python
UNDEFINED: Undefined
```

The value table's undefined, distinct from None (null): what an ECMAScript chart's undefined becomes in Python, and how to send one. There is one, tinyactors.UNDEFINED; compare with `is`.

<a id="errors"></a>

### Errors

The host raises TinyactorsError (StaleError, StateError, ...), whose status names the core's status. A failed compilation raises CompileError with every Diagnostic.

<a id="TinyactorsError"></a>

#### `TinyactorsError` (class)

```python
class TinyactorsError(Exception)
TinyactorsError(message='', code=None, reason=None, path=None, status=None, *rest, **named)
```

An error the core reported, the one exception type the host raises for its own reasons.

It comes from a call the host refused (a full pool, a closed host, a session that does not exist), from a thin view read after its batch was acknowledged, from a fault of a run, or as a typed method's error (given to on_error, or raised by the driver without one). Branch on `status`, the core's name for a bare status ("TA_ERROR_STALE", "TA_ERROR_STATE", ...); a typed method's error also has `code`, `reason`, `path` and `message` as the host's reply wrote them. MemoryError is raised instead when the host ran out of a pool its config sized.

<a id="StaleError"></a>

#### `StaleError` (class)

```python
class StaleError(TinyactorsError)
```

An actor, session, view or handle that does not exist (any more): a send to a session or name that ended, a thin view read after its batch was acknowledged, a typed method's "stale" error. Its status is "TA_ERROR_STALE".

<a id="StateError"></a>

#### `StateError` (class)

```python
class StateError(TinyactorsError)
```

A call the host cannot make now: a closed host, a snapshot from a handler or with a reply pending, a typed method's "state" error. Its status is "TA_ERROR_STATE".

<a id="CompileError"></a>

#### `CompileError` (class)

```python
class CompileError(TinyactorsError)
CompileError(message, diagnostics)
```

compile_charts or compile_system found an error in the documents.

`diagnostics` is every Diagnostic of the compilation (errors, warnings and notes, each with its file, line and column), so an editor integration, a build step or a test can show them all at once; str() of the error names the first. Nothing was compiled: fix the documents and compile again. Catch it where charts are compiled (at startup, in a build or deploy step), not around the host, which never raises it.

<a id="Diagnostic"></a>

#### `Diagnostic` (class)

```python
class Diagnostic
Diagnostic(severity, code, file, line, column, message)
```

One message of the compiler about a document: in Compiled.diagnostics (warnings and notes of a compilation that succeeded) and CompileError.diagnostics. Show them where a person edits charts (a terminal, an editor, a CI log) or assert on them in a test.

`severity` is "error", "warning" or "note", `code` the compiler's code for the kind of problem, `file`, `line` and `column` where it is (the source's name as given to compile_charts), `message` the text. repr() reads like a compiler's output line.

<a id="Diagnostic.code"></a>

##### `Diagnostic.code`

```python
code
```

<a id="Diagnostic.column"></a>

##### `Diagnostic.column`

```python
column
```

<a id="Diagnostic.file"></a>

##### `Diagnostic.file`

```python
file
```

<a id="Diagnostic.line"></a>

##### `Diagnostic.line`

```python
line
```

<a id="Diagnostic.message"></a>

##### `Diagnostic.message`

```python
message
```

<a id="Diagnostic.severity"></a>

##### `Diagnostic.severity`

```python
severity
```

<a id="InvalidError"></a>

#### `InvalidError` (class)

```python
class InvalidError(TinyactorsError)
```

An argument the host refused: a malformed config, image or address, a typed method's param of the wrong type or out of range. Its status is "TA_ERROR_INVALID".

<a id="UnsupportedError"></a>

#### `UnsupportedError` (class)

```python
class UnsupportedError(TinyactorsError)
```

A value or a feature the host does not take: a value outside the value table, a session that cannot hibernate. Its status is "TA_ERROR_UNSUPPORTED".

<a id="ResolveError"></a>

#### `ResolveError` (class)

```python
class ResolveError(TinyactorsError)
ResolveError(message, line=None, column=None)
```

Raise it from a resolver, resolver(base, source), to refuse a document a chart references with src=: not found, not allowed (a path outside the directory your charts live in), not valid.

A resolver is how charts that are split over files get compiled: the compiler calls it for each static src= it does not have among the sources. Raising ResolveError makes the refusal a diagnostic like any other, at `line` and `column` when given (a resolver that checks a file's content knows where it is wrong), so compile_charts or compile_system raises CompileError with it among the others. Any other exception a resolver raises is a bug in the resolver and propagates from the compile call.

<a id="operating-a-host"></a>

## Operating a host

Host.add_image and chart for new images and versions, compile_system and Host.boot, telemetry= and metrics(), the typed methods trace_*, Host.sweep(), hibernate() and wake() for a policy of your own, Host.migrate() with migrated= and migration_done=, Host.snapshot() and Host.restore().

<a id="compile_system"></a>

#### `compile_system` (function)

```python
compile_system(manifest, resolver=None)
```

Compile a system manifest into one image: its charts and the actors it starts with.

`manifest` is a (name, text) pair whose text is a <system> document: <chart name="worker" src="worker.scxml"/> for each chart, read through `resolver` (as for compile_charts), and <actor name="first" chart="worker"/> for each actor Host.boot spawns, under that name.

Use it when an application is a fixed set of long-lived actors (a router, a scheduler, a few workers): the manifest says what runs, so a deploy is one image to add and boot, and your program finds each actor by name (Host.actor("first"), or the address .../@first). Use compile_charts when your program spawns its actors itself, one per order or user. Returns a Compiled, as compile_charts does; an error raises CompileError with every diagnostic.

Part of operating a host (the README's "Operating a host").

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

## Wire format

transport= and send.message for other systems, Host.send(message) and Host.fail(), Address, encode() and decode() for values that leave the process, and decode_traces().

<a id="encode"></a>

#### `encode` (function)

```python
encode(value, /)
```

Encode one Python value as CBOR bytes of the value table.

Use it where a value crosses a process boundary: a config written to a file, a message for another system, a value another program decodes. Values you pass to a Host in this process (send, spawn's params, a service's data) need no encoding: they cross as Python objects.

Supported: exact built-in int (-2**64 through 2**64-1), float, str, bytes, list, dict with str keys, plus bool, None, Address and UNDEFINED. Address keeps tag 32; UNDEFINED keeps undefined, inside containers too. Container order is kept. Subclasses and tuples are not supported.

Raises TypeError for unsupported types or non-str map keys, OverflowError for integers or text outside core's length range, UnicodeError for lone surrogates, ValueError for excessive nesting (cycles included), and MemoryError on allocation failure.

Part of the wire format (the README's "Wire format").

<a id="decode"></a>

#### `decode` (function)

```python
decode(data, /)
```

Decode exactly one CBOR item of the value table from bytes.

The inverse of encode, for values that arrive from another process. Arrays become lists, maps become dicts with str keys (a repeated key keeps its last value), tag 32 on text becomes Address, undefined becomes UNDEFINED. Other tags and simple values are refused.

Raises TypeError for input other than bytes, ValueError for malformed, truncated, trailing or unsupported CBOR, and MemoryError on allocation failure.

Part of the wire format (the README's "Wire format").

<a id="decode_traces"></a>

#### `decode_traces` (function)

```python
decode_traces(data)
```

The spans of an OTLP ExportTraceServiceRequest, read without a host: the bytes a telemetry handler gets for "traces", or any exporter's.

Each span is a dict: trace, span and parent (lowercase hex; parent None for a root span), name, kind, start and end (nanoseconds since the Unix epoch), status, statusMessage, flags, attributes, events (each {name, time, attributes}), links (each {trace, span, attributes}), resource (its attributes) and scope ({name, version, attributes}). Use it in tests and in a collector of your own; bytes that are not such a request raise InvalidError.

Part of the wire format (the README's "Wire format").

<a id="others"></a>

### More of the module

<a id="Event"></a>

#### `Event` (class)

```python
class Event
```

_event in a "python" chart: the event being processed.

Conditions and actions read it: cond="_event.data['amount'] > 100", expr="_event.origin" to reply. It is immutable and stays bound until the next event, as SCXML requires. Fields that do not apply are None.

<a id="Event.name"></a>

##### `Event.name`

```python
name
```

The event's name, e.g. "order.paid" or "done.invoke.payment".

<a id="Event.type"></a>

##### `Event.type`

```python
type
```

"platform" (errors, done events), "internal" (<raise>) or "external".

<a id="Event.sendid"></a>

##### `Event.sendid`

```python
sendid
```

The id of the <send> that produced it (str), or None: what an answer or an error.communication carries back to match the request it is about.

<a id="Event.origin"></a>

##### `Event.origin`

```python
origin
```

The sender's address, or None: <send target="..." targetexpr="_event.origin"> replies to it, in this host or in another system. One sender of this system comes full (tinyactors://<system>/#_scxml_<n>) or as its fragment (#_scxml_<n>): key a table by the fragment.

<a id="Event.origintype"></a>

##### `Event.origintype`

```python
origintype
```

The I/O processor type of the origin, or None: the type a reply uses to go back the way the event came.

<a id="Event.invokeid"></a>

##### `Event.invokeid`

```python
invokeid
```

The invokeid when the event came from an invoked child or service, or None.

<a id="Event.data"></a>

##### `Event.data`

```python
data
```

The event's data as a Python value, or None.

<a id="Event.raw"></a>

##### `Event.raw`

```python
raw
```

The message as the I/O processor read it (an HTTP request, say), or None: for a chart that needs more than the event's data.
