---
title: Orchestration
description: "Use the flow of data to order work: run steps in parallel, map over lists, branch, loop, and order effects in sequence."
---

Use the flow of data to order work: run steps in parallel, map over lists, branch, loop, and order effects in sequence.

## Workflow bodies describe orchestration

See also [steps and workflows](/authoring/workflow-definitions#steps-and-workflows) and
[statements run in order inside `with sequential`](/authoring/orchestration#statements-run-in-order-inside-with-sequential).

Deployment compiles workflow source into an execution graph. The input and
step or primitive results are workflow values: data available when the
workflow runs. Field access, indexing, comparisons and boolean combinations
describe values too. Put executable Python logic inside steps.

```text
statement   := name = call | name = value | call | local_body | block | return value | return | pass
block       := with sequential: statements       # calls and assignments, no return or block
call        := step(arguments) | workflow([value]) | primitive(arguments)
arguments   := positional values and explicitly named keyword values
value       := constant | ref | value.attr | value[index] | call
             | comparison | combination | container | constructor
container   := [value, ...] | (value, ...) | {string_key: value, ...}
constructor := Record(arguments)
comparison  := value <cmp> value                 # < <= > >= == !=
             | value is None | value is not None
combination := operand and operand | operand or operand | not condition
             | the same forms using &, |, ~
condition   := comparison | combination | a workflow field or index
             | a boolean-producing call or ref
operand     := a condition containing no call
local_body  := def name(parameter?): statements; return value | return
```

A `ref` is the input, a bound result, an alias or a body parameter; an
`index` is a constant or workflow value. A constant contains no workflow
value or call and is evaluated once at deployment. Other assignments must
contain a workflow value. `Record` is a stdlib/Pydantic dataclass or Pydantic
model. Containers can be empty. A docstring is allowed before statements;
the console shows it to operators as the workflow's description, on the
workflow card and above the run form.

A workflow is a synchronous `def`; validation rejects `async def`, and
asynchronous work belongs in an async step. It takes its run's input as one
typed parameter, positional or keyword-only, or none: validation rejects a
second parameter, a default, and `*args` or `**kwargs`. Several values are
fields of one record, which is what the console's start form is built from.
Annotate the parameter and the return type; write `-> None` for a workflow
that returns nothing.

| Forbidden in the body | Use instead |
|---|---|
| `if` / `else` | `branch(condition, true=..., false=...)` |
| `for` / `while` / comprehensions | `map(step, items)` / `loop(...)`, or iteration inside a step |
| Helpers, builtins, membership tests, f-strings, arithmetic, list concatenation | A step returning the value |
| `try` / `except`, imports | Handle failures and import dependencies inside steps |
| `await` | Call workflow steps without `await`; use `await` for asynchronous work inside an async step |
| Constant / annotated assignments | Module-level constants / `result = step(...)` with a return annotation on the step |
| `*args` / `**keywords` at call sites | Write each argument explicitly |

Positions determine accepted values:

| Position | Accepted forms |
|---|---|
| Step and `map` arguments; a workflow call's argument; wait `context=`; `return`; branch results; sleep `then=` and `until=`; loop `initial=` and body result | Any value from the grammar, including constants, projections, nested lists, tuples, string-keyed dictionaries and record constructors. Branch arms and a sleep's `then=` may also name a local body. |
| Review `subject=` | A whole step or primitive result, or a tuple or record whose members are whole results, such as `subject=(summary, risks)`. |
| Branch condition; loop `until` result | Conditions. |
| Loop `body=` | A one-parameter lambda returning a value, a decorated step or workflow, or a one-parameter local body. |
| Loop `until=` | A one-parameter lambda returning a condition, or a decorated step or workflow that returns a boolean. |
| Configuration | Constants: concurrency, durations, labels, keys, iteration limits, wait types and the step selected by `map`. |

Dictionary keys must be constant strings in every data position. Values can
contain workflow values at any depth. Read record fields with attributes
(`result.count`) and dictionary entries with indexing (`result["count"]`).
These rules follow the value's declared or composed kind through aliases,
branches and loop state. Supported computed record fields remain available.
List and tuple indexes can be constants or workflow values.

Use `value is None` or `value is not None` for null tests. These test for null;
use `==` or `!=` for value equality. General object identity is not part of
workflow orchestration.

`map` takes a module-level decorated step and passes arguments as a call
does. Positional lists are mapped element by element, zipped and of equal
length, and keyword arguments are shared by every call:

```python
map(fn, xs, ys, z=z)      # fn(xs[i], ys[i], z=z) for each i
```

A lambda, a local workflow body or a workflow is not a map target: call a
workflow directly, or inside a `loop`. Put per-element Python logic in the
mapped step. Write a mapped list as `[first, second]`, not `(first, second)`;
tuples are valid shared values and list elements. An editor checks that the
first list holds the step's first parameter type and infers the result list.
It cannot check further lists, keyword arguments, or a parameter left
unfilled; deployment checks each of them.

`map` takes its step by position and reserves its own option name,
`max_concurrency`. A step parameter with that name is filled by position: in
`map(configure, limits, max_concurrency=4)` each element of `limits` is the
step's argument and `4` controls the map. Ordinary argument binding reports
a required parameter left unfilled; one with a default takes its default.

`max_concurrency` is a positive integer that bounds the elements executing at
once (default 10). A failed element fails the map: the elements still running
are cancelled and no more start. A failure the fan-out should survive is
returned as a value: the step handles its own error and returns a typed
outcome, and the workflow carries on from the list of outcomes.

```python
class Settlement(BaseModel):
    claim_id: str
    settled: bool
    reason: str | None = None


@step
def settle(claim: Claim) -> Settlement:
    try:
        post_to_payer(claim)
    except PayerRejected as rejected:
        return Settlement(claim_id=claim.id, settled=False, reason=str(rejected))
    return Settlement(claim_id=claim.id, settled=True)


@workflow
def settle_claims(claims: list[Claim]) -> list[Settlement]:
    return map(settle, claims, max_concurrency=2)
```

Start a batch of independent records as one run per record, through the API
or a trigger: a failure stays with its record, and nothing waits on the whole
batch.

## Statements run in order inside `with sequential`

Outside a block, data dependency is the only ordering, which suits data and
not effects: `post_payment(claim)` followed by `email_notice(claim.email)`
runs both at once. Write effects that must happen in order in a block:

```python
with sequential:
    post_payment(claim)
    email_notice(claim.patient_email)
    status = sleep("3d", then=check_status(claim))
return status
```

- A statement starts when the previous statement's work has finished and its
  own inputs are ready.
- Only calls written in the block are ordered; a result bound earlier has
  already started.
- Calls within one statement are ordered by data, as in
  `email(format(claim))`.
- Work after the block that uses nothing from it runs alongside it. In the
  example below `audit` starts with `post_payment`, not after `email_notice`:

  ```python
  with sequential:
      post_payment(claim)
      email_notice(claim.patient_email)
  audit(claim)
  ```

- In a branch arm or a loop body, the block goes in a local body.

A statement in a block is a call or an assignment; a `return` and a block
written directly inside a block are rejected. A statement whose work is
skipped, such as a `branch` whose arm is not chosen, counts as finished. A
statement whose work fails ends the run as any failed call does, so the
statements after it never start. A name bound in the block is used after it
as any other result is. A `branch`, `map`, `loop`, wait or sleep written as a
statement is ordered the same way; a sleep in a block also waits for the
statement before it.

Repeated calls to one target are bound to names, as anywhere in a body. The
names are the calls' node keys, which is how a later run finds their recorded
outputs; they order nothing:

```python
with sequential:
    to_patient = send_email(claim.patient_email)
    to_provider = send_email(claim.provider_email)
```

Deploy warns about a call outside a block whose result nothing uses while
later calls exist, since it runs alongside them; write such calls in a block
when their order matters. Two effects that do not depend on each other are a
valid body, so this is a warning. A call written after a block gets no
warning of its own.

A run can wait on several things at once. Two independent reviews, two
sleeps, or a review beside a sleep, a child run or a long retry delay each
continue when their own response, wake time or child arrives; the rest stay
parked until theirs does.

Work without a data dependency runs concurrently. When a run suspends for a
wait, sleep, or long retry delay, independent scheduled work, including other
map elements, finishes and checkpoints before the run parks; completed steps
are reused on resume. A step interrupted by a lost worker runs again on
resume, so side effects must tolerate re-execution; use provider idempotency
keys as described in
[Retries and durability](/authoring/retries-and-durability). A failure
in that work fails the attempt. Failure or cancellation aborts and drains
unfinished work, including map elements, before the runtime closes.

Primitive contracts:

- `map(step, *lists, **shared)` calls a step once per element:
  positional lists zip element by element, and keyword arguments are shared
  by every call. `max_concurrency` bounds the elements executing at once
  (default 10). A failed element fails the map.
- `branch(cond, true=..., false=...)`: `cond` is a bool field or
  comparison (`review.timed_out`, `draft.score > 0.9`) or the result of a
  step or primitive typed `bool`; deploy rejects a result typed anything
  else. A `type` alias of `bool`, `Literal[True, False]`, and each of these
  `| None` count as `bool`; unannotated and `Any` results remain unchecked.
  Both non-null arms must return the same type when their types are known.
  An arm may yield `None` for an empty result; the result then includes `None`
  and the consumer must accept it. `false=` is optional: a false condition
  with no false arm yields `None`. Omit `false` instead of writing a no-op
  step. Calls written inside an
  arm, including nested calls, run only when it is chosen, and the branch
  awaits all of that work. A previously bound result retains its enclosing
  scope: `charged = charge(input); branch(cond, true=charged)` runs `charge`
  unconditionally. Write `branch(cond, true=charge(input))` to make it
  conditional.
- `loop(body, until=, max_iterations=, initial=)` is a **do-while**: the body
  always runs at least once and `until` is evaluated on each iteration's
  output, never on `initial`. Supply `body` positionally or by keyword as a
  lambda, a decorated step or workflow, or a one-parameter local body. `until`
  is a lambda returning a condition in the same forms as `branch`'s `cond`, or
  a decorated step or workflow that returns a boolean. Outer workflow values captured by a body remain fixed across
  its iterations. `initial` and the body result can be composed values.
  Each iteration evaluates its body result before `until`; the predicate and
  next iteration receive that same canonical value. The body result must be
  compatible with the initial state's type when those types are known.
  Dictionary state can add or remove keys; each lookup must be valid for the
  iteration that executes it. Gate the loop behind `branch(...)` if the first
  iteration must be avoidable.
- `wait_for_review`, `wait_for_event` and `sleep` park the run until a
  decision, an event or a wake time arrives; their contracts are in
  [Human review and waits](/authoring/human-review-and-waits)
  (`andon docs show authoring/wait-for-a-review-an-event-or-a-time`).
- A call to a `@workflow` function, such as `process_claim(claim)`, starts
  the callee as a child run and waits until it ends. The callee's annotations
  give the argument and result types, so an editor checks the argument and
  infers the result. The child has its own `timeout`, sandbox and waits, and
  takes its parent's deployment; time the caller spends waiting on it does not
  count against the caller's `timeout`. A record passed to the child reads
  there as the caller held it, field by field, whatever its aliases. A child that fails or is cancelled
  fails the call. The caller sets no deadline on the child, so a child parked
  on a long wait keeps its caller waiting, up to the end of the caller's 14-day life. The call runs the workflow its
  import names, identified by its key, and the deployment must declare that
  same function in `andon.toml`; deployment rejects a call whose key belongs
  to a different declared workflow. Calling a workflow as ordinary Python, such as
  from a step, raises an error, and validation reports such a call in a step
  body.
