# Steps and undo

This page is the inline step's three forms, what a step may return, and when to reach for `defineStep` or `defineExternalStep`. The commands it teaches are `durable-sdk doctor --host` and `durable-sdk explain <refusal id>`.

## The three forms

`ctx.step(name, body, options)` runs a step through the recorder: replay by `seq:name` on a later attempt, strict assertions, the compensation truth. `options` says what the step did to the world, and the door refuses a step that says neither:

```ts
// A write with its undo: the body calls a provider and hands the answer back.
const held = await ctx.step(
  "stock.reserve",
  (i) => stock.reserve(sku, qty, i.stop),
  {
    undo: (i, out) => stock.release(out.reservationId),
    effect: "provider",
  },
);

// A read, or a write nothing can take back: say why in words.
const lines = await ctx.step("cart.lines", () => countLines(ctx.input), {
  irreversible: "a count",
});

// A read that re-runs for free may land its row late and save a statement.
const cart = await ctx.step(
  "cart.read",
  () => carts.read(ctx.input.checkoutId),
  {
    irreversible: "a read",
    completion: "behind",
  },
);
```

Beside `undo`, `effect` is required: `"provider"` when the body calls a provider and hands its answer back (the recorder then writes the call's row to [the ledger](https://durablesdk.com/docs/concepts.md#the-ledger) itself, `provider/<step>`, and a row reversing it when the saga ran the undo), `"ledgered"` when the body appends its own row, `"external"` when it writes through a spec. Never `"read"`: an undo reverses a record, and a read writes none. An undo whose body is blank and an `irreversible` with no word in it are refused at the door, in every mode, before the body runs. The refusal ids are `step.undo.effect`, `step.undo.blank` and `step.undo.reason`; `durable-sdk explain step.undo.effect` prints the sentence, the trap and the remedy.

## Read before you write

A step body may run again after a crash between its write and its row. That is why every write reads first and does nothing when the world already matches: an **absolute** desired state ("status is captured") is idempotent by construction; a **relative** change ("+1") is not and needs its own keyed row. Judge first, as a value, then write once, and read the answer from the write's images, never from the row you read before it.

The body sees `i`: `i.runId`, `i.actor`, `i.attempt`, `i.signal`, `i.cancel`, `i.stop`, `i.deadlineAt`, `i.budget`, `i.secrets`, merged over the `input` you pass as the fourth argument. Pass `i.stop` to every provider call and every read: it aborts when the attempt loses its lease or a person cancels the run, so a call never outlives its attempt.

## What a step returns

A step's answer is its **stored form** on every attempt, the attempt that ran the body as the one that replays the row: a `Date` is its ISO string, a bigint its decimal, a `Map` its entries, a `Set` an array, an `undefined` dropped. `out.createdAt.getTime()` is a type error, never a crash after a crash. The undo sees the same form.

The output must fit its row (16 000 characters of stored JSON) and hold nothing the redaction policy blanks; a row the memo cannot serve re-invokes the step after any crash, and a `provider` step then calls its provider again. Return a bounded delta (ids, moments, the columns a caller keys on) and put the rest on the ledger. A one-time value (a token minted in the step) goes back through `ctx.reply(value)` and is never stored.

## A retry

A read may retry on the codes it names; a write may not be retried blindly:

```ts
await ctx.step("tax.quote", () => taxes.quote(ctx.input.checkoutId), {
  irreversible: "a read",
  timeout: "10s",
  retry: {
    attempts: 3,
    delays: ["400ms", "2s"],
    codes: ["http_5xx", "StepTimedOut"],
  },
});
```

`retry` and `timeout` sit on the `irreversible` branch alone; a write's retry belongs to its spec. Every duration is one grammar: `"<n>ms"`, `"<n>s"`, `"<n>m"`, `"<n>h"`, `"<n>d"`. A retry whose delay would end past the attempt's budget parks the run instead of holding the function; `resume: "park"` parks at every retry.

## A compensation

When a later step throws, the saga runs the completed steps' undos in reverse of their completion order. Each undo gets `(i, out)`: the context and the step's stored output. A compensation that changed state writes its own `<step>.undo` row with the image it found and the image it restored; one that cannot (the world moved under it) fails by name, and the run stays `FAILED` for a person with the step named, so nothing is written over what a later actor did. A step that said `irreversible` is listed as such on the run's `compensation`. `COMPENSATED` means every compensable step was undone and the run's error names what was not.

## An external write

A write a provider cannot repeat (a charge, a label, a message) goes through an external step: the engine drives its phases and records the intent before the call, so a redrive after a lost answer finds what landed instead of writing again.

```ts
import { defineExternalStep, type ExternalStepInput } from "@durable-sdk/core";

export const capturePayment = defineExternalStep<
  ExternalStepInput & { checkoutId: string; amount: number },
  { paymentId: string; status: "authorized" | "captured" }
>({
  name: "payment.capture",
  undo: (i, _before, current) => payments.refund(current.paymentId, i.stop),
  resource: (i) => ({
    shop: i.shop,
    resourceType: "payment",
    resourceId: i.checkoutId,
    operation: "update",
  }),
  read: async (i) => payments.read(i.checkoutId, i.stop),
  compare: (current, desired) => desired?.status === current.status,
  desired: () => ({ status: "captured" }),
  image: (s) => s,
  write: async (i) => payments.capture(i.checkoutId, i.amount, i.stop),
  retry: { idempotent: true, classify: () => false, delays: ["400ms"] },
  timeout: "30s",
});
```

`read` the world, `compare` it with `desired`, `write` only when they differ, `image` what the ledger keeps. Under `retry.idempotent: false` the write is never repeated automatically and a cancel never aborts it in flight. Two writes under one `writeKey` in one step are refused at the second's door.

## `defineStep` for a shared step

A step two workflows share, or whose undo is longer than its body, is a `defineStep` both import, so its name, effect and undo are declared once:

```ts
import { defineStep } from "@durable-sdk/core";

export const reserve = defineStep<
  { sku: string; qty: number },
  { reservationId: string }
>({
  name: "stock.reserve",
  invoke: (i) => stock.reserve(i.sku, i.qty, i.stop),
  compensate: (i, out) => stock.release(out.reservationId),
  effect: "provider",
});

// in a body:
const held = await ctx.step(reserve, { sku, qty });
```

## Lightweight runs

A body that reads and computes and never writes may say `lightweight: true` on `defineWorkflow`: one run row and no step row, every `ctx.step` a read kept in memory and landed with the finish. A crash before the landing re-runs the body whole, so the door refuses a step with an undo, an external step, a wait, a child, a batch or a poll under the word. Declare it on a counter, a projection or a quote the next run re-derives; keep it off anything that touches a provider.

## Check it

`durable-sdk doctor --host` refuses a raw provider write in a step body outside an external step, a catch around `ctx.step` that swallows an abort, a `Promise.all` over steps (use `ctx.all`), and a clock read between steps. The refusals a door throws for steps are the `step.*` rows of [Refusals](https://durablesdk.com/docs/reference/refusals.md); [Testing](https://durablesdk.com/docs/guide/testing.md) crashes every step boundary for you.

---

Prompt for an agent:

```text
Read https://durablesdk.com/docs/guide/steps-and-undo.md, then write a step that changes the world so a crash, a retry or a compensation never doubles or loses it; run durable-sdk doctor --host before and after; a refused line is a refusal id: durable-sdk explain <id>
```
