# Changing a workflow

This page is what a run in flight sees when the body under it changes, and the four tools that keep that honest. The commands it teaches are `durable-sdk doctor --host` before the deploy and `durable-sdk deploy --prod` after; the console's Limbo view shows the runs a change abandoned.

A run that parked on a wait, or that waits in [limbo](https://durablesdk.com/docs/concepts.md#limbo), replays its completed steps from their rows on its next attempt, under whatever body is deployed then. The recorder replays a step by `seq:name` unless it carries an `id`.

## The four rules

**Add a step at the end, never reorder.** A step inserted in the middle shifts every seq after it. The next attempt meets another step's row at that seq and refuses it (`ReplayDiverged` on the row, the run `FAILED` before any re-invoke), so nothing lands twice; but the run is now a person's to redrive after a version bump.

**Give a step an `id` when it may move**, and give every step of a workflow that waits or has children an id from the start:

```ts
await ctx.step("label", body, { id: "label", undo, effect: "provider" });
await ctx.sleep("1h", { id: "nap" });
await ctx.waitFor("shipment.matched", { id: "matched", match, deadline });
await ctx.child(review, input, { id: "review" });
await ctx.poll("shipment", probe, {
  id: "shipment",
  every: "10m",
  until: "24h",
  done,
});
await ctx.batch("sweep", source, { id: "sweep", size: 100 }, body, undo);
```

An id is `[a-z0-9._-]+`, unique within the definition. The recorder replays the step by the newest prior row with that id whatever seq it sits at now, so an inserted step no longer re-invokes the ones after it. A step inside a loop spells its id per iteration at the call.

**Bump `version`** (`defineWorkflow({ version: 2 })`) when a step's meaning changes, when one is removed, or when an undo changes what it undoes, and no patch can carry the change. The version is stored on every run at its start; every run in flight under the old number lands `FAILED abandoned: version 1 → 2` with no compensation attempted, one cause in the console's Limbo view for the whole deploy, and a person redrives it under the new version ("Accept version 2") or dismisses it.

**Put a replaced branch behind `ctx.patched`** when a step is replaced by another and the runs in flight should finish under the branch they started, with no bump and no person:

```ts
if (await ctx.patched("invoice-v2")) {
  await ctx.step("invoice.v2", makeInvoiceV2, {
    id: "invoice.v2",
    irreversible: "an invoice issued",
  });
} else {
  await ctx.step("invoice", makeInvoice, {
    id: "invoice",
    irreversible: "an invoice issued",
  });
}
```

The call runs between steps, never inside one. On the attempt that first reaches it, it answers `true` and writes a marker row, `patch:<id>`, served on every later attempt. A resumed run answers what its rows say: the marker anywhere → `true`; another step's row at this point (the run walked the old branch before the deploy) → `false`, nothing written; no row at this point → `true` and the marker written. The dance has three deploys: (1) `patched` with both branches; (2) once no pre-patch run is open, `ctx.deprecatePatch("invoice-v2")` with the new branch alone, refused as a value (`PatchStillOpen`) while a run without the marker is still open; (3) remove the call. A rollback to the patched body after step 2 reads the marker and takes the new branch.

## What a run in flight sees

| The change                                 | What happens on the next attempt                                                                                                                   |
| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| A new step at the end                      | The completed prefix replays, the new step is invoked. No id, no bump.                                                                             |
| An inserted step, with ids                 | The steps before and after replay by id, the new step is invoked once. No bump.                                                                    |
| An inserted step, without ids              | `ReplayDiverged` on the row, the run `FAILED` before any re-invoke. Bump the version, redeploy, redrive.                                           |
| A step renamed under its id                | Refused the same way; fix the body and redrive.                                                                                                    |
| A step's input that moves between attempts | The clock, randomness or a row read outside a step: refused the same way. Read it inside a step with an id.                                        |
| Ids added to an existing workflow          | Every completed step re-invokes once (the rows key `seq:name`, the steps now `id`). Add them in a release that inserts nothing, or bump with them. |
| A branch behind `ctx.patched`              | An old run finishes its branch, a parked run takes the new branch at its frontier, a fresh run takes the new branch. No person.                    |
| A version bump                             | Every run in flight lands `FAILED abandoned: version 1 → 2`; a person accepts the new version on the run or the cause.                             |
| A rollback to an older version             | A bump the other way: `abandoned: version 3 → 2`, accepted with `acceptVersion: 2`.                                                                |

An attempt already executing the old body finishes under it; only the next attempt compares.

## A run that outgrows its history

A run replays every row it has on every wake, so a run of thousands of steps pays more per step the longer it lives. A run that walks a cursor, a page or a day at a time closes itself and goes on as a fresh run under the same key:

```ts
export const walkCatalog = defineWorkflow({
  name: "catalog.walk",
  key: ["walkId"],
  describe: "Walks the catalog a page at a time, one run per page.",
  example: { walkId: "w1", from: null as string | null },
  async run(ctx) {
    const { walkId, from } = ctx.input;
    const page = await ctx.step("page", () => readPage(from), {
      irreversible: "a read",
      effect: "read",
      id: "page",
    });
    await ctx.step("apply", () => apply(page.rows), {
      undo: () => revert(page.rows),
      effect: "provider",
      id: "apply",
    });
    if (page.next !== null)
      await ctx.continueAsNew({ walkId, from: page.next });
    return { walked: page.rows.length };
  },
});
```

`await ctx.continueAsNew(next)` after a step, never inside one. The call never returns: the run lands `CONTINUED` naming the next, which starts at once with its steps from seq 1. The next input must key to the same key (`from` is no key field). `{ carry: "state" }` carries `ctx.state` onto the next run. The chain is one intent: `execute` of the same input answers the newest run's outcome, the run page links the chain each way, and `verify` is green across it. Keep each run's history bounded (a page, a hundred steps, a day) and the cost per step is flat whatever the chain's length.

## Before the deploy

```bash
durable-sdk doctor --host
pnpm test
durable-sdk deploy --prod
```

The doctor refuses a reordered step without ids where it can see it and a wait without an id in a loop; the harness proves a crash at every step boundary under the new body ([Testing](https://durablesdk.com/docs/guide/testing.md)). After the deploy, the console's Limbo view lists what the change abandoned, each under its cause, with the redrive under the new version beside it ([Console](https://durablesdk.com/docs/operate/console.md)). The whole statement, with the proofs each sentence carries, is on the generated page [Workflows](https://durablesdk.com/docs/workflows.md).

---

Prompt for an agent:

```text
Read https://durablesdk.com/docs/guide/changing-a-workflow.md, then change a deployed workflow while runs of it are parked or in limbo without doubling a write or stranding a run; run durable-sdk doctor --host before and after; a refused line is a refusal id: durable-sdk explain <id>
```
