# Runtime and execution semantics

The first-party engine. Validation pipeline, execution plans, readiness, control routing, skips, joins, parallelism, retries, timeouts, cancellation, loops, checkpoints and trace events.

Source: https://glamorous-boar.cloudvent.net/architecture/runtime/

---

The runtime (`packages/runtime`) executes canonical IR. It has no dependency on web frameworks, databases or model SDKs, so the API, the CLI and exported apps all embed the same engine.

## Lifecycle

<Diagram caption="From raw IR to a result and a trace.">

```
flowchart LR
  A[raw IR] -- parse / migrate --> B[ProjectDocument]
  B -- validate --> C[ValidationReport]
  B -- compile_plan --> D[ExecutionPlan]
  D -- Engine.run --> E[RunResult + TraceEvents]
```

</Diagram>

## Validation pipeline

1. Parse against the IR schema (`IR_*` codes).
2. Resolve node types and versions in the registry (`NODE_UNKNOWN_TYPE`, `NODE_UNKNOWN_VERSION`).
3. Validate each node's config against its schema (`CONFIG_INVALID`, with a `path`).
4. Validate edges, ports, types and cardinality (`EDGE_*`, `PORT_*`).
5. Validate structure: duplicates, cycles, isolated nodes, loops (`GRAPH_*`, `LOOP_*`).
6. Check secrets, permissions and trust (`SECRET_*`, `NODE_ISOLATION_UNAVAILABLE`, `NODE_NOT_PERMITTED`).
7. Return structured diagnostics: `code`, `severity`, `message`, `node_id`, `edge_id`, `port`, `path`, `related_node_ids`, `hint`.

Only `error` severity blocks execution. The IDE runs the same pipeline live as you edit.

## Execution plan

Typed config is parsed once; per-node data and control inputs, the upstream set, the effective timeout and attempts, and the set of secrets each node may resolve are precomputed. The order is a deterministic topological sort. With `targets`, only the targets and everything they depend on are kept.

## Execution semantics

| Rule | Behaviour |
|---|---|
| Readiness | A node is ready when every upstream node (data or control) is terminal. |
| Control routing | With incoming control edges, a node runs only if at least one comes from a succeeded node that activated that branch (OR-join). `control_join="all"` nodes such as Join need every one. Otherwise **skipped** (`control_not_activated`). Branches may come from config (`branches_from_config`, e.g. Router routes). |
| Skip propagation | If all producers of a required input were skipped, the node is skipped (`upstream_skipped:<port>`). |
| Joins | `multiple` inputs receive a list in **edge-ID order**, not completion order, so results are deterministic. |
| Parallelism | Ready nodes run concurrently up to `max_concurrency` (asyncio). |
| Failure | Fail-fast: the first node failure (after retries) cancels in-flight nodes and fails the run. |
| Retries | Only retryable errors (`TransientNodeError`), up to `max_attempts`, exponential backoff. Timeouts are retried only for nodes declared idempotent. Unhandled exceptions are never retried. |
| Timeouts | Per node: manifest default, overridable in IR `execution.timeout_seconds`. |
| Cancellation | Cooperative via a cancel token; running nodes are cancelled and reported. |
| Output contract | Outputs must match declared ports and types exactly; branches must be declared; run outputs must be JSON. |
| Secrets | Nodes resolve only secrets in their own config (or delegated through handles), only with `credentials`. Values are scrubbed from traces, errors and stored outputs. |
| Cycles | Rejected at validation. Iteration uses Loop / Loop End regions. |

## Loops

A `loop_start` (Loop) and `loop_end` (Loop End) node paired by a `scope → scope` edge enclose a body: every node on a path between them. The plan lifts body nodes out of the top-level order. Loop End runs the body once per iteration in a fresh scope seeded with `item` / `index` / `state`: `for_each` (bounded concurrency, results in item order, `on_item_error` fail or skip) or `repeat` (state carried forward; stop on `continue=false` or `max_iterations`; engine ceiling 10,000). Events inside a loop carry `data.iteration`. A failure inside an iteration fails the loop with the inner node's code and an "iteration N" message, unless items are skipped.

## Handles and secret delegation

Values on handle ports (`EmbeddingModel`, `VectorStoreHandle`, `Tool`, `Database`, `Ontology`) are descriptors that may contain secret references. A node with `credentials` may resolve the references carried by handles wired into it; tool handles delegate transitively. Secret values never travel on edges.

## Checkpoints, suspension and resume

Every finished top-level node is checkpointed exactly. Values that are not JSON or that contain a secret value are non-restorable and re-run on resume. A `can_suspend` node raising `SuspendNode` becomes `waiting`; once independent work is done the run ends as `waiting`. `Engine.run(plan, resume=ResumeState(checkpoints, responses, last_seq))` restores the root scope, passes each response as `ctx.resume_value`, emits `run_resumed` and continues event numbering.

## Memory, storage and artifacts

- `memory` permission → `ctx.memory`: project-scoped conversation turns and long-term memories (database-backed in the API, in-process in the CLI).
- `filesystem` permission → `ctx.storage_path(...)`: a persistent folder under the data directory.
- `artifacts` permission → `ctx.read_artifact(id)`: project files, scoped to the run's project.

## Streaming

When the observer implements `on_stream`, each invocation gets a sink; nodes check `ctx.streaming` and call `ctx.stream_text(delta)`. Otherwise nodes make normal calls.

## Trace events

Every event has `run_id`, `project_id`, `seq` (1..n, gap-free per run), `timestamp`, `event_type`, and where relevant `node_id`, `node_type`, `invocation_id`, `attempt`, `retry_count`, `status`, `duration_ms`, redacted `inputs_summary` / `outputs_summary`, `usage` (provider, model, tokens, estimated cost), `error` (`code`, `message`, `node_id`, `retryable`) and `data`.

Core types: `run_started`, `run_succeeded`, `run_failed`, `run_cancelled`, `run_waiting`, `run_resumed`, `node_started`, `node_succeeded`, `node_failed`, `node_retrying`, `node_skipped`, `node_cancelled`, `node_waiting`, `node_event` (custom, via `ctx.emit`, e.g. `agent_turn`, `tool_call`, `handoff`, `retrieved`, `model_route`, `loop_iteration`).

Summaries truncate long strings and collections and redact sensitive keys and resolved secret values.

### Streaming to clients

`GET /api/runs/{id}/events` returns JSON (`?after=<seq>` to page) or, with `Accept: text/event-stream`, SSE: each message has `id: <seq>` and `event: trace` (or `event: token`); browsers reconnect with `Last-Event-ID`; a final `event: end` is sent once the run is terminal and all events were delivered.

## Run statuses

`queued`, `running`, `succeeded`, `failed`, `cancelled`, `waiting`. API-level failures: `RUN_INTERRUPTED` (resumable), `RUN_ABORTED`, `RUN_RECOVERY_LIMIT`, `RUNTIME_INTERNAL_ERROR`.

See [Error codes](/error-codes/) for every diagnostic and runtime code.
