# Split and aggregate

> Run a stretch of a workflow once per item of a list with a split step, then collect every item's result with an aggregate step.

Source: https://developers.manykind.ai/agents/workflows/split-and-aggregate/

A **split** step opens an item region and an **aggregate** step closes it. Every step between them runs once per item: an agent is asked once per ticket, a model is called once per chunk, a person answers once per item. The aggregate waits until its policy is met, then hands every item's result on as one list.

Use a region when each item needs more than one step, or a step that waits (an agent, a person, a connector action). For a single model call per list entry, the model step's `each` option is simpler: see [Steps: Model](https://developers.manykind.ai/agents/workflows/steps/#model).

## How a region runs

```
trigger → split ──→ classify → reply ──→ aggregate → output
              (once per item, up to 8 at a time)
```

1. The split reads a list from the carried item, for example `$json.tickets`.
2. Each list entry becomes an item. A step inside the region receives the carried item with the entry's fields spread over it, plus `itemIndex` (0-based position in the list) and `itemKey`. An entry that is not an object arrives as `$json.item`.
3. The list field itself is removed from what each item carries, so 200 tickets are not copied into every per-item step.
4. Each item walks the region independently until it reaches the aggregate.
5. When the aggregate's policy is met, the region closes and the run continues once, with the results under the aggregate's `into` field.

![A split and aggregate drawn as a region frame around two per-item steps](https://developers.manykind.ai/shots/workflow-region.png)
## Split parameters

| Param | Builder label | Values | Default | What it does |
|---|---|---|---|---|
| `source` | Items from: **A list on the item**, then **List field** | `{ list: "<field>" }` | required | The dot path of the list to walk, read from the carried item. |
| `mode` | Items run: **One at a time** / **Several at once**, then **At most at once** | `"sequential"`, `"parallel"`, or `{ parallel: n }` | `"sequential"` | Sequential walks one item at a time. `"parallel"` walks up to 8 items at once per region; `{ parallel: n }` sets the bound, 1 to 64. |
| `itemLabel` | Item label | text or a mapping | none | What run views call each item, such as `"={{ $json.name }}"`. |

An empty list closes the region at once and the aggregate hands on zero results.

## Aggregate parameters

| Param | Builder label | Values | Default | What it does |
|---|---|---|---|---|
| `split` | Closes | a split step's id | required | The split this aggregate closes. Each split has exactly one aggregate. |
| `policy` | Carries on when | `"all"`, `"any"`, `{ atLeast: n }` | `"all"` | When the region closes: every item finished, the first item done, or `n` items done. |
| `order` | Order | `"seq"` (**Item order**) or `"arrival"` (**As they arrived**) | `"seq"` | Order of the results list. |
| `into` | Save items as | a field name | `"items"` | Where the results land on the carried item. |
| `close` | | `{ after, minDone?, early? }` | none | A deadline on the region. Code only; see [Close a region early](#close-a-region-early). |

The aggregate writes this object under `into`:

```json
{
  "items": [
    { "itemKey": "split#1#0", "itemIndex": 0, "state": "done", "result": { "category": "billing" } },
    { "itemKey": "split#1#1", "itemIndex": 1, "state": "done", "result": { "category": "bug" } }
  ],
  "reason": "complete",
  "count": 2,
  "total": 2
}
```

`result` is the carried item as it reached the aggregate. `count` is how many items finished `done`; `total` is how many items the list held. `reason` is `complete` when the policy was met, `deadline` or `forced` when a person closed the region. When the region closes before every item finished, items still queued or running are listed with their state and no result, and their later answers are dropped.

## Close a region early

`close` gives a region a deadline, so a region waiting on people who never answer can still finish.

| Field | What it does |
|---|---|
| `after` | Minutes the region stays open once the split is entered, 1 to 1440. A number or a mapping read from the item the split received. A value outside that range fails the run at the split. |
| `minDone` | Items that must be done before the region can close. Default 1. |
| `early` | `"initiator"` lets the person who started the run close it before the deadline. |

```ts
{ id: "collect", kind: "aggregate", params: { split: "each-reviewer", policy: "all", close: { after: 60, minDone: 2 } } }
```

Nothing fires on its own at the deadline. Once it has passed, the region closes when a member of the run asks for it (`workflow.region_close` with `runId` and the aggregate's `nodeId`) or when the next item finishes, provided `minDone` items are done. The initiator closes it before the deadline with `now: true` on the same event, when `early` allows it. A refused request is announced as `workflow.region_close_refused` with a `why`: `not_open`, `not_member`, `not_initiator`, `not_early`, `not_due`, or `too_few`.

## Example

Triage a batch of tickets: one model call and one cubby write per ticket, several tickets at once.

```ts
nodes: [
  { id: "batch", kind: "trigger" },
  { id: "each-ticket", kind: "split", params: { source: { list: "tickets" }, mode: "parallel" } },
  {
    id: "classify",
    kind: "model",
    params: {
      alias: "llm",
      input: {
        messages: [{ role: "user", content: "=Classify as billing, bug or question:\n{{ $json.text }}" }],
        max_tokens: 16,
      },
      into: "classification",
    },
  },
  {
    id: "save",
    kind: "cubbyExec",
    params: {
      alias: "triage",
      sql: "INSERT INTO triage_tickets (run_id, ticket_id, category) VALUES ('{{ $runId }}', ?, ?)",
      args: ["={{ $json.id }}", "={{ $json.classification.text }}"],
    },
  },
  { id: "collect", kind: "aggregate", params: { split: "each-ticket", policy: "all", into: "triaged" } },
  { id: "done", kind: "output" },
],
edges: [
  { from: "batch", to: "each-ticket" },
  { from: "each-ticket", to: "classify" },
  { from: "classify", to: "save" },
  { from: "save", to: "collect" },
  { from: "collect", to: "done" },
],
```

Start it with a payload like `{ "tickets": [{ "id": "T-1", "text": "I was charged twice" }, { "id": "T-2", "text": "The export button does nothing" }] }`.

## Per-item waits

Agent, connector action, and person steps inside a region wait per item. Each item's answer is matched to that item, so answers can arrive in any order. A loop edge inside a region counts per item, which is how you retry one item without touching the others.

A person's step inside a region:

- must be an assigned step (it declares `assignees`, `policy`, `options`, or another assigned-step param), so each answer names its item. See [People in workflows](https://developers.manykind.ai/agents/workflows/people/).
- is allowed in a sequential region, or in a parallel region that declares its bound (`{ parallel: n }`, **At most at once**). A plain `"parallel"` region is refused, because every item would hold a person's wait open at once.

## Failures

A failed item fails the run. The aggregate's `onItemError` param accepts only `"fail-run"`, which is also the default.

## Rules the graph must follow

`mk build` and the runner refuse a graph that breaks any of these, before the run has any effect:

| Rule | Why |
|---|---|
| Every split has exactly one aggregate whose `split` names it. | One region, one place where items come back. |
| No split inside a region. | Nested regions are not supported. |
| No `join` inside a region. | An item's branches would join across items. |
| No trigger inside a region. | It would start runs from inside one item. |
| Edges enter a region only through its split and leave only through its aggregate. | An item that leaves by a side door never reaches the aggregate, so the region never closes. |
| A loop edge may not cross the region boundary. | Same reason. |
| The split has at least one edge out. | Otherwise no item is walked. |

## Limits

| What | Limit |
|---|---|
| Items in flight per region, `"parallel"` | 8 |
| Items in flight per region, `{ parallel: n }` | 1 to 64 |
| Region deadline (`close.after`) | 1 to 1440 minutes |
| Items in flight, sequential mode | 1 |
| Nested regions | not supported |
| `onItemError` | `fail-run` only |

## Related

- [Next: Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/)
- [Steps](https://developers.manykind.ai/agents/workflows/steps/)
- [People in workflows](https://developers.manykind.ai/agents/workflows/people/)
- [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/)
