> ## Documentation Index
> Fetch the complete documentation index at: https://docs.canary.effectiveai.app/llms.txt
> Use this file to discover all available pages before exploring further.

# for-each node

> Run a block of steps once for every item of a list, in order or a few at a time, and collect the results in item order.

A `for-each` runs one heading body once per element of a list the run already has, such as the
policies in a batch, and gathers per-item results into lists ordered like the input. Each item
can call your systems, route, or ask a person or an agent session. Use
[`repeat`](https://docs.canary.effectiveai.app/procedures/reference/nodes/repeat) when the number of rounds depends on what each round
produces, and [`parallel`](https://docs.canary.effectiveai.app/procedures/reference/nodes/parallel) for a fixed set of different
workstreams.

## Syntax

```yaml for-each id=send-notices theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
items: $inputs.policies
item:
  name: policy
  schema: policy
body: '#send-one-notice'
concurrency: 5
collect:
  receipts:
    schema: receipt-list
    from: $mail_receipt
```

## Fields

| Field | Type | Required | Default | What it does |
| - | - | - | - | - |
| `items` | reference | Yes | None | One reference to a required array, such as `$inputs.policies` or an earlier step's list |
| `item.name` | name | Yes | None | A new name for the current element. The body reads it as `$<name>`, such as `$policy` |
| `item.schema` | schema id | Yes | None | The schema of one element. The array's element schema must fit it |
| `body` | quoted `'#block'` | Yes | None | The child heading that runs once per item |
| `concurrency` | positive integer | No | `1` | How many items may run at the same time. `1` runs them one after another, in list order |
| `collect` | mapping | No | None | Lists to build from every item. Each entry has an array `schema` and a per-item `from` reference |
| `collect.<name>.schema` | schema id | With `collect` | None | The schema of the finished list |
| `collect.<name>.from` | reference | With `collect` | None | The per-item value to add, such as `$mail_receipt` or `$review.value.verdict` |

The fence takes no attributes after `id`, and its body takes no other fields.

### The body

The `for-each` follows the same heading rules as a
[`choice`](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice#heading-bodies): it is the last fence in its
section, `body` is a direct child heading of that section, and the run continues at the next
heading after it.

* The body can hold any steps: calls, values, tasks, agents, waits, and nested `choice`, `repeat`
  or `for-each` constructs. Tasks and agents are allowed at any `concurrency`.
* The item name and every value the body binds belong to that item. Items running at the same
  time can't see or overwrite each other's values. The item name can't reuse a name that is
  already visible.
* Every value a `collect` entry reads must be bound on every path through the body.
* `complete` isn't allowed in the body. Ending the run from one item would cut the other items
  short. Route or complete after the `for-each`, using the collected lists.

### Collected lists

Each `collect` entry becomes a list named after the entry, such as `$receipts`, that later steps
can read. The list is in item order, the order of `items`, whatever order the items finish in. It
is checked against its `schema` when the `for-each` ends. Values the body binds that aren't
collected can't be read after the `for-each`.

An empty `items` list runs no item and produces empty lists.

### Limits and failures

* A list with more than 1,000 items fails the run with `failure.code` `for_each_limit` when the
  `for-each` starts.
* If one item fails, for example its effect runs out of retries, the run fails. No new item starts,
  open tasks of items still running are cancelled before the run ends, and no collected list is
  produced. A write that an earlier or concurrent item already sent may still reach your system;
  failing the run doesn't undo it.
* To handle an expected per-item problem, such as a policy the mail vendor refuses, return it as
  data from the item's effect, for example a `status` member, and route on it after the
  `for-each`. Then every item still collects a result.

## Example

This procedure sends a past-due notice for every policy in a batch, five at a time. The effect
sends the step's idempotency key so the mail vendor can drop a duplicate if a retry repeats a
request. The vendor host and policy values are illustrative.

````markdown past-due-notices.procedure.md theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
---
kind: procedure@v0
id: past-due-notices
inputs:
  policies: { schema: policy-list }
outputs:
  result: { schema: notice-report }
---

# Past-due notices

Send a past-due notice for every policy in the batch, five at a time.

## Send the notices

```yaml for-each id=send-notices
items: $inputs.policies
item:
  name: policy
  schema: policy
body: '#send-one-notice'
concurrency: 5
collect:
  policy_numbers:
    schema: string-list
    from: $policy.policyNumber
  receipts:
    schema: receipt-list
    from: $mail_receipt
```

### Send one notice {#send-one-notice}

Queue the notice with the mail vendor and keep its tracking ID.

```yaml call id=queue-notice
function: '@local.queue-mail-notice'
input:
  policyNumber: $policy.policyNumber
  insuredName: $policy.insuredName
  amountDue: $policy.amountDue
output: mail_receipt
```

## Report

```yaml complete id=finish
value:
  policyNumbers: $policy_numbers
  receipts: $receipts
```

## Resources

```yaml schema id=policy
type: object
additionalProperties: false
required: [policyNumber, insuredName, amountDue]
properties:
  policyNumber: { type: string }
  insuredName: { type: string }
  amountDue: { type: string, format: decimal }
```

```yaml schema id=policy-list
type: array
maxItems: 1000
items: { $ref: '#/schemas/policy' }
```

```yaml schema id=mail-receipt
type: object
additionalProperties: false
required: [trackingId]
properties:
  trackingId: { type: string }
```

```yaml schema id=receipt-list
type: array
maxItems: 1000
items: { $ref: '#/schemas/mail-receipt' }
```

```yaml schema id=string-list
type: array
maxItems: 1000
items: { type: string }
```

```yaml schema id=notice-report
type: object
additionalProperties: false
required: [policyNumbers, receipts]
properties:
  policyNumbers: { $ref: '#/schemas/string-list' }
  receipts: { $ref: '#/schemas/receipt-list' }
```

```ts effect id=queue-mail-notice input=policy result=mail-receipt uses=fetch
async (policy, { fetch, operation }) => {
  const response = await fetch('https://mail.northwind.example/notices', {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'idempotency-key': operation.idempotencyKey,
    },
    body: JSON.stringify(policy),
  });
  if (!response.ok) throw new Error(`Mail vendor returned ${response.status}.`);
  return { trackingId: response.headers.get('x-tracking-id') ?? '' };
};
```
````

Given policies `NW-100234`, `NW-100517` and `NW-100902`, the run ends with
`policyNumbers: ["NW-100234", "NW-100517", "NW-100902"]` and one receipt for each, in that order,
even if the second notice is queued last.

### Ask a person about each item

An item body can hold a task. With `concurrency: 2`, at most two review tasks are open at a time,
and the verdicts are collected in item order. This excerpt leaves out the schemas.

````markdown theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
```yaml for-each id=review-entries
items: $inputs.entries
item:
  name: entry
  schema: entry
body: '#review-one'
concurrency: 2
collect:
  verdicts:
    schema: verdict-list
    from: $entry_review.value.verdict
```

### Review one entry {#review-one}

```yaml task id=review-entry
assignees: [group:underwriting]
title: Review {{ $entry.name }}
instructions: Confirm the entry {{ $entry.name }} reads well.
result:
  schema: review-verdict
output: entry_review
```
````

## On retry and resume

* **Each item is its own step.** The same step has a different identity for each item. Each
  item's call, task or agent session runs once for that item, and an effect's
  `operation.idempotencyKey` differs between items and stays the same across retries of one item.
* **Finished items aren't run again.** When a run resumes, items that finished keep their recorded
  results. Only unfinished work continues.
* **Order doesn't depend on timing.** With `concurrency` above 1, items finish in any order, but
  collected lists are always in item order. New items start in list order as earlier ones finish.
* **All lists appear together.** Collected lists become visible in one step when the last item
  finishes, never partly.
* **Failure cleans up.** When one item fails, open tasks of other items are cancelled before the
  run is marked failed.

## Common errors

| Code | Cause | Fix |
| - | - | - |
| `PROC-FOREACH-001` | An unknown or missing field, a bad `item`, or a `concurrency` that isn't a positive integer, such as `0` | Use the fields above, with `concurrency` of 1 or more |
| `PROC-FOREACH-002` | `items` is unknown, optional or not an array, or its elements don't fit `item.schema` | Point at a required array whose element schema fits `item.schema` |
| `PROC-FOREACH-003` | The item name collides, a `collect.from` isn't bound on every path, or the body contains `complete` (`complete is not permitted inside a for-each body.`) | Rename, bind the value on every path, and complete after the `for-each` |
| `PROC-REGION-001` to `PROC-REGION-003` | The body heading is missing, misplaced or used by another construct | Follow the [heading rules](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice.md#heading-bodies) |

At run time, a list longer than 1,000 items fails the run with `for_each_limit`. Split large
batches before the `for-each`, or run them as separate runs.

## See also

* [repeat node](https://docs.canary.effectiveai.app/procedures/reference/nodes/repeat.md)
* [parallel node](https://docs.canary.effectiveai.app/procedures/reference/nodes/parallel.md)
* [call node](https://docs.canary.effectiveai.app/procedures/reference/nodes/call.md) and [function and effect](https://docs.canary.effectiveai.app/procedures/reference/nodes/function-and-effect.md)
* [Writes to your systems](https://docs.canary.effectiveai.app/procedures/concepts/writes-to-your-systems.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.