# Webhooks

Futex delivers every decision state change to your endpoint. This page is the
delivery contract: **what we send, what your status code means to us, how long we
keep trying, and what happens when we stop.**

If you only read one section, read
[Which status codes we retry](#which-status-codes-we-retry). Returning the wrong
one is the difference between a retried delivery and a permanently lost approval
outcome, and the two look identical from your side at the moment you answer.

## What we send

One `POST` per event per subscribed endpoint.

| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `X-HITL-Event-Id` | `evt_<hex>` — stable across retries of the same event |
| `X-HITL-Event-Type` | e.g. `decision.terminal`, `task.assigned` |
| `X-HITL-Timestamp` | unix seconds, as a string |
| `X-HITL-Signature` | `sha256=<hex>` (see below), or `none` if the subscription has no secret |
| `X-HITL-Attempt` | which try this is, starting at `1`. It is not part of the signed material. |
| `User-Agent` | `RodmenaHITL/1.0` |

Body:

```json
{
  "event_id": "evt_0f3c…",
  "event_type": "decision.terminal",
  "tenant_id": "ten_…",
  "resource": {"type": "decision", "id": "dec_…"},
  "data": {}
}
```

**Signature.** HMAC-SHA256 over `timestamp + "." + raw_body`, keyed with your
subscription secret, hex-encoded, prefixed `sha256=`. Verify against the **raw
bytes** you received, not a re-serialised copy of the parsed JSON — key order and
separators will not survive a round trip. We serialise compactly
(`separators=(",", ":")`, no spaces).

**Every attempt is signed afresh.** A retry is not a replay of the original
bytes: `X-HITL-Timestamp` is taken from the clock at send time and the signature
is recomputed over it, so attempt 5 at +36 minutes carries a timestamp from +36
minutes. A freshness window on your side therefore works normally, and a
**replay cache keyed on the signature will not reject our retries.**

**Delivery is at-least-once.** Delivery rows are written in the same database
transaction as the state change that produced them, so an event cannot be lost,
and cannot fire for a change that rolled back. The flip side is that you can see
the same `X-HITL-Event-Id` more than once — **deduplicate on it.**

> **A signature cache is not deduplication.** Those two paragraphs interact in a
> way that has surprised an integrator. Because we re-sign, our legitimate
> retries carry *new* signatures and pass straight through a replay cache — which
> is exactly why the cache is safe for us, and exactly why it gives you no
> protection against processing the same approval twice. They are different jobs:
>
> | Guard | Stops |
> |---|---|
> | signature cache | an intercepted request being replayed at you |
> | `X-HITL-Event-Id` dedupe | the same event being **processed** twice |
>
> Keep the event id longer than any freshness window — a requeued delivery can
> arrive days after the original.

## Which status codes we retry

We classify your response and either retry on the ladder or dead-letter it
immediately. There is no middle state.

| Your response | We | Notes |
|---|---|---|
| `2xx` | **Delivered.** Done. | Any 2xx. We do not read the body. |
| `401`, `403` | **Retry** | Usually a signature check failing during a secret rotation or a verifier deploy, which clears within the ladder. |
| `408`, `429` | **Retry** | |
| `5xx` (all) | **Retry** | |
| connection refused, timeout, TLS failure, no answer | **Retry** | No HTTP status at all is transient by definition. |
| **any other `4xx`** | **Dead-letter immediately, no second attempt** | `400`, `404`, **`409`**, `410`, `422`, **`425`** … |

The rule in one line:

```python
permanent = 400 <= status < 500 and status not in (401, 403, 408, 429)
```

### 401 and 403 are retried (changed by FTX-143)

Until FTX-143 we dead-lettered `401` and `403` on the first attempt. A `401` at a
webhook receiver almost always describes the receiver's credential state: a
secret was rotated, or a new verifier build went out before the secret did. Both
usually clear within minutes, well inside our 7h 36m ladder, so we now retry
them. Many verifiers answer a bad signature with `403` rather than `401`, so
`403` gets the same treatment. mail-api classifies these two codes the same way.

An endpoint that keeps refusing still dead-letters after the last attempt, and
while it is retrying it shows in `GET /v1/webhooks` as `retrying_now` (deliveries
on the ladder after at least one failed attempt) and `oldest_retrying_at`.

If you built a reconciliation path because a `401` used to be final, that path
can now process an event twice: once by your reconciliation, and again when our
retry succeeds. Deduplicating on `X-HITL-Event-Id` does not catch this, because
the delivery that met the `401` never reached your handler and you have no record
of its event id.

### Two traps worth spelling out

**`409 Conflict` is not retried.** This is the one that has already cost a
partner platform a production incident. If your handler receives an event about a
resource whose row you have not finished writing yet, `409` feels like the
natural "I'm not ready, come back" — and we will dead-letter it on the first
attempt. Nothing comes back.

**`425 Too Early` is not retried either.** It is semantically *exactly* "you sent
this too early, try later", and it still falls in the permanent branch, because
the rule is structural (`4xx` minus `401`/`403`/`408`/`429`) rather than per-code.

If you need us to come back, return **`503`** (or `429`). If you cannot, see
[Reconciling instead of retrying](#reconciling-instead-of-retrying) — for many
races it is the better answer anyway.

## How long we keep trying

For a retryable outcome: **8 attempts**, exponential backoff, then dead-letter.

| Attempt | Fires at (approx., cumulative) |
|---|---|
| 1 | immediately |
| 2 | +10s |
| 3 | +70s |
| 4 | +6m 10s |
| 5 | +36m 10s |
| 6 | +1h 36m |
| 7 | +3h 36m |
| 8 | +7h 36m 10s — **last attempt** |
| — | dead-lettered immediately after attempt 8 fails |

So the delivery window is **≈7h 36m**, and an endpoint that is down for eight
hours loses the event.

Ladder in seconds: `[10, 60, 300, 1800, 3600, 7200, 14400, 28800]`, attempt count
`WEBHOOK_MAX_ATTEMPTS` (default and current production value: `8`). The drainer
ticks every 5s, so each attempt lands within ~5s of its scheduled time.

> **The ladder is longer than the window.** With 8 attempts, only the first
> **seven** gaps are ever used — the 8th attempt is the last, so the final entry
> (`28800`, 8h) is never applied. Summing the whole ladder gives 15h 36m, which is
> *not* the delivery window and never was; the real figure is 7h 36m. If you raise
> `WEBHOOK_MAX_ATTEMPTS` to 9 the last entry starts being used and the window
> becomes 15h 36m.

## Event types

These are the event types we emit. Registering any other name is refused with `422`, and the
error lists the valid names (FTX-145). Subscriptions stored before that check keep whatever names
they were saved with; a name that is not on this list never matches anything.

| Event | Fires when |
|---|---|
| `decision.created` | a decision is raised |
| `decision.terminal` | a decision reaches ANY terminal state — carries the full outcome envelope |
| `decision.escalated` | an SLA escalation reassigned or escalated the decision |
| `decision.clearance_required` | a reviewer triggered a further-clearance profile |
| `decision.gate_revived` | a RunFlow gate was revived |
| `decision.workflow_withdrawn` | the bound RunFlow workflow withdrew |
| `decision.binding_credential_rejected` | a RunFlow binding credential was refused |
| `decision.binding_unobservable` | a RunFlow binding could not be observed |
| `task.assigned` | a task was assigned to a reviewer |
| `task.completed` | a reviewer completed a task |
| `policy.created` · `tenant.created` | control-plane creations |
| `policy.updated` | a tenant admin replaced a policy's definition in place (`data.version` is the new version) |
| `policy.retired` | a policy was retired and accepts no new decisions |
| `member.added` · `member.role_changed` | a tenant member was added, or their role changed |
| `delegation.created` · `delegation.accepted` · `delegation.revoked` | delegation lifecycle |

**There is no `decision.approved`, `decision.rejected`, `decision.cancelled` or
`decision.timed_out` event.** Every terminal outcome arrives as a single `decision.terminal`,
and the result is `outcome.result` inside the envelope — `approved`, `rejected`,
`changes_requested`, `timed_out` or `cancelled`. Filter on the event, branch on the field.

Those names *do* exist as **audit** actions (`GET /v1/audit`), which is a trap worth naming: a
list built by grepping our source for `decision.*` strings includes several that are never
dispatched as webhooks.

**`events: []` (or omitted) means EVERY event type**, not none. If you want everything, that is
the correct and intended value.

## When we stop

A delivery that is dead-lettered — whether by a permanent status or by exhausting
the ladder — is **not silently dropped**:

- the row moves to `state = "dead"` and `dead_at` is stamped;
- an audit event `webhook.dead_lettered` records the attempt count and last error;
- `GET /v1/webhooks` reports per-endpoint `dead_total` and `last_dead_at`, and
  `retrying_now` and `oldest_retrying_at` for deliveries still on the ladder;
- `GET /v1/webhooks/deliveries` lists the rows, including dead ones;
- `POST /v1/webhooks/deliveries/{id}/requeue` moves a dead row back to pending and
  we try again from the top.

**Requeue only works on dead rows.** It is `WHERE state = 'dead'`, and returns
`409` otherwise. This has a consequence worth understanding: if you answer `2xx`
to an event you could not actually process, we mark it **delivered**, stop
tracking it as a problem, and it can never be requeued. Answering `200` to
something you dropped is not a soft failure — it closes our recovery path.

## When an endpoint keeps failing

After `WEBHOOK_DISABLE_AFTER_DEAD` dead deliveries (default 10) since an endpoint's last
success, Futex disables the subscription. `GET /v1/webhooks` then shows `active: false`
with `disabled_at` and `disabled_reason`, which tells an auto-disable apart from a
colleague switching it off. New events are not queued for a disabled subscription.

Once the endpoint is fixed, `POST /v1/webhooks/{id}/enable` (permission
`hitl:webhook:manage`) turns it back on. Enabling does not replay the backlog. Requeue
the dead rows you want one at a time with `POST /v1/webhooks/deliveries/{id}/requeue`,
or read the outcomes with `GET /v1/decisions/{id}`.

## Reconciling instead of retrying

If your failure is a race — the event arrived before your own write landed — a
retry only helps if the race has resolved by the time we come back, and you are
relying on our backoff ladder to paper over your write ordering.

The alternative is to pull. `GET /v1/decisions/{id}` (permission
`hitl:decision:read`) returns the full outcome envelope once the decision is
terminal: status, who acted, reason codes and text, justifications, `acting_as`
for delegated approvals, and `terminal_at`. It is the same information the webhook
carries.

So a handler that finds no local row can log it and read the outcome back later,
once it knows the decision id — no retry, no dependence on our ladder, and no
status-code negotiation between us.

## Registering an endpoint

```http
POST /v1/webhooks          permission: hitl:webhook:manage
{"url": "https://…", "secret": "…", "events": ["decision.terminal"]}
```

`events: []` (or omitted) means **all** events. The URL is SSRF-checked at
registration and again at every send, against the resolved IP, with the
connection pinned to the address that was validated — so a DNS rebind between
check and connect cannot redirect a delivery. Private and link-local targets are
rejected unless the host is on the `WEBHOOK_ALLOW_HOSTS` platform allowlist.

Subscriptions belong to a tenant. A platform that gives each of its customers a Futex
tenant registers one subscription per tenant, with that tenant's key.

### Rotating a secret

There is no rotate route. Register a second subscription to the same URL with the new
secret, deploy a verifier that accepts either secret, then `DELETE /v1/webhooks/{old_id}`.
During the overlap each event arrives once per subscription. Both copies carry the same
`X-HITL-Event-Id`, and your event-id dedupe drops the second.

### Endpoints on a development machine

A laptop or a `.local` name is not reachable, and private addresses are refused. Expose
the port on a public HTTPS URL (for example `retunnel http <port>`, which gives a
`https://<name>.retunnel.net` address), register that URL, and delete the subscription
when the tunnel goes away.

## Note for readers of this repository

The live delivery path is `app/integrations/webhook_sender.py` (one POST, no
internal loop) driven by `app/workers/webhook_drain.py` (durable scheduling via
`next_attempt_at`), fed by `app/domain/outbox.py`.

`app/webhook.py::WebhookClient` is **not** the live path. It is retained for its
tests only, it retries in-process with its own loop, and its payload carries an
`occurred_at` field the live path does not send. Do not read it as the contract.

The classification above is asserted against a real HTTP server in
`tests/test_webhook_status_classification.py`, in both directions, rather than
against a hand-built result object — see `SPECS/FTX-131-webhook-status-classification.md`
for why that distinction is the whole point.
