# Undo that the verifier checks

This guide makes a workflow that takes money and then fails give the money back, on every
path, and has gvn check that before anything runs. At the end you have an order workflow
(charge, ship, refund on failure) whose plan is refused if any way to "cancelled" skips the
refund.

- **You will be able to:** declare that a stage's effects are undone by another stage, and
  have gvn prove, before anything runs, that every way your workflow can end "undone" really
  passes through that undo.
- **Read first:** [Workflows](../concepts/workflows.md) and [Errands](../concepts/errands.md).
  The [first tutorial](../tutorials/first-machine.md) shows what the verifier checks for a
  single machine.
- **Time:** about 15 minutes.

## Where this fits

In the [big picture](../quickstart.md#the-big-picture), the **actor** is a state machine
that gvn's **verifier** checks before it runs: in the quickstart, it refused a machine with
an unanswered case. This guide adds one more check to a
[workflow](../reference/glossary.md#workflow) (an actor whose states run child actors in
[**stages**](../reference/glossary.md#stage)): the verifier checks that paths to `cancelled`
complete the declared compensating stages. Your application implements and checks what those
stages undo.

The running example is an order: charge the card, then ship. If shipping fails, a successful
refund lets the order end as `cancelled`. A failed refund routes to `needs_person`:

```mermaid
flowchart LR
    charging["charging<br/><i>effect: money moves</i>"]
    shipping["shipping"]
    refunding["refunding<br/><i>undoes charging</i>"]
    delivered(["delivered"])
    cancelled(["cancelled<br/>= undone"])
    person(["needs_person"])
    charging -- "charged" --> shipping
    charging -- "not_charged" --> cancelled
    charging -- "charge_failed" --> refunding
    shipping -- "shipped" --> delivered
    shipping -- "not_shipped" --> refunding
    refunding -- "refunded" --> cancelled
    refunding -- "refund_failed" --> person
```

Nothing changes in the Governor, the fulfillers or the journal: the check happens when the
workflow's plan is built, before any run.

## The problem

The shop charges the customer's card, then ships the order. If shipping fails, the card must
be refunded and the order cancelled. This pattern has a name, a [**saga**](../reference/glossary.md#saga): a sequence of steps
with effects, where each step that has an effect has a [**compensation**](../reference/glossary.md#compensation), a later step that
undoes it, and a run that cannot finish undoes what it did, latest first.

The danger is not in the happy path. It is in the one path someone adds months later, say
"if the courier refuses the parcel, cancel the order", that goes straight to `cancelled` and
forgets the refund. Tests catch it only if someone thought to test that path.

In gvn you declare the pairs (this stage's effects are undone by that stage) and the final
states that mean "undone". The plan is then checked like the rest of the machine: every way to
an undone final state must pass through the compensations, in reverse order, or the plan is
refused and the message shows the way that skips them.

## Step 1: the machine

Three stages: `charging`, `shipping` and `refunding`. The function takes where a failed
shipment goes, so you can build a broken variant in step 4:

```python
from gvn.kernel.blueprint import MooreBlueprint
from gvn.kernel.definition import Definition
from gvn.kernel.symbols import Alphabet


def order_machine(when_not_shipped: str) -> Definition:
    return (
        MooreBlueprint(name="order")
        .inputs("started", "charged", "charge_failed", "not_charged")
        .inputs("shipped", "not_shipped", "refunded", "refund_failed")
        .outputs("idle", "charge", "ship", "refund", "delivered", "cancelled", "needs_person")
        .state(name="idle", output="idle")
        .state(name="charging", output="charge")
        .state(name="shipping", output="ship")
        .state(name="refunding", output="refund")
        .state(name="delivered", output="delivered", final=True)
        .state(name="cancelled", output="cancelled", final=True)
        .state(name="needs_person", output="needs_person", final=True)
        .initial(name="idle")
        .on(source="idle", input="started", target="charging")
        .branch(
            source="charging",
            outcomes=Alphabet.of("charged", "charge_failed", "not_charged"),
            routes={
                "charged": "shipping",
                "charge_failed": "refunding",
                "not_charged": "cancelled",
            },
        )
        .branch(
            source="shipping",
            outcomes=Alphabet.of("shipped", "not_shipped"),
            routes={"shipped": "delivered", "not_shipped": when_not_shipped},
        )
        .branch(
            source="refunding",
            outcomes=Alphabet.of("refunded", "refund_failed"),
            routes={"refunded": "cancelled", "refund_failed": "needs_person"},
        )
        .otherwise_stay()
        .build()
    )
```

Look at how `charging` can end:

- `charged`: the money moved.
- `charge_failed`: the call to the bank failed. A failed call **may have happened** (the bank
  may have charged and then lost the line), so this way goes through `refunding` too.
- `not_charged`: the call never ran (the policy forbade it, or a person declined it). Nothing
  moved, so this way may cancel at once.

`refunding` can fail as well. A failed refund does not end `cancelled`: it ends
`needs_person`, which says plainly that the undo could not be done.

## Step 2: the stages

Each stage is a `Host` (the stage that runs one child, from
[Workflows](../concepts/workflows.md)) whose child is an [`Errand`](../concepts/errands.md)
making one tool call. An errand ends in one of four final states: `done` (the call
succeeded), `failed` (it ran and failed), `refused` (the policy forbade it) or `declined` (a
person declined it). The host's `routes` map each of them to an input of the workflow's
machine.

The three tools are `StubTool`s, test fakes that return a fixed result, or raise the
exception given as `result`; `calls()` lists the arguments each received. The courier is
down today, so `ship_order` raises. Each tool is built once and that object is passed
wherever the tool is meant: to the errand's `FixedCall` (a call id, the tool and its
arguments), to the plan and to the runtime's toolbox ([Tools](../concepts/tools.md)):

```python
from gvn.harness.errand import Errand
from gvn.harness.events import Event
from gvn.harness.tools import FixedCall, Tool
from gvn.harness.workflow import Host
from gvn.kernel.schema import Record, Text
from gvn.testing.fakes import StubTool

by_order = Record({"order_id": Text()})
charge = StubTool(name="charge_card", arguments=by_order, result={"charged": 40.0})
ship = StubTool(name="ship_order", arguments=by_order, result=RuntimeError("courier down"))
refund = StubTool(name="refund_card", arguments=by_order, result={"refunded": 40.0})


def one_call(tool: Tool, done: str, failed: str, not_run: str) -> Host:
    return Host(
        actor_class=Errand,
        make=lambda name, memo: Errand(
            name=name,
            calls=[
                FixedCall(
                    call_id=tool.name(),
                    tool=tool,
                    arguments={"order_id": memo.input()["order_id"]},
                )
            ],
        ),
        start=lambda memo: Event("started"),
        routes={"done": done, "failed": failed, "refused": not_run, "declined": not_run},
    )


STAGES = {
    "charging": one_call(
        tool=charge, done="charged", failed="charge_failed", not_run="not_charged"
    ),
    "shipping": one_call(
        tool=ship, done="shipped", failed="not_shipped", not_run="not_shipped"
    ),
    "refunding": one_call(
        tool=refund, done="refunded", failed="refund_failed", not_run="refund_failed"
    ),
}
```

## Step 3: declare the compensation

`Compensate` says which stage undoes which. The `Plan` joins the machine to its stages, as in
[Workflows](../concepts/workflows.md), and takes two more arguments here: `compensations`, the
list of `Compensate` pairs, and `undone`, the final states that mean "this run was undone".
`tools` declares the tools the errands call, so the runtime can check its toolbox before the
run starts ([Tools](../concepts/tools.md#what-a-workflow-declares)):

```python
from gvn.harness.workflow import Compensate, Plan

REFUND = Compensate(
    stage="charging",
    by="refunding",
    done=["refunded"],
    untouched=["not_charged"],
)

ORDER = Plan(
    definition=order_machine(when_not_shipped="refunding"),
    stages=STAGES,
    compensations=[REFUND],
    undone=["cancelled"],
    tools=[charge, ship, refund],
)
print(ORDER.compensations(), sorted(state.name() for state in ORDER.undone()))
```

```text
(Compensate('charging', by='refunding', done=['refunded'], untouched=['not_charged']),) ['cancelled']
```

- `stage` and `by`: the stage with effects, and the stage that undoes them.
- `done`: the symbols `by` ends with when it has undone them. `refund_failed` is not one.
- `untouched`: the symbols `stage` ends with only when it changed nothing. Here, only
  `not_charged`: a call that never ran.

The plan was built, so the verifier found every way to `cancelled` sound: each one either
left `charging` on `not_charged`, or later left `refunding` on `refunded`.

## Step 4: the plan that forgets the refund

Now the change someone makes months later: "a parcel that cannot be shipped just cancels the
order". One argument differs. A plan the checks refuse raises `PlanRejected`, whose `problems()`
lists every finding:

```python
from gvn.harness.workflow import PlanRejected

try:
    Plan(
        definition=order_machine(when_not_shipped="cancelled"),
        stages=STAGES,
        compensations=[REFUND],
        undone=["cancelled"],
        tools=[charge, ship, refund],
    )
except PlanRejected as rejected:
    for problem in rejected.problems():
        print(problem)
```

```text
compensation: uncompensated-path charging/cancelled: 'charging' is not compensated on this way to the undone final state 'cancelled': idle --started--> charging --charged--> shipping --not_shipped--> cancelled. After 'charging', the way must leave 'refunding' on 'refunded'.
```

The plan is refused before any run starts, and the message shows the way that skips the
refund, step by step. Route `not_shipped` back to `refunding` and it builds.

## Step 5: run it

The courier is down, so shipping fails and the refund runs. The run is wired as in
the tutorials: a `Workflow` class that returns the plan, a policy that clears every call, and
a toolbox of the three tools from Step 2:

```python
import asyncio

from gvn.harness.tools import VERDICTS, Toolbox
from gvn.harness.workflow import Plan, Workflow
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput


class Order(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return ORDER


class AllowEverything(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return Symbol("cleared")


toolbox = Toolbox(tools=[charge, ship, refund])
governor = Governor(
    fulfillers={
        "consult_policy": PolicyFulfiller(decision=AllowEverything()),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
    },
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
started = Event("started", payload={"order_id": "A-17"})
result = asyncio.run(governor.deliver(actor=Order(name="order-5"), event=started))
print(result.outcome().state())
print([len(tool.calls()) for tool in (charge, ship, refund)])
```

```text
State('cancelled')
[1, 1, 1]
```

Nothing new happens at run time: the compensation is an ordinary stage, and the machine routes
through it because the verifier made sure it does. What the declaration bought is the proof,
before the run, that no way to `cancelled` forgets it.

## Several effects: undo the latest first

With more than one stage with effects (reserve stock, then charge the card), declare one
`Compensate` for each, and give each its own compensating stage. The verifier then also
checks the order: the compensation of the latest effect must finish before the one of an
earlier effect. A machine that releases the stock reservation before refunding the later
charge is refused (`unordered-compensation`). The verifier also refuses a path that enters
an earlier effect stage again while a later one is still outstanding.

The [data backfill](../domains/data.md) declares two pairs this way: staging is undone by
discarding, swapping by restoring, and the verifier proves restoring always comes first.

## What the verifier proves and what you declare

The verifier reasons about the machine's **walks**: every sequence of transitions from the
initial state. Every real run is one of them, so what holds for all walks holds for every run.
For each walk into an undone final state it proves:

- every compensated stage entered on the way was later left through its `by` stage on a
  `done` symbol, unless that entry ended on an `untouched` symbol (an `untouched` exit never
  cancels an earlier entry of the same stage that is still outstanding);
- the compensations happened latest first.

The declarations are yours, and the proof rests on them:

- declare a `Compensate` for every stage that has effects; the verifier checks the stages you
  name;
- the compensating stage must really undo the effect, and an `untouched` exit must really
  mean nothing changed; the verifier takes both declarations as it takes your routes;
- a run that ends in another final state (`needs_person` here) is outside the proof, so give
  every compensating stage's failure a declared way out;
- the proof is about the machine's shape, not about data: which orders, which amounts,
  whether each refund matched its charge. A check over recorded runs (see
  [Replay and evaluation](replay-and-evaluation.md)) covers that; the data harness has one,
  `Compensated`.

The verifier can refuse a plan whose bad walk no run could take, because a
[judge](../reference/glossary.md#judge) (the [Decision](../concepts/decisions.md) that picks
a stage's answer) never gives that answer at that point. Reroute the walk or make the
machine say what the judge does. A stage's `deadline` (a time limit) ends it with its
`expired` symbol, which can be neither `done` nor `untouched`: work cut at a deadline may
have done anything, and has undone nothing.

## Recap

- `Compensate(stage=..., by=..., done=[...], untouched=[...])` pairs a stage with effects with
  the stage that undoes them; `undone=[...]` names the final states that mean "undone".
- The plan is refused, with the offending walk, unless every way to an undone final state
  passes through the compensations, latest first.
- Compensating stages are ordinary stages; their own failure needs a declared way out that is
  not an undone final state.

**Next:** to run workflows like this one from several processes and finish them after a
crash, read [Running as a service](running-as-a-service.md); for every rule of the check,
read [Workflows in depth](../concepts/workflows-in-depth.md#compensation-the-verifier-checks).
