# Cancellation

> Cooperative cancel that lets your code clean up, hard cancel as the fallback, and how steps react.

Source: https://cairnflow.dev/docs/develop/cancellation

There are two ways to cancel an invocation.

| | Cooperative (`mode=signal`) | Hard |
|---|---|---|
| HTTP | `POST /invocations/{id}/cancel?mode=signal` | `POST /invocations/{id}/cancel` |
| Client | `handle.cancel()` (the default) | `handle.cancel({ mode: "hard" })` |
| Key needed | One that can invoke handlers | An admin key |
| Your code | Gets a `TerminalError` (code `409`) at its next wait, and can clean up | Gets no further turn |
| Ends as | Whatever your code does — usually `failed` with `409` | `failed` with code `572` |
| Needs your service up | Yes | No |

Both answer `{"cancelled": true|false, "status": ...}` once the invocation has stopped;
`cancelled` says whether it really stopped. Cancelling an invocation that already finished is a
no-op: `{"cancelled": false, "status": "completed"}`.

## Cooperative cancel

Cairnflow delivers a cancel signal to the invocation. From then on, every **wait point** throws
`TerminalError` with code `409`, so your `try/catch/finally` can undo what was done:

```ts
async run(ctx: Context, order: Order) {
  const undo: Array<() => PromiseLike<unknown> | void> = [];
  try {
    const charge = await ctx.run(
      "charge",
      (signal) => payments.charge(order, { signal }),
      { cancellable: true },
    );
    undo.push(() => ctx.run("refund", () => payments.refund(charge.id)));
    await ctx.promise<boolean>("shipped").get();
    return "done";
  } catch (e) {
    if (e instanceof TerminalError) {
      for (const step of undo.reverse()) await step();
      ctx.send("Email", "orderCancelled", { orderId: order.id });
    }
    throw e;
  }
}
```

Each undo step is registered only after its forward step has a result, and the list is rebuilt the
same way on every replay.

In streaming mode (`BIDI_STREAM`, which `serve()` declares), a cancel that arrives in the middle
of a turn reaches the handler at once. In request-response mode there is no channel into a running
request: the cancel takes effect from the next turn. That is always the case with `fetchHandler`,
and on Cairnflow Cloud also with `serve()` unless the deployment is registered with
`"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)).

### What is and is not a cancellation point

| Command | After a cooperative cancel |
|---|---|
| `await` on something not finished yet: `ctx.sleep`, `ctx.call`, `ctx.promise(...).get()`, `ctx.signal`, an awakeable, `ctx.all`, `ctx.race` | Throws `TerminalError` 409 |
| `ctx.run(name, fn)` (default) | **Runs normally.** Compensation steps are `ctx.run`, and they must work after a cancel |
| `ctx.run(name, fn, { cancellable: true })` | Does not start; throws 409. If the cancel arrives while the closure runs (streaming mode only), its `AbortSignal` fires |
| `ctx.send`, `ctx.set`, `ctx.clear` | Run normally |
| A result already in the journal | Returned normally |

This is why compensation code should use only `ctx.run` (not cancellable) and `ctx.send`: a
`ctx.call` or a sleep in a `catch` block throws again at once.

### Cancellable steps

Mark forward work that is expensive or pointless after a cancel — model calls, tool calls, long
fetches — as `cancellable`:

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

- If the invocation is already cancelled and the step has no result yet, the closure does not run
  and `ctx.run` throws 409.
- If the cancel arrives while the closure runs (streaming mode only), the `AbortSignal` passed to
  the closure fires. Whatever the closure throws afterwards becomes a 409; nothing is recorded.
- If the closure ignores the signal and returns normally, its result is recorded as usual.

### The service must be reachable

Cooperative cancel needs your code to run. If your service is down, the invocation keeps waiting
for it. That is what the hard cancel is for.

## Hard cancel

A hard cancel writes the terminal state directly, without asking your code:

- The invocation ends `failed` with code `572`. Callers waiting on it with `ctx.call` get that
  failure.
- If it held a virtual object's key, the next invocation in the queue runs.
- A turn already running on your service is not cut off. It runs to its next natural stop; its
  steps have run (and cost what they cost), and its state writes still apply. Only its outcome is
  discarded.
- Pending timers and retries are discarded when they come due.
- Your `catch` blocks never run: a saga does not compensate on a hard cancel.

### Propagation to children

A hard cancel also cancels every invocation it created with `ctx.call` and is still waiting for,
recursively down the tree. Calls not yet dispatched are never sent. Invocations started with
`ctx.send` are detached work and are **not** cancelled; cancel them by ID.

## Choosing

Use cooperative cancel by default: it lets you refund, release and notify. Fall back to the hard
cancel when the service cannot answer, or when you need the invocation stopped regardless of what
its code does.
