A host: the object that holds actors and runs their charts, many actor systems as one.
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.
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").
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").
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.
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.
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.
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.
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").
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.
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.
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").
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").
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").
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").
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").
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").
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").
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").
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.
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.
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.
__enter__()
Enter the synchronous driver: returns the host; refuses an async def handler (use async with).
__exit__(...)
Leave the synchronous driver: closes the host.
__aenter__()
Enter the asyncio driver: the host turns on the running event loop.
__aexit__(...)
Leave the asyncio driver: awaits the handlers' tasks, then closes the host.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
system
The host's system id (the config's systemID), the authority of its actors' addresses.
closed
True once the host was freed (close(), the end of a with block); every call refuses then.
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).
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.