# Durable steps

> ctx.run, what it guarantees, and what has to go inside it.

Source: https://cairnflow.dev/docs/develop/durable-steps

`ctx.run` runs a piece of code once and records its result in the invocation's journal. When the
handler replays — after a crash, a deploy or a wait — the step returns the recorded result and the
closure is not called again.

```ts
const receipt = await ctx.run("charge", () => chargeCard(order.amount));
```

```ts
run<T>(
  name: string,
  fn: (signal: AbortSignal) => Promise<T> | T,
  opts?: { cancellable?: boolean },
): Promise<T>;
```

## What it guarantees

1. The closure runs.
2. The SDK sends the result to cairnflow and **waits until it is durable** before the handler goes
   on. Only then do later steps run.
3. On every later replay, `ctx.run` returns the recorded result.

If the process dies **while the closure is running**, the result is unknown, so the closure runs
again on the next attempt. This is the at-least-once part no runtime can remove: nobody knows how
far a network call got. Make the work inside a step idempotent — for example, pass an idempotency
key to the payment API derived from `ctx.invocationId` and the step name.

If the process dies **after** the result is durable, the step never runs again.

## The result is JSON

Results are stored with `JSON.stringify` and read back with `JSON.parse`, and the handler always
continues with the stored value. Return plain data:

- `undefined` becomes `null`.
- A `Date` becomes a string; `Map` and `Set` become `{}`; class instances lose their methods.
- A result whose encoded frame is over 16 MiB is not sent: the step fails for good with a
  `TerminalError` of code `413`, recorded like any other result, so the closure does not run
  again.
- Put files and images in an [artifact](/docs/develop/artifacts) and return the reference. Large
  JSON results are stored as segments rather than inline; see
  [Payload](/docs/cloud/limits#payload) for the limits on Cairnflow Cloud.

:::caution
Do not return secrets (API tokens, keys) from a step. Results are stored in the journal and shown
in the console. Read secrets from the environment inside the closure instead.
:::

## Step names are part of the journal

On replay, the SDK checks each command against the journal: its kind, its name (for `ctx.run`,
the step name), and every other field it records, such as a call's target, key and input. If a
deploy renames a step, an in-flight invocation that reaches it stops in the `paused` state with
code `570` (journal mismatch) instead of running the wrong code.

- Keep names stable across deploys.
- Do not put configuration in names (model IDs, prompt versions). Put them in
  [span attributes](/docs/develop/streams-logs) instead.
- Names built from data are fine when the data is deterministic, for example
  `` ctx.run(`dig/${section}`, ...) `` inside a loop over the input.

See [Deploying new versions](/docs/develop/versioning) for how to change step names safely.

## Errors inside a step

| The closure throws | What happens |
|---|---|
| A normal `Error` | Nothing is recorded. The current turn fails and is retried under the handler's retry policy; on retry, completed steps replay and this closure runs again. Any `ctx` command after the failure throws `TurnFailed`, even if your code catches the error |
| `RunFailure(message, code)` or `TerminalError(message, code)` | The failure **is** recorded, and the SDK waits until it is durable. `ctx.run` then throws a `TerminalError` with that code and message, now and on every replay. The step never runs again. Catch it to compensate, or let it fail the invocation |

Use `RunFailure` or `TerminalError` when your code decides that a failure is permanent — a
`410 Gone` from the other side, a vendor that has not answered after several attempts:

```ts

const note = await ctx.run(`dig/${section}`, async () => {
  if (ctx.attempt >= 5) {
    throw new RunFailure(`vendor did not answer after ${ctx.attempt} attempts`, 503);
  }
  return callVendor(section);
});
```

More in [Errors and retries](/docs/develop/errors-retries).

## Deterministic helpers

The handler body outside `ctx.run` must take the same path on every replay. Use these instead of
non-deterministic sources:

| Instead of | Use |
|---|---|
| `Math.random()` | `ctx.random()` — a seeded generator that replays the same sequence |
| `Date.now()`, `new Date()` | `await ctx.run("now", () => Date.now())` |
| `crypto.randomUUID()` | `await ctx.run("id", () => crypto.randomUUID())` |
| Your own invocation ID | `ctx.invocationId` |
| Retry counter | `ctx.attempt` — attempts since the handler last made progress (0 on the first run) |

Waits have their own deterministic form: `ctx.sleep` computes its wake-up time once and records it.

## What must go inside ctx.run

Anything whose result can differ between two runs, or that touches the outside world:

- HTTP calls, model calls, tool calls, database reads and writes, sending email.
- Reading the clock or generating random IDs.
- Reading anything that can change between attempts (files, environment-dependent lookups) when the
  handler's path depends on it.

Pure computation on the handler's input and on previous step results can stay outside.

## Long steps and parallel steps

- Only the streaming transport (`BIDI_STREAM`) keeps the connection alive while a closure runs, so
  a long closure is not cut there. In request-response mode each turn is one HTTP request and must
  finish within the handler's `inactivityTimeout`, and on a serverless platform within the
  platform's time limit too. That is always the case with `fetchHandler`, and on Cairnflow Cloud
  it is also the case for `serve()` unless you register the deployment with
  `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)).
- A step that runs past that limit is cut and retried: its closure runs again from the start, and
  without a retry policy the retries do not stop. Split long work into several shorter steps, or
  declare a longer `inactivityTimeout` for the handler
  ([Handler options](/docs/develop/services#handler-options)). The default and the upper bound on
  Cloud are in [Turn time limit](/docs/cloud/limits#turn-time-limit).
- Several steps can run at once with `Promise.all([ctx.run(...), ctx.run(...)])`. Results reach
  your code in the order they were recorded in the journal, so parallel branches take the same
  path on every replay. Code after `await ctx.run(...)` never runs in the same turn as that
  step's closure: do not make a closure wait for something only that later code would do.

## Cancellation

By default a step is not interrupted by a cooperative cancel, so compensation steps still run. Mark
forward steps (model calls, tools) with `{ cancellable: true }`: they do not start once the
invocation is cancelled, and their closure receives an `AbortSignal` that fires if the cancel
arrives mid-step (streaming mode only). See [Cancellation](/docs/develop/cancellation).

```ts
const page = await ctx.run(
  "fetch",
  (signal) => fetch(url, { signal }).then((r) => r.text()),
  { cancellable: true },
);
```
