# How flows run

> What happens between a trigger firing and a run ending, through steps, branches, approvals and waits; the states a run passes through; and how a run, its steps and their attempts relate.

Source: https://docs.go-lumen.ai/concepts/how-flows-run

**In one sentence**: A flow is a graph you save once; every time a trigger fires, Lumen starts a run that walks the graph step by step, records each step and each attempt, and parks, held by no worker, whenever it waits for a person or a time.

A **flow** is configuration: a trigger or more, and the nodes that do the work, joined by `next`. A **run** is one execution of it. The flow says what could happen; the run is what did.

*Diagram: How a flow is shaped: a trigger, steps, a branch, an approval and a join.* An email arrives and starts a run. The run reads the text of the attached invoice, then an AI agent step finds the supplier and the total. A branch then picks one path: invoices of 10,000 or more go to an approval, where the run waits for a person to answer; otherwise the invoice is checked against the ERP with an API call, and the run waits until the due date the ERP returned. Both paths join at the last step, which keeps the file.

*One run of the `invoice-approval` flow. Each tile is a node; a run walks the edges and records every node it reaches.*

## A trigger starts a run

Every run starts from exactly one trigger and carries the documents that arrived with it: an email and its attachments, an uploaded file, a row, or nothing at all for a schedule.

-   A flow may have several triggers, for example an email address and a manual **Run** button. Each fires its own runs.
-   A trigger can have a **start only when** condition, tested as the email arrives. Mail that does not match starts no run and costs nothing; the flow's intake log shows it as unmatched.
-   A redelivery of the same message is recognised and starts nothing.

## Steps do the work

Each node is one of six kinds. Most are **steps**, units of work from the catalog such as reading a document or sending an email; the other five shape the path.

| Node | What it does | Example |
| --- | --- | --- |
| Step | Runs one step from the [catalog](https://docs.go-lumen.ai/reference/steps/send-email.md) | read the text, find details, send an email |
| Branch | Sends the run down the first path whose condition holds, or the default | large invoices to an approver |
| Filter | Lets the run go on only when a condition holds | only mail from suppliers |
| For each | Runs its nodes once per item of a list | one row per invoice line |
| Wait | Pauses until a time or a date found earlier | until the due date |
| Approval | Asks a person and pauses until they answer | approve a payment |

A node's `next` lists the nodes after it. Several entries run side by side, and paths may join again at a later node.

## Documents and data

A step declares what it **needs** and what it **produces**, as data types: `file`, `text`, `fields` and `email`. The editor offers a step only where what it needs is already on the path, which is why the picker never shows a step that cannot run there.

By default a run carries one document at a time (`item`). A step whose input is `batch`, such as merging PDFs, sees all the documents of one arrival together.

Steps also have named **outputs**. A later node reads one as `{nodeId.field}` in text and as `nodeId.field` in a condition: `{details.supplier}` in an email subject, `details.total` in a branch.

## A branch takes the first path that holds

A branch works like *if, else if, otherwise*: its cases are checked in order, the first one that holds is the path the run takes, and the default path (`branchDefault`) runs when none does. In the diagram, an invoice of 10,000 or more goes to the approver; every other invoice goes to the ERP check. The two paths join again at **Keep the file**.

A node that no taken path reaches is recorded as `skipped`, so the run still shows the whole flow and why part of it did not run.

## Approvals and waits park the run

An **approval** emails a person a question, with the fields they should fill in and a deadline (`timeout`). A **wait** pauses until a time, or a date an earlier step found.

While a step waits, no worker holds it and nothing is claimed. The run's state is `waiting`, and it can wait for days. When the person answers, the deadline passes or the time comes, the run picks up at the next node.

> **Waiting is cheap:**
> 
> A run that waits three days for an approval holds no worker in those three days. Waits are safe to use generously.

## The states of a run

*Diagram: The states of a run.* A run that is admitted but may not start yet is held, for example while its budget is used up or an earlier run holds its file lock; it becomes queued when the reason clears. A queued run becomes running when a worker claims its first step. A running run becomes waiting while it waits on an approval, a question or a time, and running again when that is answered or the time comes. From running it ends in exactly one of three states: succeeded when every node on its path is done, failed when a step fails after its last attempt, or cancelled when a person stops it.

*Steps use the same states, plus `skipped` for a node a branch did not take.*

| State | Means | Ends here? |
| --- | --- | --- |
| `held` | Admitted, but not allowed to start or go on yet: its budget is used up, or an earlier run holds the same file lock. It is never failed; it continues when the reason clears. | no |
| `queued` | Ready, waiting for a worker to claim its next step. | no |
| `running` | A worker is running one of its steps. | no |
| `waiting` | Parked on an approval, a question or a wait. No worker holds it. | no |
| `succeeded` | Every node on its path is done. | yes |
| `failed` | A step failed after its last attempt. | yes |
| `cancelled` | A person stopped it before it finished. | yes |

## Runs, steps and attempts

Run `invoice-approval-7k2q` (succeeded): one trigger, one document, one bill

1.  Step `text` (#1 succeeded)
2.  Step `details` (#1 worker lost) (#2 succeeded)
3.  Step `approver` (#1 waited 3 h) (answered)
4.  Step `erp` (#1 timed out) (#2 succeeded)
5.  Step `settle` (waited 9 days) (done)
6.  Step `keep` (#1 succeeded)

*A run holds one step per node it reached. A step holds its attempts: up to three by default, each claimed by one worker.*

-   A **run** is one flow over one arrival. It is never claimed by a worker itself; its steps are, and the run's state sums them up.
-   A **step** is one node the run reached. It has the same states as the run, plus `skipped`.
-   An **attempt** is one try at a step, claimed by exactly one worker. A step runs once, and up to twice more after an outage or a lost worker: three attempts by default. Only the worker that holds the current attempt can finish it, so a slow worker that lost its claim cannot overwrite the result.

A step that changes something outside Lumen (sends an email, calls an API, saves to a connection) is marked as having **side effects**. Retrying a run, or running it again from a step, asks before repeating such a step.

> **Retries and side effects:**
> 
> An automatic second attempt of an API call is still a second call. Give side-effecting calls an idempotency key, as the ERP check in the example below does, so the receiving system can recognise a repeat.

## The flow as YAML

The flow in the diagram, as the resource the console saves. It comes from the repository's examples and validates against the built-in catalog.

**YAML:**

```yaml title="invoice-approval.yaml"
apiVersion: lumen.ai/v1alpha1
kind: Flow
metadata:
  name: invoice-approval
  namespace: tenant-acme
spec:
  displayName: Invoice approval
  triggers:
    - id: email
      ref: {name: email-arrives}
      connectorRef: {name: invoices-inbox}
      next: [suppliers]
  nodes:
    - id: suppliers
      filter:
        when: {field: email.from, op: contains, value: "@supplier.example"}
      next: [text]
    - id: text
      stepRef: {name: read-text}
      next: [details]
    - id: details
      stepRef: {name: chat-agent}
      config:
        instructions: Find these details in the invoice.
        fields: [{name: supplier}, {name: total, hint: Amount due, type: money}]
        files: {mode: ifNoText}
      next: [route]
    - id: route
      branch:
        - when: {field: details.total, op: gte, value: 10000}
          next: [approver]
      branchDefault: [erp]
    - id: approver
      approval:
        to: approvals@acme.example
        subject: "Approve {details.supplier}, {details.total}?"
        timeout: 48h
        fields:
          - {name: approved, label: Approve payment, type: boolean, required: true}
          - {name: comment, type: text}
      next: [keep]
    - id: erp
      stepRef: {name: http-request}
      config:
        method: POST
        url: https://erp.acme.example/api/invoices/check
        body: '{"supplier": "{details.supplier}", "total": {details.total}}'
        idempotencyKey: "{email.from}-{details.supplier}-{details.total}"
        outputs:
          - {name: dueDate, type: date, jsonPath: $.dueDate}
      next: [settle]
    - id: settle
      wait: {until: erp.dueDate}
      next: [keep]
    - id: keep
      stepRef: {name: save-file}
```

**Console:**

1.  **Flows**, then **New flow**. Choose **When an email arrives** and pick the forwarding address.
2.  Add **Filter** and set it to *From contains @supplier.example*.
3.  Add **Read the text**, then from **AI** the agent step, with the fields *supplier* and *total*.
4.  Add **Branches** with one path, *details.total is at least 10000*, then **Add an "Otherwise" path**.
5.  On the **Otherwise** path add **Call API** and then **Wait** until *erp.dueDate*.
6.  Join both paths into **Save the file**, then **Save and enable**.

The editor cannot draw an approval node yet, so add the approval on the first path in YAML (see [Approvals](https://docs.go-lumen.ai/approvals/approvals.md)). A run of a flow that has one shows it on the run page.

**CLI:**

```bash title="Apply the flow and cancel a run"
lumen apply -f invoice-approval.yaml
# a run waiting on an approval can be stopped by its id
lumen cancel run 87912742-2bba-5bfa-b40d-9b6fd7a81d76
```

The flow above starts only from email. To start it from the CLI with `lumen run`, give it a [`manual-run`](https://docs.go-lumen.ai/reference/triggers/manual-run.md) trigger as in [Your first flow](https://docs.go-lumen.ai/getting-started/first-flow.md#the-same-flow-as-yaml).

## Next steps

[Your first flowBuild and run a flow from a template in ten minutes.](https://docs.go-lumen.ai/getting-started/first-flow.md)[Step referenceWhat each step needs, produces and takes as settings, generated from the catalog.](https://docs.go-lumen.ai/reference/steps/send-email.md)[Approvals and questionsThe approval node in full: who is asked, fields, reminders and timeouts.](https://docs.go-lumen.ai/approvals/approvals.md)[Credits and budgetsWhat a run costs, and what holds a run when the budget is used up.](https://docs.go-lumen.ai/concepts/credits-and-budgets.md)
