Python SDK

API reference for the iii SDK for Python.

Link to this sectionInstallation

Terminal
pip install iii-sdk

Link to this sectionInitialization

Link to this sectionregister_worker

Register the worker with a iii instance, returns a connected worker client.

Blocks up to 30 seconds for the WebSocket connection to be established. If the engine is not reachable in time, a warning is logged and the client is returned anyway; it keeps retrying in the background and flushes registrations once connected. Use add_connection_state_listener to observe the actual transition.

Signature

register_worker(address: str | None = None, options: InitOptions | None = None) -> III
addressstr | None

WebSocket URL of the III engine (e.g. ws://localhost:49134). When omitted, resolves from III_URL and then DEFAULT_ENGINE_URL.

optionsInitOptions | None

Optional configuration for worker name, timeouts, reconnection, and OTel.

Show `InitOptions` fields
enable_metrics_reportingbool

Enable worker metrics via OpenTelemetry. Default True.

headersdict[str, str] | None

Custom HTTP headers sent during the WebSocket handshake, on the main connection and on streaming channels. Authorization: Bearer $III_TOKEN is added unless you set Authorization here.

invocation_timeout_msint

Default timeout for worker.call() invocations in milliseconds. Default 30000.

namespacestr | None

Namespace this worker belongs to. Falls back to the III_NAMESPACE env var; when neither is set the engine applies default. It scopes more than the registration: the worker and its functions register here, and everything the worker does afterwards follows it: call resolves its target here and observe resolves its source and target here, unless the call names another namespace.

otelOtelConfig | dict[str, Any] | None

OpenTelemetry configuration. Enabled by default. Set {'enabled': False} or env OTEL_ENABLED=false to disable.

reconnection_configReconnectionConfig | None

WebSocket reconnection behavior.

telemetryTelemetryOptions | None

Internal worker metadata reported to the engine.

worker_descriptionstr | None

One-line, human/LLM-readable summary of what this worker does. Surfaces in engine::workers::list / engine::workers::info.

worker_namestr | None

Display name for this worker. A non-empty III_WORKER_NAME overrides it. Defaults to hostname:pid.

Link to this sectionMethods

Link to this sectionregister_function

Register a function with the engine.

Pass a handler for local execution, or an HttpInvocationConfig for HTTP-invoked functions (Lambda, Cloudflare Workers, etc.). Passing an HttpInvocationConfig emits a FutureWarning: HTTP-invoked functions are deprecated (iii-http-functions). Register a handler that makes the HTTP call instead.

Handlers can be synchronous or asynchronous. Sync handlers are automatically wrapped with run_in_executor so they do not block the event loop. Each handler receives a data argument containing the call's payload, and may optionally accept a second metadata argument carrying per-invocation metadata (e.g. def handler(data, metadata=None) or def handler(data, *, metadata=None)). Metadata is only forwarded to handlers that declare a parameter literally named metadata, so existing handlers, including ones with unrelated extra parameters, *args, or **kwargs, keep working unchanged.

The handler's return value is what the function's observers observe. An event source's handler returns the event it is called with. What this worker does when the function is observed is set with the hook methods (on_observer_added, on_observer_removed, on_observation_match, on_observation_deliver) on the client by id or on the returned FunctionRef. Set on_observer_added and on_observer_removed by id before registering so they run for every observer: the engine may announce an observer before a hook set on the FunctionRef is in place.

request_format and response_format are auto-extracted from the handler's type hints when omitted or passed as None (the default). To opt out of auto-extraction, pass an explicit schema (RegisterFunctionFormat or dict). This behavior is Python-specific; the Node SDK relies on explicit schemas because TypeScript types are erased at runtime.

Signature

register_function(function_id: str, handler_or_invocation: RemoteFunctionHandler | HttpInvocationConfig, *, description: str | None = None, metadata: dict[str, Any] | None = None, request_format: RegisterFunctionFormat | dict[str, Any] | None = None, response_format: RegisterFunctionFormat | dict[str, Any] | None = None, args_format: Any = None, private: bool = False, observable: bool = True, local_dispatch: bool = True) -> FunctionRef
function_idstrrequired

Unique string identifier for the function.

handler_or_invocationRemoteFunctionHandler | HttpInvocationConfigrequired

A callable handler or HttpInvocationConfig. Callable handlers receive data (the call's payload) as the first argument and may optionally accept metadata (per-invocation metadata) as a second argument; they may return a value.

descriptionstr | None

Human-readable description of what the function does.

metadatadict[str, Any] | None

Arbitrary metadata attached to the function.

request_formatRegisterFunctionFormat | dict[str, Any] | None

Schema describing expected input. When None (default), auto-extracted from the handler's first-parameter type hint. Pass an explicit schema to override; there is no way to register with no schema when the handler is typed.

Show `RegisterFunctionFormat` fields
bodylist[RegisterFunctionFormat] | None

Nested fields for object types.

descriptionstr | None

Human-readable description of the parameter.

itemsRegisterFunctionFormat | None

Item schema for array types.

namestrrequired

Parameter name.

requiredbool

Whether the parameter is required.

typestrrequired

Type string (string, number, boolean, object, array, null, map).

response_formatRegisterFunctionFormat | dict[str, Any] | None

Schema describing the handler's return value, what observers observe. Same auto-extraction semantics as request_format.

args_formatAny

JSON Schema (or a Pydantic model) of the observers' args; the engine validates them (INVALID_ARGS). A function without it takes no args.

privatebool

Only this worker may call the function; others may observe it. This worker's own calls pass the input and the result by reference: the handler and hooks treat both as read-only.

observablebool

False: nobody may observe the function (NOT_OBSERVABLE), for functions whose payloads carry credentials.

local_dispatchbool

Calls this worker makes to its own function run in-process once the engine confirmed it (default True). Like a remote invocation, each local call to a sync handler runs on a thread of its own (one per call, not pooled), so the caller can stop waiting at its timeout. A sync handler that blocks for long should be async, or set False so its calls go through the engine (also for a handler that relies on engine-side effects).


Link to this sectioncall

Call a function and return its result.

The routing behavior and return type depend on the action field:

  • No action: synchronous, waits for the function to return.
  • CallAction.Enqueue(...): async via named queue, returns a dict with messageReceiptId.
  • CallAction.Void(): fire-and-forget, returns None.

A function this worker registered with a handler, once the engine confirmed it, runs in-process (local dispatch): a sync handler on a thread of its own (the caller waits up to the timeout), an async one on the SDK loop. Its observers are still delivered to, and only matched calls reach the engine. dispatch="remote" (or action=Enqueue) always goes through the engine. Whatever a local handler raises, BaseExceptions such as KeyboardInterrupt and SystemExit included, reaches the caller as InvocationError("invocation_failed") with the original as its __cause__ (for a Void call nothing reaches the caller: the error is logged).

metadata is any JSON value; the handler receives it beside the payload, and None is no metadata.

A request with observer (an Observer of a function this worker hosts) calls through it: the engine runs the observer's target with its policy (max_fires, expiry, max_in_flight), metadata sidecar and loop guard, and the call resolves to the target's result. It takes no metadata: the target's metadata argument is the observer's registration metadata, and a request that names metadata raises ValueError before anything is sent. The payload goes as given: filters are applied where the worker chooses observers: iii's delivery, or obs.matches(call) in an on_observation_deliver. A host also calls through an observer to send it something of its own, such as its initial state once it is accepted (see Observer.accepted).

Signature

call(request: dict[str, Any] | CallRequest) -> Any
requestdict[str, Any] | CallRequestrequired

A CallRequest or dict with function_id (or observer), payload, and optional action / timeout_ms / metadata / namespace / dispatch ("auto", the default, or "remote").

Show `CallRequest` fields
actionCallActionEnqueue | CallActionVoid | None

Sets how the call is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. CallAction.Enqueue(...), CallAction.Void()).

dispatchLiteral['auto', 'remote'] | None

auto (default) runs a function this worker hosts in-process once the engine confirmed it; remote always goes through the engine.

function_idstr | None

ID of the function to call.

metadataAny | None

Per-invocation metadata (any JSON value) supplied to the called handler beside the payload. None is no metadata.

namespacestr | None

Target namespace for routing. Omit to inherit this worker's; say default to reach the engine's from a namespaced worker.

observerAny

An Observer of a function this worker hosts: the call runs its target, with its policy and metadata sidecar. Takes no function_id, namespace, metadata or enqueue action.

payloadAny

Input data passed to the function.

timeout_msint | None

Override the default invocation timeout, in milliseconds.


Link to this sectionobserve

Observes a function: when source runs, target runs. Every call of the source function that passes source["filters"] invokes target, a registered function, with the Observed payload: the top-level fields plus what source["capture"] names that applies to the outcome (input, output or error, caller, metadata). capture also decides which outcomes fire the target. The worker that hosts the source can decide otherwise in its on_observation_deliver.

Returns synchronously, also before the connection is up; the observer is replayed with the same id on every reconnect. The handle holds its id until its dispose() is called or the engine disposes it; the id is free again at once after that. An observer without max_fires or expires_in_ms that the engine disposed because this worker was away past its grace period (OBSERVER_DISCONNECTED) is not: it is observed again, with the same id, and goes pending. Errors (INVALID_ARGS, INVALID_FILTER, FORBIDDEN, NOT_OBSERVABLE, the rejection of the source's worker, UNSUPPORTED against an engine without observe) show up as state error and make ready() raise ObserveRejection. An error answer to the handle's observe or to its replay after a reconnect is the engine's refusal and the handle's final answer: the engine holds no observer for it, it is not replayed, it holds its id until its dispose(), and that dispose() sends nothing. An observer that moves to error after its answer stays held: it is replayed, and its dispose() sends an unobserve.

Signature

observe(source: str | ObserveSource | dict[str, Any], target: Target, options: ObserverOptions | dict[str, Any] | None = None) -> ObserverHandle
sourcestr | ObserveSource | dict[str, Any]required

What is observed: a function id, or function_id, namespace, args (read by the worker that hosts the function, validated against its args_format), filters, and capture.

Show `ObserveSource` fields
function_idstrrequired

The observed function.

argsdict[str, Any]

For the worker that hosts the function, which reads them in its hooks; validated against the function's args_format. A function without args_format takes none.

capturelist[Capture]

What the target's payload carries, and with it which outcomes fire the target. Default ["input", "output", "caller"]. input and output fire on success, error fires on error; caller and metadata only add to the payload, so a capture must name at least one of input, output, error (INVALID_ARGS otherwise). [] fires on success with the top-level fields only. The default fires on success, ["error", "caller"] on errors, ["input", "error"] on both.

filtersFilter

Which calls reach the target; {} (or absent) = every call.

namespacestr

Defaults to this worker's (engine::* and configuration::* resolve to default).

targetTargetrequired

The function to invoke: its id, or {"function_id": ..., "namespace": ...}. Register it first; until then the observer stays pending.

optionsObserverOptions | dict[str, Any] | None

id, max_fires, expires_in_ms, max_in_flight, metadata (the activation's metadata sidecar).

Show `ObserverOptions` fields
expires_in_msint

Disposed after this long.

idstr

Default: a random UUID, stable across replays.

max_firesint

Disposed after this many activations.

max_in_flightint

Activations running at once (the engine queues the rest).

metadatadict[str, Any]

Delivered as the metadata sidecar of every activation.


Link to this sectiontrigger

Call a function: call under its 0.25 name.

Signature

trigger(request: dict[str, Any] | CallRequest) -> Any

Link to this sectionParameters

requestdict[str, Any] | CallRequestrequired
Show `CallRequest` fields
actionCallActionEnqueue | CallActionVoid | None

Sets how the call is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. CallAction.Enqueue(...), CallAction.Void()).

dispatchLiteral['auto', 'remote'] | None

auto (default) runs a function this worker hosts in-process once the engine confirmed it; remote always goes through the engine.

function_idstr | None

ID of the function to call.

metadataAny | None

Per-invocation metadata (any JSON value) supplied to the called handler beside the payload. None is no metadata.

namespacestr | None

Target namespace for routing. Omit to inherit this worker's; say default to reach the engine's from a namespaced worker.

observerAny

An Observer of a function this worker hosts: the call runs its target, with its policy and metadata sidecar. Takes no function_id, namespace, metadata or enqueue action.

payloadAny

Input data passed to the function.

timeout_msint | None

Override the default invocation timeout, in milliseconds.


Link to this sectionadd_connection_state_listener

Subscribe to connection-state transitions.

The handler is fired immediately with the current state (on the caller's thread), then once per transition. Transitions fire on the SDK's background event-loop thread: keep handlers fast and do not call sync SDK methods from them (they would raise RuntimeError). Treat calls as state notifications, not edges. A state may rarely be observed twice around subscription. Registering the same handler twice fires it twice. Returns an idempotent unsubscribe function that removes only its own registration.

Signature

add_connection_state_listener(handler: ConnectionStateCallback) -> Callable[[], None]
handlerConnectionStateCallbackrequired

Link to this sectioncall_async

Call a function and return its result (on any event loop).

The routing behavior and return type depend on the action field:

  • No action: synchronous, waits for the function to return.
  • CallAction.Enqueue(...): async via named queue, returns a dict with messageReceiptId.
  • CallAction.Void(): fire-and-forget, returns None.

A function this worker registered with a handler, once the engine confirmed it, runs in-process on the calling loop (a sync handler on a thread of its own); dispatch="remote" (or action=Enqueue) always goes through the engine. A request with observer calls through it, as for call.

Signature

async (request: dict[str, Any] | CallRequest) -> Any
requestdict[str, Any] | CallRequestrequired

A CallRequest or dict with function_id (or observer), payload, and optional action / timeout_ms / metadata / namespace / dispatch ("auto" or "remote").

Show `CallRequest` fields
actionCallActionEnqueue | CallActionVoid | None

Sets how the call is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. CallAction.Enqueue(...), CallAction.Void()).

dispatchLiteral['auto', 'remote'] | None

auto (default) runs a function this worker hosts in-process once the engine confirmed it; remote always goes through the engine.

function_idstr | None

ID of the function to call.

metadataAny | None

Per-invocation metadata (any JSON value) supplied to the called handler beside the payload. None is no metadata.

namespacestr | None

Target namespace for routing. Omit to inherit this worker's; say default to reach the engine's from a namespaced worker.

observerAny

An Observer of a function this worker hosts: the call runs its target, with its policy and metadata sidecar. Takes no function_id, namespace, metadata or enqueue action.

payloadAny

Input data passed to the function.

timeout_msint | None

Override the default invocation timeout, in milliseconds.


Link to this sectionconnect_async

Connect to the III Engine via WebSocket.

Initializes OpenTelemetry (if configured), attaches the event loop, and establishes the WebSocket connection. This is called automatically during construction; use it only if you need to reconnect manually from an async context.

Signature

async () -> None

Link to this sectioncurrent_invocation

The invocation the calling code runs in (in every handler, remote or local), or None outside any handler.

Signature

current_invocation() -> InvocationContext | None

Link to this sectionExample

def create_order(order):
    inv = iii.current_invocation()  # function_id, invocation_id, caller, observe_depth
    return {"id": inv.invocation_id if inv else None}

Link to this sectionget_address

Return the engine address this worker resolved to.

The explicit register_worker argument, else III_URL, else DEFAULT_ENGINE_URL. Mirrors the Rust SDK's address() and the Node SDK's getAddress().

Signature

get_address() -> str

Link to this sectionget_connection_state

Return the current WebSocket connection state.

Signature

get_connection_state() -> IIIConnectionState

Link to this sectionExample

worker = register_worker("ws://localhost:49134")
if worker.get_connection_state() != "connected":
    print("engine not reachable yet")

Link to this sectionis_observed

Whether a call of a function this worker hosts would reach anyone, so a source can skip building an event nobody wants.

Without call: whether the function has any active observer (one load). With call (a Call or a partial one, {"input": ...}) on a function matched by keys (on_observation_match): whether an observer is filed under one of the call's keys. On any other function the call is ignored.

Signature

is_observed(function_id: str, call: CallLike | None = None) -> bool
function_idstrrequired
callCallLike | None

Link to this sectionobservers

The active observers of a function this worker hosts, as it sees them.

Signature

observers(function_id: str) -> list[Observer]
function_idstrrequired

Link to this sectionon_observation_deliver

Delivers each call of one function itself: hook(call, observers) receives the Call and the observers that matched it (on_observation_match, or all of them), as a snapshot taken when the call started, and what it returns (or raises) is what the caller gets back. iii delivers nothing for that function: the hook calls through observers (iii.call({"observer": obs, ...})) and applies their capture and filters with obs.matches(call). Works as a decorator (@iii.on_observation_deliver("fn::id")) and returns the hook; None restores iii's delivery.

The hook runs inside the function's invocation, so the calls it makes have that invocation as their caller. A sync hook runs on a thread of its own. A function with a deliver hook needs an engine with observe.v2.

Signature

on_observation_deliver(function_id: str, hook: Any = ...) -> Any
function_idstrrequired
hookAny

Link to this sectionon_observation_match

Sets which observers want each call of one function. By default every observer wants every call; iii's delivery then applies their capture and filters, and an on_observation_deliver receives only the observers that matched.

As a predicate, hook(obs, call) -> bool is asked once per observation: for every call, once for each active observer, before its filters; a predicate that raises counts as no match for that observer. As keys, observer= and call= key functions each return a string or strings, and an observer wants a call when they share a key: the SDK computes an observer's keys once, when it is accepted, and files it under each, so a call costs one lookup per key whatever the number of observers. An observer whose key function raises is rejected (OBSERVE_REJECTED); a call whose key function raises matches no observer. A match hook that raises is logged once per function. Wildcards are keys too: file an observer of every table under "primary|*|insert" and give a change the keys "primary|orders|insert", "primary|orders|*", "primary|*|insert" and "primary|*|*".

Works as a decorator for a predicate (@iii.on_observation_match("fn::id")) and returns the hook (a MatchKeys for the keys form); None removes it, and every observer gets every call again. A match hook set while the function has active observers is applied to them on the SDK loop, which rebuilds the index from them. Predicates and key functions are sync: they run on every call. A function with a match hook needs an engine with observe.v2: against an older one it stays unregistered, and UNSUPPORTED is logged once.

Signature

on_observation_match(function_id: str, hook: Any = ..., *, observer: Any = None, call: Any = None) -> Any
function_idstrrequired
hookAny
observerAny
callAny

Link to this sectionon_observer_added

Sets what runs when an observer is added, before it is accepted: for every function this worker hosts (on_observer_added(hook)), or for one (on_observer_added("fn::id", hook)). Works as a decorator, @iii.on_observer_added or @iii.on_observer_added("fn::id"), and returns the hook; None removes it.

The worker's hook runs, then the function's; the observer is accepted (acked, then active) once both resolved. A hook that raises rejects the observer with the ObserveRejection it raised, or OBSERVE_REJECTED; one still running after 30 s rejects it with OWNER_TIMEOUT. Then the on_observer_removed of each level whose hook already resolved runs. Hooks may be sync (on a thread of their own) or async, and the hooks of one function run one at a time.

Hooks are stored by function id, so they can be set before the function is registered (which makes them run for every observer) and stay in place across unregister(). A hook set while the function already has active observers runs for each of them at once (a raise rejects that observer) and logs one warning. A second after the connection is registered, and after the last hook set by id, a warning names each hook id this worker has not registered.

Signature

on_observer_added(function_id_or_hook: Any, hook: Any = ...) -> Any
function_id_or_hookAnyrequired
hookAny

Link to this sectionon_observer_removed

Sets what runs when an accepted observer goes (on unobserve, on disposal, after a late rejection): for every function this worker hosts, or for one. The same forms as on_observer_added.

It runs exactly once for every accepted observer, the function's hook and then the worker's, and never for an observer that was not accepted. An error it raises is logged; the observer is removed either way.

Signature

on_observer_removed(function_id_or_hook: Any, hook: Any = ...) -> Any
function_id_or_hookAnyrequired
hookAny

Link to this sectionpipe

Create a pipe owned by this worker: .output to write, .input to read.

The explicit form of what a call does for each stream value. Pass one end in a call payload and use the other here; the worker that made the pipe stays connected until both ends attached. Blocks the calling thread; use pipe_async on an event loop.

Signature

pipe(buffer_size: int | None = None) -> Pipe
buffer_sizeint | None

Frames the engine buffers between the ends (its default when None).


Link to this sectionpipe_async

pipe on any event loop.

Signature

async (buffer_size: int | None = None) -> Pipe
buffer_sizeint | None

Link to this sectionregister_trigger

Removed in 0.26.0: raises an error that points to observe.

Signature

register_trigger(_args: Any = (), _kwargs: Any = {}) -> NoReturn

Link to this sectionParameters

_argsAny
_kwargsAny

Link to this sectionregister_trigger_type

Removed in 0.26.0: raises an error that points to register_function and the observer hooks.

Signature

register_trigger_type(_args: Any = (), _kwargs: Any = {}) -> NoReturn

Link to this sectionParameters

_argsAny
_kwargsAny

Link to this sectionshutdown

Gracefully shut down the client, releasing all resources.

Cancels any pending reconnection attempts, rejects all in-flight invocations with an error, closes the WebSocket connection, and stops the background event-loop thread. After this call the instance must not be reused.

Signature

shutdown() -> None

Link to this sectionExample

worker = register_worker('ws://localhost:49134')
# ... do work ...
worker.shutdown()

Link to this sectionshutdown_async

Gracefully shut down the client, releasing all resources.

Cancels any pending reconnection attempts, rejects all in-flight invocations with an error, closes the WebSocket connection, and stops the background event-loop thread. After this call the instance must not be reused.

Signature

async () -> None

Link to this sectionExample

worker = register_worker('ws://localhost:49134')
# ... do work ...
await worker.shutdown_async()

Link to this sectiontrigger_async

Call a function: call_async under its 0.25 name.

Signature

async (request: dict[str, Any] | CallRequest) -> Any

Link to this sectionParameters

requestdict[str, Any] | CallRequestrequired
Show `CallRequest` fields
actionCallActionEnqueue | CallActionVoid | None

Sets how the call is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. CallAction.Enqueue(...), CallAction.Void()).

dispatchLiteral['auto', 'remote'] | None

auto (default) runs a function this worker hosts in-process once the engine confirmed it; remote always goes through the engine.

function_idstr | None

ID of the function to call.

metadataAny | None

Per-invocation metadata (any JSON value) supplied to the called handler beside the payload. None is no metadata.

namespacestr | None

Target namespace for routing. Omit to inherit this worker's; say default to reach the engine's from a namespaced worker.

observerAny

An Observer of a function this worker hosts: the call runs its target, with its policy and metadata sidecar. Takes no function_id, namespace, metadata or enqueue action.

payloadAny

Input data passed to the function.

timeout_msint | None

Override the default invocation timeout, in milliseconds.


Link to this sectionunregister_trigger_type

Removed in 0.26.0: raises an error that points to FunctionRef.unregister.

Signature

unregister_trigger_type(_args: Any = (), _kwargs: Any = {}) -> NoReturn

Link to this sectionParameters

_argsAny
_kwargsAny

Link to this sectionTypes

Link to this sectioniii

Call · CallAction · CallActionEnqueue · CallActionVoid · Caller · EnqueueResult · InitOptions · InputStream · InvocationContext · MatchKeys · MiddlewareFunctionInput · Observed · Observer · ObserverHandle · ObserverOptions · ObserveSource · OutputStream · Pipe · StreamInfo · StreamRequest · StreamResponse · TelemetryOptions

Link to this sectionCall

One call of a function, as its observers observe it and its on_observation_match and on_observation_deliver hooks receive it.

NameTypeRequiredDescription
callerdict[str, Any] | NoneNoWho made the call: \{worker_id?, worker_name?, function_id?, invocation_id?, parent?\}; None outside any handler.
errordict[str, Any] | NoneNoWhat the handler raised, \{code, message, stacktrace?\} (None when it returned).
function_idstrYesThe called function.
inputInputTYesWhat the function was called with, as the caller passed it (channel refs as refs, not readers and writers).
invocation_idstrYesThis call's id.
metadataAnyNoThe call's metadata sidecar.
outputOutputT | NoneNoThe handler's return value: what observers observe (None when it raised).
statusLiteral['success', 'error']Yes"success" or "error".

Link to this sectionCallAction

Factory for creating call actions used with call().

NameTypeRequiredDescription
Enqueue(*, queue: str) -> CallActionEnqueueYesRoute the invocation through a named queue for async processing.
Void() -> CallActionVoidYesFire-and-forget routing. No response is returned.

Link to this sectionCallActionEnqueue

Routes the call through a named queue for async processing.

Requires the queue worker in worker-compose.yaml and a matching entry under that worker's queue_configs. Without it the call rejects with enqueue_error (no queue provider).

NameTypeRequiredDescription
queuestrYesName of the target queue.
typeLiteral['enqueue']NoAlways 'enqueue'.

Link to this sectionCallActionVoid

Fire-and-forget routing. No response is returned.

NameTypeRequiredDescription
typeLiteral['void']NoAlways 'void'.

Link to this sectionCaller

Who started an invocation: the worker (worker_id / worker_name, stamped by the engine), and the function and invocation the call was made from (absent for top-level calls). parent is that handler's own caller, one level only.

NameTypeRequiredDescription
function_idstrNo-
invocation_idstrNo-
worker_idstrNo-
worker_namestrNo-
parentCallerParentNo-

Link to this sectionEnqueueResult

Result returned when a function is called with CallAction.Enqueue.

NameTypeRequiredDescription
messageReceiptIdstrYesUnique receipt ID for the enqueued message.

Link to this sectionInitOptions

Configuration options passed to register_worker.

NameTypeRequiredDescription
enable_metrics_reportingboolNoEnable worker metrics via OpenTelemetry. Default True.
headersdict[str, str] | NoneNoCustom HTTP headers sent during the WebSocket handshake, on the main connection and on streaming channels. Authorization: Bearer $III_TOKEN is added unless you set Authorization here.
invocation_timeout_msintNoDefault timeout for worker.call() invocations in milliseconds. Default 30000.
namespacestr | NoneNoNamespace this worker belongs to. Falls back to the III_NAMESPACE env var; when neither is set the engine applies default. It scopes more than the registration: the worker and its functions register here, and everything the worker does afterwards follows it: call resolves its target here and observe resolves its source and target here, unless the call names another namespace.
otelOtelConfig | dict[str, Any] | NoneNoOpenTelemetry configuration. Enabled by default. Set \{'enabled': False\} or env OTEL_ENABLED=false to disable.
reconnection_configReconnectionConfig | NoneNoWebSocket reconnection behavior.
telemetryTelemetryOptions | NoneNoInternal worker metadata reported to the engine.
worker_descriptionstr | NoneNoOne-line, human/LLM-readable summary of what this worker does. Surfaces in engine::workers::list / engine::workers::info.
worker_namestr | NoneNoDisplay name for this worker. A non-empty III_WORKER_NAME overrides it. Defaults to hostname:pid.

Link to this sectionInputStream

A stream to read: bytes in binary frames, messages in text frames.

Received in a handler's input or in a call's result wherever the sender put a stream (a ref with "direction": "read"). Build one to send with from_file, from_iter or from_bytes; an open binary file and an async generator in a payload are streamed as well.

A stream has one reader: a second iteration, read_all, text, lines, messages or frames raises StreamInUseError; call tee before reading for two copies. A received stream opens its socket on the first read. When the writer aborts the stream, the read raises StreamAbortedError once the data sent before the abort has been read.

NameTypeRequiredDescription
cancelasync () -> NoneYesStop reading: the writer learns the reader left. A read in progress, and every later read, raises StreamClosedError: what was read is not the whole stream. A stream read to its end stays ended, and one passed on to another call is that call's (a no-op here).
frames() -> AsyncIterator[ChannelItem]YesEvery frame in order: ChannelItem with binary (bytes) or text (a message, as sent).
from_bytes(data: bytes | bytearray | memoryview | str) -> InputStreamYesA stream of data (str is sent as UTF-8 bytes).
from_file(file: str | IO[bytes], *, chunk_size: int = MAX_FRAME_SIZE) -> InputStreamYesA stream of a file's bytes, read in chunk_size pieces off the event loop.
from_iter(iterable: Iterable[Chunk] | AsyncIterable[Chunk]) -> InputStreamYesA stream of what iterable yields: bytes (str is sent as UTF-8 bytes).
idstrYesThe channel id of a received stream; local:<hex> for one built in this process.
lines(encoding: str = 'utf-8') -> AsyncIterator[str]YesThe stream's text, one line at a time, without the line ending (\n or \r\n); a last line with no newline is yielded too.
messages() -> AsyncIterator[Any]YesThe messages (text frames), each parsed as JSON; a text frame that is not JSON is yielded as the string it is. Binary frames are skipped.
read_allasync () -> bytesYesEvery byte of the stream, once it ended (text frames are skipped).
tee() -> tuple[InputStream, InputStream]YesTwo streams that each read every frame of this one (in-process copies). Call it before reading; this stream is then read through the copies.
textasync (encoding: str = 'utf-8', errors: str = 'strict') -> strYesThe stream's bytes, decoded.

Link to this sectionInvocationContext

The invocation the current code runs in, in every handler, remote or local.

Returned by iii.current_invocation().

NameTypeRequiredDescription
activationdict[str, Any] | NoneNo\{observer_id, activation_id?\} when this invocation is the activation of an observer's target.
callerdict[str, Any] | NoneNoWho started it: \{worker_id, worker_name, function_id?, invocation_id?, parent?\}; None when unknown.
function_idstrYesThe function whose handler is running.
invocation_idstrYesThis invocation's id.
observe_depthintNoDepth of the causal chain in observe hops (0 outside any activation).

Link to this sectionMatchKeys

on_observation_match as keys: an observer wants a call when they share a key, and the SDK keeps an index instead of asking every observer.

NameTypeRequiredDescription
callCallable[[Call[Any, Any]], Key]YesWhat a call is, computed once per call; a raise matches no observer.
observerCallable[[Observer], Key]YesWhat an observer listens for, computed once when it is accepted; an observer whose keys raise is rejected (OBSERVE_REJECTED).

Link to this sectionMiddlewareFunctionInput

Input passed to the RBAC middleware function on every function invocation through the RBAC port.

NameTypeRequiredDescription
actionCallActionEnqueue | CallActionVoid | NoneNoRouting action, if any.
contextdict[str, Any]YesAuth context returned by the auth function for this session.
function_idstrYesID of the function being invoked.
namespacestr | NoneNoTarget namespace the invoke addressed; forward the call here to stay in the caller's namespace. Absent -> the engine's default namespace.
payloaddict[str, Any]YesPayload sent by the caller.

Link to this sectionObserved

What an observer's target receives when iii delivers: the top-level fields, plus whichever of the observer's capture apply to the outcome. Fields not captured, or that do not apply, are absent.

NameTypeRequiredDescription
activation_idstrNo-
callerCallerNo-
duration_msfloatNo-
errordict[str, Any]No-
function_idstrNo-
inputAnyNo-
invocation_idstrNo-
metadatadict[str, Any]No-
namespacestrNo-
observer_idstrNo-
outputAnyNo-
started_at_msintNo-
statusLiteral['success', 'error']No-

Link to this sectionObserver

An observer as the worker that hosts its function sees it (on_observer_added, observers(), a deliver hook's observers): what was asked for. Never who observes, the observer's metadata or its policy.

The object stays the same for the observer's whole lifetime, so a worker keeps it in its own index (route table, consumers, ...).

NameTypeRequiredDescription
accepted(timeout: float | None = None) -> NoneYesBlocks until the SDK has acked this observer: a call made afterwards reaches an active observer. Use it to send a new observer its initial state, outside its on_observer_added (which runs before the ack): a call through it (\{"observer": obs, "payload": ...\}), which runs its target alone with the payload as given. Use accepted_async in async code.
accepted_asyncasync () -> NoneYesWaits until the SDK has acked this observer (on any event loop).
argsdict[str, Any]NoThe observer's args, validated against args_format by the engine.
capturelist[str]NoWhat the target's payload carries when iii delivers, and with it the outcomes that fire it (see ObserveSource).
filtersdict[str, Any]NoThe observer's filters, normalized; iii's delivery and matches apply them.
fires_onlist[str] | NoneNo-
function_idstrNoThe observed function (one this worker hosts).
idstrNoThe observer's id.
matches(call: CallLike) -> boolYesWhether call passes this observer's capture and filters: what iii's delivery checks, for a deliver hook that calls targets itself.
reject(code: str, message: str) -> NoneYesLate rejection of an active observer (e.g. after a config reload).
targetstrNoThe target function id.
to_dict() -> dict[str, Any]Yes-

Link to this sectionObserverHandle

What iii.observe returns, synchronously.

The observer is replayed with the same id on every reconnect until it is disposed. An error answer to its observe or to a replay is the engine's refusal and is final: the engine holds nothing for it, and it is not replayed. State listeners are called in order, on a callback thread of the SDK (never on the event loop that reads the engine's frames), so they may call the sync API.

NameTypeRequiredDescription
dispose() -> NoneYesRemoves the observer (unobserve). It is not replayed on reconnect.
dispose_asyncasync () -> NoneYesThe async form of dispose (it does not wait for the engine).
idAnyNoThe observer's id (stable across replays).
on_state_change(listener: StateListener) -> Callable[[], None]YesCalls listener(state, reason) on every state change after it subscribes, in order, on the SDK's callback thread. Returns the unsubscribe function; a change still queued then is not delivered to it.
ready(timeout: float | None = None) -> NoneYesBlocks until the observer is active. Use ready_async in async code.
ready_asyncasync () -> NoneYesWaits until the observer is active (on any event loop).
reasonObserveReason | NoneYesWhy the observer is in its state (error, suspended, disposed).
stateObserverStateYespending, active, suspended, error or disposed.

Link to this sectionObserverOptions

The observer itself: its id, policy and metadata (the third argument of iii.observe).

NameTypeRequiredDescription
expires_in_msintNoDisposed after this long.
idstrNoDefault: a random UUID, stable across replays.
max_firesintNoDisposed after this many activations.
max_in_flightintNoActivations running at once (the engine queues the rest).
metadatadict[str, Any]NoDelivered as the metadata sidecar of every activation.

Link to this sectionObserveSource

The left side of iii.observe: what is observed.

NameTypeRequiredDescription
function_idstrYesThe observed function.
argsdict[str, Any]NoFor the worker that hosts the function, which reads them in its hooks; validated against the function's args_format. A function without args_format takes none.
capturelist[Capture]NoWhat the target's payload carries, and with it which outcomes fire the target. Default ["input", "output", "caller"]. input and output fire on success, error fires on error; caller and metadata only add to the payload, so a capture must name at least one of input, output, error (INVALID_ARGS otherwise). [] fires on success with the top-level fields only. The default fires on success, ["error", "caller"] on errors, ["input", "error"] on both.
filtersFilterNoWhich calls reach the target; \{\} (or absent) = every call.
namespacestrNoDefaults to this worker's (engine::* and configuration::* resolve to default).

Link to this sectionOutputStream

A stream to write: write sends bytes, send sends a message.

Received in a handler's input or in a call's result wherever the sender put a sink (a ref with "direction": "write"). Build one to pass with to_file or to: the call resolves once what the function wrote reached it.

In a handler, a received OutputStream that was written to is closed when the handler returns and aborted when it raises. One the handler never used is closed when it returns, unless the invocation is an observer activation (an HTTP route target, say) that returned a value other than None: then it is left untouched. Call keep_open to keep writing after the handler returns. async with out: closes it at the end of the block, or aborts it on an error.

NameTypeRequiredDescription
abortasync (reason: str | BaseException | None = None) -> NoneYesEnd the stream as failed: the reader gets StreamAbortedError instead of a stream that looks complete. A stream never written is opened first, so the reader always learns of the failure. Idempotent; a no-op once closed or passed on.
closeasync () -> NoneYesEnd the stream: the reader sees a clean end. A stream never written is opened and closed (the reader sees an empty stream). Idempotent; a no-op once aborted or passed on.
idstrYesThe channel id of a received stream; local:<hex> for one built in this process.
keep_open() -> OutputStreamYesKeep the stream open after the handler that received it returns: the handler's code then closes or aborts it.
sendasync (message: Any) -> NoneYesSend message as JSON in one text frame (a file or writer sink drops it).
to(writer: Any) -> OutputStreamYesA sink that writes the stream's bytes to writer: a binary file object, an asyncio.StreamWriter, or anything with write(bytes) (sync or async). It is flushed or drained at the end and never closed: its owner closes it. Messages are not written. A writer that is not a file object (an asyncio writer, say) is used on the loop it was passed on.
to_file(path: str) -> OutputStreamYesA sink that writes the stream's bytes to path (created or truncated on the first write; an empty stream leaves an empty file). Messages are not written. On an abort the file keeps what was written, and the call rejects.
writeasync (data: bytes | bytearray | memoryview | str) -> NoneYesSend bytes (str is sent as UTF-8 bytes) in binary frames; returns once they were accepted (backpressure).

Link to this sectionPipe

Both ends of a pipe made with iii.pipe(): pass input to the function that reads, write output here (or the other way round).

NameTypeRequiredDescription
inputInputStreamYes-
outputOutputStreamYes-

Link to this sectionStreamInfo

What an observer sees where the observed call carried a stream: that a stream was passed, its direction and its channel id, and no bytes.

An observer's target receives it in the input and output of the Observed payload iii delivers. The access key still travels on the wire (a 0.26 engine sends the ref); this SDK drops it.

NameTypeRequiredDescription
directionLiteral['read', 'write']Yes-
idstrYes-
streamLiteral[True]No-

Link to this sectionStreamRequest

Incoming streaming request received by a function that serves a streaming HTTP route.

NameTypeRequiredDescription
bodyAnyYes-
headersdict[str, str | list[str]]Yes-
methodstrYes-
path_paramsdict[str, str]Yes-
query_paramsdict[str, str | list[str]]Yes-
request_bodyInputStreamYes-

Link to this sectionStreamResponse

Streaming HTTP response written to the request's response OutputStream.

Set the status and headers before the first body byte. The HTTP worker reads them as the control messages {"type": "set_status", ...} and {"type": "set_headers", ...}.

NameTypeRequiredDescription
closeasync () -> NoneYesEnd the body. The handler that returns closes it too.
headersasync (headers: dict[str, str]) -> NoneYes-
statusasync (status_code: int) -> NoneYes-
writeasync (data: bytes | str) -> NoneYesBody bytes (str is sent as UTF-8).
writerOutputStreamYesThe response stream itself.

Link to this sectionTelemetryOptions

Worker metadata reported to the engine (language, framework, project).

NameTypeRequiredDescription
frameworkstr | NoneNoFramework name, if applicable.
languagestr | NoneNoProgramming language of the worker.
project_namestr | NoneNoName of the project this worker belongs to.

Link to this sectioniii.engine

EngineFunctions · EngineSources

Link to this sectionEngineFunctions

Engine function ids for internal operations (parity with the Node SDK).

NameTypeRequiredDescription
INFO_FUNCTIONSFinal[str]No-
INFO_WORKERSFinal[str]No-
LIST_FUNCTIONSFinal[str]No-
LIST_WORKERSFinal[str]No-
REGISTER_WORKERFinal[str]No-

Link to this sectionEngineSources

Ids of the engine-hosted functions that are called once per event: observe them with iii.observe(EngineSources.FUNCTIONS_CHANGED, target) (parity with the Node SDK).

NameTypeRequiredDescription
CONFIGURATION_UPDATEDFinal[str]No-
FUNCTIONS_CHANGEDFinal[str]No-
LOGFinal[str]No-
OBSERVERS_CHANGEDFinal[str]No-
SPANFinal[str]No-
WORKERS_CHANGEDFinal[str]No-

Link to this sectioniii.errors

InvocationError · ObserveRejection · RegistrationRejectedError · StreamAbortedError · StreamClosedError · StreamInUseError

Link to this sectionInvocationError

Raised when an invocation dispatched by the SDK fails.

Inspect err.code to react to a specific category (e.g. 'FORBIDDEN' for RBAC denials, 'TIMEOUT' for timeouts). Catch this class to handle every rejection. except Exception continues to work because InvocationError inherits from Exception.

Attributes are read-only after construction. stacktrace is the engine-side trace when the remote handler raised; it may include internal file paths and should not be surfaced to end users. str(err) intentionally never includes the stacktrace.

NameTypeRequiredDescription
codeAnyNo-
function_idAnyNo-
invocation_idAnyNo-
messageAnyNo-
stacktraceAnyNo-

Link to this sectionObserveRejection

Rejects an observer with a code of its own.

Raise it from an on_observer_added hook, at either level (HTTP_ROUTE_CONFLICT, INVALID_CRON_EXPRESSION, ...); any other exception rejects the observer with OBSERVE_REJECTED. Raised from an on_observation_deliver hook, its code is the error the caller gets. Also what ObserverHandle.ready() and Observer.accepted() raise when the observer turns error or disposed, with the engine's or the hook's code (INVALID_ARGS, FORBIDDEN, UNSUPPORTED, ...).

NameTypeRequiredDescription
codeAnyNo-
messageAnyNo-

Link to this sectionRegistrationRejectedError

Raised when the engine rejects this worker's registration.

The engine pushes a registrationrejected message and closes the connection on a registration collision (e.g. another live worker already owns (namespace, worker_name)). This is fatal: the SDK does not reconnect. Inspect the attributes to identify the conflict.

NameTypeRequiredDescription
codeAnyNo-
namespaceAnyNo-
owner_worker_idAnyNo-
worker_nameAnyNo-

Link to this sectionStreamAbortedError

A stream ended in failure instead of a clean close (code is 'STREAM_ABORTED').

Raised by a read of an InputStream whose writer aborted it (its source failed, its handler raised, or its socket was lost), once the data sent before the abort has been read. A call rejects with it when a sink passed in its payload was aborted, even if the function succeeded.

NameTypeRequiredDescription
close_codeAnyNoThe WebSocket close code the reader got (1011 for an abort the engine relayed), or None for an abort raised in this process.
reasonAnyNoWhy the stream was aborted, as the reader learned it. A 0.26 engine relays an abort as channel writer aborted: closed with code <n> (or connection lost before close), not the writer's own reason.

Link to this sectionStreamClosedError

A stream that cannot be read or written any more (code is 'STREAM_CLOSED').

Raised by a write or send on an OutputStream that is closed or aborted, or whose reader left (the engine closed the socket, or the local sink failed), or whose connection failed; by a read of an InputStream that was cancelled (by cancel(), or by the guard when its handler returned), so a partly read stream never looks complete; and by passing such a stream to a call.

Also a RuntimeError, as these errors were before they had a code.


Link to this sectionStreamInUseError

A stream used where it can no longer be (code is 'STREAM_IN_USE'): a second reader of an InputStream, the same stream twice in one payload, a stream passed on after it was read to the end or already sent to another call, or a write to an OutputStream passed on.

Also a RuntimeError, as these errors were before they had a code.

Link to this sectioniii.protocol

CallRequest · ChannelDirection · ChannelItem · MessageType · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · SDK_FEATURES · StreamChannelRef · StreamChannelRefDict

Link to this sectionCallRequest

Request object for call() / call_async().

Name the function to call with function_id, or call through an observer with observer: the call runs the observer's target, and only the worker that hosts the observed function may make it.

NameTypeRequiredDescription
actionCallActionEnqueue | CallActionVoid | NoneNoSets how the call is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. CallAction.Enqueue(...), CallAction.Void()).
dispatchLiteral['auto', 'remote'] | NoneNoauto (default) runs a function this worker hosts in-process once the engine confirmed it; remote always goes through the engine.
function_idstr | NoneNoID of the function to call.
metadataAny | NoneNoPer-invocation metadata (any JSON value) supplied to the called handler beside the payload. None is no metadata.
namespacestr | NoneNoTarget namespace for routing. Omit to inherit this worker's; say default to reach the engine's from a namespaced worker.
observerAnyNoAn Observer of a function this worker hosts: the call runs its target, with its policy and metadata sidecar. Takes no function_id, namespace, metadata or enqueue action.
payloadAnyNoInput data passed to the function.
timeout_msint | NoneNoOverride the default invocation timeout, in milliseconds.

Link to this sectionChannelDirection

Direction of a streaming channel reference.

Mirrors the Rust SDK's ChannelDirection enum. The string values ("read" / "write") match the wire format used by StreamChannelRef.direction.

NameTypeRequiredDescription
READAnyNo-
WRITEAnyNo-

Link to this sectionChannelItem

A single frame transferred over a channel (what iii.InputStream.frames yields).

Mirrors the Rust SDK's ChannelItem enum. Exactly one of text or binary is set; use text_item / binary_item to construct instances.

NameTypeRequiredDescription
binarybytes | NoneNo-
binary_item(value: bytes) -> ChannelItemYes-
is_binaryboolYes-
is_textboolYes-
textstr | NoneNo-
text_item(value: str) -> ChannelItemYes-

Link to this sectionMessageType

Message types for iii communication.

NameTypeRequiredDescription
FUNCTION_REGISTEREDAnyNo-
INVOCATIONS_OBSERVEDAnyNo-
INVOCATION_RESULTAnyNo-
INVOKE_FUNCTIONAnyNo-
LOCAL_INVOCATION_STATSAnyNo-
OBSERVEAnyNo-
OBSERVER_ACKAnyNo-
OBSERVER_ADDEDAnyNo-
OBSERVER_REMOVEDAnyNo-
OBSERVER_STATE_CHANGEDAnyNo-
OBSERVE_RESULTAnyNo-
REATTACHAnyNo-
REGISTER_FUNCTIONAnyNo-
REGISTER_SERVICEAnyNo-
REGISTRATION_REJECTEDAnyNo-
UNOBSERVEAnyNo-
UNREGISTER_FUNCTIONAnyNo-
WORKER_REGISTEREDAnyNo-

Link to this sectionRegisterFunctionFormat

Format definition for function parameters.

NameTypeRequiredDescription
bodylist[RegisterFunctionFormat] | NoneNoNested fields for object types.
descriptionstr | NoneNoHuman-readable description of the parameter.
itemsRegisterFunctionFormat | NoneNoItem schema for array types.
namestrYesParameter name.
requiredboolNoWhether the parameter is required.
typestrYesType string (string, number, boolean, object, array, null, map).

Link to this sectionRegisterFunctionInput

Input for registering a function, matches Node.js RegisterFunctionInput.

NameTypeRequiredDescription
descriptionstr | NoneNoHuman-readable description.
idstrYesUnique function identifier.
invocationHttpInvocationConfig | NoneNoHTTP invocation config for externally hosted functions.
metadataAny | NoneNoArbitrary metadata attached to the function.
request_formatRegisterFunctionFormat | dict[str, Any] | NoneNoSchema describing expected input.
response_formatRegisterFunctionFormat | dict[str, Any] | NoneNoSchema describing expected output.

Link to this sectionRegisterFunctionMessage

NameTypeRequiredDescription
args_formatAny | NoneNo-
descriptionstr | NoneNo-
idstrYes-
invocationHttpInvocationConfig | NoneNo-
message_typeMessageTypeNo-
metadataAny | NoneNo-
observablebool | NoneNo-
privatebool | NoneNo-
request_formatRegisterFunctionFormat | dict[str, Any] | NoneNo-
response_formatRegisterFunctionFormat | dict[str, Any] | NoneNo-

Link to this sectionSDK_FEATURES

SDK_FEATURES = tuple[str, ...]

Link to this sectionStreamChannelRef

Reference to a streaming channel for worker-to-worker data transfer.

NameTypeRequiredDescription
access_keystrYesSecret key for authenticating channel access.
channel_idstrYesUnique channel identifier.
directionLiteral['read', 'write']YesChannel direction (read or write).

Link to this sectionStreamChannelRefDict

Wire-shape of a StreamChannelRef as it appears in raw payloads.

Used as the narrowed type for is_channel_ref so type checkers can validate value["channel_id"] style access after the guard passes.

NameTypeRequiredDescription
access_keystrYes-
channel_idstrYes-
directionLiteral['read', 'write']Yes-

Link to this sectioniii.runtime

FunctionRef

Link to this sectionFunctionRef

A registered function: the client's hook methods with its id filled in, its observers, and unregister().

Each hook method works as a decorator and as a plain call, returns the hook, and removes the hook when given None. Hooks are stored by function id, so they stay in place across unregister() and a later registration of the same id.

The SDK loop runs on a thread of its own, so the engine may announce an observer before a hook set here is in place: on_observer_added then runs for that observer after it became active, and a warning says so. For on_observer_added and on_observer_removed to run for every observer, set them on the client by id before register_function.

NameTypeRequiredDescription
idAnyNoThe function's id.
is_observed(call: CallLike | None = None) -> boolYesWhether a call would reach anyone (see III.is_observed).
observers() -> list[Observer]YesThe function's active observers, as this worker sees them.
on_observation_deliver(hook: DeliverHook | None) -> DeliverHook | NoneYesThis function's on_observation_deliver (see III.on_observation_deliver).
on_observation_match(hook: Any = ..., *, observer: Any = None, call: Any = None) -> AnyYesThis function's on_observation_match: a predicate (obs, call) -> bool, or observer= and call= key functions (see III.on_observation_match).
on_observer_added(hook: AddedHook | None) -> AddedHook | NoneYesThis function's on_observer_added (see III.on_observer_added).
on_observer_removed(hook: RemovedHook | None) -> RemovedHook | NoneYesThis function's on_observer_removed (see III.on_observer_removed).
unregister() -> NoneYesRemoves the function from the engine; on_observer_removed runs for each of its accepted observers.

Link to this sectioniii.state

IState · StateDeleteInput · StateDeleteResult · StateEventData · StateEventType · StateGetInput · StateListInput · StateSetInput · StateSetResult · StateUpdateInput · StateUpdateResult

Link to this sectionIState

Abstract interface for state management operations.

NameTypeRequiredDescription
deleteasync (input: StateDeleteInput) -> StateDeleteResultYesDelete a state value.
getasync (input: StateGetInput) -> TData | NoneYesRetrieve a value by scope and key.
listasync (input: StateListInput) -> list[TData]YesList all values in a scope.
setasync (input: StateSetInput) -> StateSetResult[TData] | NoneYesSet (create or overwrite) a state value.
updateasync (input: StateUpdateInput) -> StateUpdateResult[TData] | NoneYesApply atomic update operations to a state value.

Link to this sectionStateDeleteInput

Input for deleting a state value.

NameTypeRequiredDescription
keystrYesKey within the scope.
scopestrYesState scope (namespace).

Link to this sectionStateDeleteResult

Result of a state delete operation.

NameTypeRequiredDescription
old_valueAny | NoneNoPrevious value (if it existed).

Link to this sectionStateEventData

Payload for state change events.

NameTypeRequiredDescription
event_typeStateEventTypeYesType of state change.
keystrYesKey within the scope.
new_valueTData | NoneNoNew value (for create/update events).
old_valueTData | NoneNoPrevious value (for update/delete events).
scopestrYesState scope (namespace).
typestrNoEvent category (always state).

Link to this sectionStateEventType

Types of state change events.

NameTypeRequiredDescription
CREATEDAnyNo-
DELETEDAnyNo-
UPDATEDAnyNo-

Link to this sectionStateGetInput

Input for retrieving a state value.

NameTypeRequiredDescription
keystrYesKey within the scope.
scopestrYesState scope (namespace).

Link to this sectionStateListInput

Input for listing all values in a state scope.

NameTypeRequiredDescription
scopestrYesState scope (namespace).

Link to this sectionStateSetInput

Input for setting a state value.

NameTypeRequiredDescription
keystrYesKey within the scope.
scopestrYesState scope (namespace).
valueAnyYesValue to store.

Link to this sectionStateSetResult

Result of a state set operation.

NameTypeRequiredDescription
new_valueTDataYesNew value that was stored.
old_valueTData | NoneNoPrevious value (if it existed).

Link to this sectionStateUpdateInput

Input for atomically updating a state value.

NameTypeRequiredDescription
keystrYesKey within the scope.
opslist[UpdateOp]YesOrdered list of update operations to apply atomically.
scopestrYesState scope (namespace).

Link to this sectionStateUpdateResult

Result of a state update operation.

NameTypeRequiredDescription
new_valueTDataYesNew value after the update.
old_valueTData | NoneNoPrevious value (if it existed).

Link to this sectioniii.stream

IStream · StreamDeleteInput · StreamDeleteResult · StreamGetInput · StreamListGroupsInput · StreamListInput · StreamSetInput · StreamSetResult · StreamUpdateInput · StreamUpdateResult

Link to this sectionIStream

Abstract interface for stream operations.

.. deprecated:: IStream is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams

Defining a subclass emits a FutureWarning attributed to the line of the class statement (once per subclass definition, never per request). Importing this module does not warn.

NameTypeRequiredDescription
deleteasync (input: StreamDeleteInput) -> StreamDeleteResultYesDelete an item from the stream.
getasync (input: StreamGetInput) -> TData | NoneYesGet an item from the stream.
listasync (input: StreamListInput) -> list[TData]YesGet all items in a group.
list_groupsasync (input: StreamListGroupsInput) -> List[str]YesList all groups in the stream.
setasync (input: StreamSetInput) -> StreamSetResult[TData] | NoneYesSet an item in the stream.
updateasync (input: StreamUpdateInput) -> StreamUpdateResult[TData] | NoneYesApply atomic update operations to a stream item.

Link to this sectionStreamDeleteInput

Input for stream delete operation.

.. deprecated:: StreamDeleteInput is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams

NameTypeRequiredDescription
group_idstrYesGroup identifier.
item_idstrYesItem identifier.
stream_namestrYesName of the stream.

Link to this sectionStreamDeleteResult

Result of stream delete operation.

NameTypeRequiredDescription
old_valueAny | NoneNoPrevious value (if it existed).

Link to this sectionStreamGetInput

Input for stream get operation.

.. deprecated:: StreamGetInput is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams

NameTypeRequiredDescription
group_idstrYesGroup identifier.
item_idstrYesItem identifier.
stream_namestrYesName of the stream.

Link to this sectionStreamListGroupsInput

Input for stream list groups operation.

.. deprecated:: StreamListGroupsInput is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams

NameTypeRequiredDescription
stream_namestrYesName of the stream.

Link to this sectionStreamListInput

Input for stream list operation.

.. deprecated:: StreamListInput is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams

NameTypeRequiredDescription
group_idstrYesGroup identifier.
stream_namestrYesName of the stream.

Link to this sectionStreamSetInput

Input for stream set operation.

.. deprecated:: StreamSetInput is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams

NameTypeRequiredDescription
dataAnyYesData to store.
group_idstrYesGroup identifier.
item_idstrYesItem identifier.
stream_namestrYesName of the stream.

Link to this sectionStreamSetResult

Result of stream set operation.

NameTypeRequiredDescription
new_valueTDataYesNew value that was stored.
old_valueTData | NoneNoPrevious value (if it existed).

Link to this sectionStreamUpdateInput

Input for stream update operation.

.. deprecated:: StreamUpdateInput is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Migration guide: https://iii.dev/docs/upgrading/migrate-from-streams

NameTypeRequiredDescription
group_idstrYesGroup identifier.
item_idstrYesItem identifier.
opslist['UpdateOp']YesOrdered list of update operations to apply atomically.
stream_namestrYesName of the stream.

Link to this sectionStreamUpdateResult

Result of stream update operation.

NameTypeRequiredDescription
errorslist[UpdateOpError]NoPer-op errors. Emitted by merge and append for validation rejections (path depth/size, value depth, or a __proto__ / constructor / prototype segment or top-level key) and by append for the append.type_mismatch and append.target_not_object surfaces. Successfully applied ops are still reflected in new_value. The field is omitted from the JSON wire when empty.
new_valueTDataYesNew value after the update.
old_valueTData | NoneNoPrevious value (if it existed).