# Parallel steps and child runs

> Run steps concurrently with ctx.gather, and start other workflows with ctx.run_child.

Source: https://docs.pyrula.io/workflows/guides/parallel-and-children/

## Parallel steps

`ctx.gather` runs awaitables concurrently, results in argument order. Each leg is journaled, so a
resumed run re-runs only unfinished legs.

```python
from pyrula.workflows import workflow


@workflow(name="quote")
async def quote(ctx, skus: list[str]) -> int:
    prices = await ctx.gather(*[ctx.step(f"price:{s}", fetch_price, s) for s in skus])
    return sum(prices)
```

Give each step a distinct id. Two `ctx.step` calls with one id that run at the same time outside
`ctx.gather` (`asyncio.gather`, a task group, `create_task`) raise `ConcurrentStepIdError`, because
they would share a journal key.  `return_exceptions=True` returns exceptions as results instead
of raising the first.

Direct calls (an agent's tool, sub-agent and model calls, and the drop-in provider adapters) take no step id, so a resumed run matches each to its record by its inputs; a call whose inputs changed is refused before it runs ([Determinism](https://docs.pyrula.io/workflows/concepts/determinism.md)). Under `asyncio.gather` or a task group a resume mid-region may refuse with `REPLAY_INPUT_CHANGED`: use `ctx.gather` or give each call its own `id=`. Reusing an `id=` while an earlier call under it is still running raises `ConcurrentCallIdError` and ends the run.

### Bounding fan-out

Every leg starts at once by default. `max_concurrency=` caps legs in flight:

```python
@workflow(name="summarize_documents")
async def summarize_documents(ctx, docs: list[str]) -> list[str]:
    return await ctx.gather(
        *[ctx.step(f"summarize:{d}", summarize, d) for d in docs],
        max_concurrency=8,
    )
```

Legs start in argument order. The bound only delays starts; result order, step ids and replay
don't change. The first error cancels the rest, queued legs included. The cap counts legs, not steps.
(`par_map` is a separate process-based helper for CPU-bound work, sized with `workers=`.)

A leg can't wait. `ctx.sleep`, `ctx.sleep_until`, `ctx.wait_for_signal` and `ctx.interrupt`
inside a leg raise `SuspendInGatherLeg`, because a run has one suspension slot. Wait before or after
the gather. Tasks you start with plain `asyncio` may wait, but a task group cancels its other tasks
when one of them parks the run, so a call in flight there runs again after the answer. Put calls that
must run once in `ctx.gather`.

### Blocking calls in threads

`await ctx.to_thread(fn, *args, **kwargs)` runs a blocking function on a worker thread that carries the run's context, and `await ctx.map_threads(fn, items, max_workers=8)` runs it once per item in item order. A plain `threading.Thread` or `ThreadPoolExecutor` does not carry the context, so a model call there runs live again on every resume. See [Sync code and threads](https://docs.pyrula.io/agents/integrations/drop-in-clients.md#sync-code-and-threads).

```python
answers = await ctx.map_threads(ask, questions, max_workers=4)
```

## Child runs

`ctx.run_child` starts another registered workflow as its own run and waits for the result. The
child has its own journal, retries and version, and inherits the parent's owner.

```python
@workflow(name="ship")
async def ship(ctx, order: str) -> str:
    return await ctx.step("label", lambda: make_label(order))


@workflow(name="order")
async def order(ctx, order: str) -> dict:
    total = await ctx.step("total", lambda: price(order))
    label = await ctx.run_child("ship", {"order": order}, timeout=60)
    return {"total": total, "label": label}
```

- A worker serving the child's name must be running. The parent polls until it finishes.
- A failed child raises `ChildWorkflowError`. `timeout` bounds the wait.
- The child id derives from the parent's, so a replayed parent re-attaches to the same child.
- It composes with `gather`: `await ctx.gather(ctx.run_child("a"), ctx.run_child("b"))`.

`run_child` holds the parent's worker while it polls; it doesn't suspend the parent.

### What happens to a child when its parent ends

A child is open from when the parent journals it until the parent collects its result. If the
parent ends meanwhile (completes, fails, cancelled, terminated), the worker applies `parent_close`
before writing the parent's terminal event:

| `parent_close` | The open child |
| --- | --- |
| `"cancel"` (default) | Is asked to cancel, so its cleanup runs. Needs a worker. |
| `"terminate"` | Is ended at once, without its worker or cleanup. |
| `"abandon"` | Keeps running. |

```python
await ctx.run_child("notify", {"order": order}, parent_close="abandon")
```

Runs from `ctx.spawn_workflow` (agents) aren't children and are never closed this way.

Agents fan out with [`ctx.gather_subagents`](https://docs.pyrula.io/agents/authoring/context.md), which takes `(agent, kwargs)` pairs.
