Skip to content

Safe retries

Scenario. An agent places an order, and the network drops before the response arrives. The agent does not know whether the order exists. What should it do?

It retries with the same idempotency key. Sefra returns the first result and does not act twice.

Start from a clean sandbox, in its directory:

./sandbox destroy
./sandbox up
AGENT=$(./sandbox token agent)
BODY='{"intent": "procurement.create_purchase_order",
       "input": {"vendor_id": "v_1001", "sku": "MOUSE", "quantity": 3,
                 "unit_price_minor": 2500, "currency": "EUR", "department": "it-ops"}}'
send() {
  curl -sS -o /tmp/sefra-result.json -w '%{http_code} ' -X POST http://127.0.0.1:18180/v1/executions \
    -H "Authorization: Bearer $AGENT" -H "Content-Type: application/json" \
    -H "Idempotency-Key: $KEY" -d "$BODY"
  jq -c '{status: (.envelope.status // .status), replayed, code}' /tmp/sefra-result.json
}
KEY=retry-example-key-0001
send
send
./sandbox erp state | jq '[.purchase_orders[] | select(.sku == "MOUSE")] | length'

The second answer is 200 with "replayed": true, and the ERP holds one order.

A key belongs to one action. Using it with different input is a bug in the caller, so Sefra refuses:

BODY=$(echo "$BODY" | sed 's/"quantity": 3/"quantity": 4/')
send

A new key says “this is a new action”. Here the starter policy adds a second safeguard: it refuses an identical write by the same agent within 24 hours, which catches an agent stuck in a loop.

BODY=$(echo "$BODY" | sed 's/"quantity": 4/"quantity": 3/')
KEY=retry-example-key-0002
send
jq -r '.envelope.error.violations[0].rule' /tmp/sefra-result.json
Situation Key Result
Retry after a timeout Same The original result, with no second action
Same key, different input Same Refused with IDEMPOTENCY_KEY_REUSED
A new, identical action New Refused by the duplicate rule, if your policy has one
A genuinely different action New Evaluated normally

In your agent, create the key when you decide to act, store it with the task, and reuse it for every retry of that task.