Skip to content

Roll back a plan

Scenario. An agent onboards a supplier in two steps: create the vendor, then place the first order. The ERP refuses the order. Without care, you are left with a vendor nobody wanted.

A plan treats the steps as one unit. If a step fails, Sefra runs the compensation of each completed step, in reverse order.

Start from a clean sandbox, in its directory:

./sandbox destroy
./sandbox up
AGENT=$(./sandbox token agent)
./sandbox erp fail '{"operation": "POST /purchase-orders", "mode": "error", "status": 422, "times": 1}'

The second step takes the new vendor’s id from the first with $ref. The value is filled in just before the step runs.

RESPONSE=$(curl -sS -X POST http://127.0.0.1:18180/v1/executions \
  -H "Authorization: Bearer $AGENT" -H "Content-Type: application/json" \
  -H "Idempotency-Key: rollback-example-0001" \
  -d '{"steps": [
        {"id": "vendor", "intent": "procurement.create_vendor",
         "input": {"legal_name": "Northwind Supplies GmbH", "country": "DE", "tax_id": "DE900000001"}},
        {"id": "order", "intent": "procurement.create_purchase_order",
         "input": {"vendor_id": {"$ref": "steps.vendor.output.vendor_id"}, "sku": "LAPTOP-14",
                   "quantity": 3, "unit_price_minor": 120000, "currency": "EUR", "department": "it-ops"}}],
       "rationale": "Onboard a new supplier"}')
echo "$RESPONSE" | jq '{status, required: .approval.required}'
EXECUTION=$(echo "$RESPONSE" | jq -r .execution_id)
APPROVAL=$(echo "$RESPONSE" | jq -r .approval.approval_id)

The starter policy holds every new vendor for a finance approver. One approval covers the whole plan, so the approver sees both steps together.

SEFRA_OPERATOR_TOKEN=$(./sandbox token approver) ./sandbox sefra approvals approve "$APPROVAL" --comment "Supplier checked"
./sandbox wait "$EXECUTION" | jq '{status, steps: [.steps[] | {id, status}], code: .error.code}'
{
  "status": "rolled_back",
  "steps": [
    { "id": "vendor", "status": "compensated" },
    { "id": "order", "status": "failed" }
  ],
  "code": "DOWNSTREAM_REJECTED"
}

The vendor still exists, because ERPs rarely allow deleting one. Its compensation deactivated it, so nothing can be ordered from it:

./sandbox erp state | jq '.vendors | map(select(.legal_name == "Northwind Supplies GmbH") | {legal_name, status})'
  • Undo means the business meaning, not the bytes. Cancelling an order or deactivating a vendor is often the right reversal.
  • Treat “already undone” as success. List those responses in already_undone, so a retried compensation does not fail.
  • Put anything irreversible last. A payment cannot be undone, so Sefra allows at most one irreversible step per plan, and only as the final step.

If a compensation itself keeps failing, Sefra stops and alerts an operator, as the next example shows.