# Errors, retries and idempotency

This page lists the errors the router's public calls answer, says which ones to retry, and shows
how `Idempotency-Key` makes a submit safe to retry.

## The error envelope

Every answer that is not a 2xx has the same body:

```json
{"error": {"code": "<snake_case>", "message": "<human-readable text>", "details": {}}}
```

- `code` is stable. Branch on `code`, never on `message`.
- `message` is for people and can change at any time.
- `details` is always an object, possibly empty. Its keys depend on the code, and a code can gain
  new keys.

With eigenkit, every router failure raises `eigenorbit_router_client.RouterError` with `code`,
`message`, `details` and `http_status`. The eigenkit sample uses `circuit`, `weights` and
`inputs` from the [Quickstart](/docs/quickstart) script.

<CodeTabs syncKey="client">

```python title="eigenkit"
from eigenorbit_router_client import RouterError

try:
    values = circuit(weights, inputs)
except RouterError as error:
    if error.code == "insufficient_balance":
        print("Add funds on the Balance page.")
    else:
        raise
```

```json title="HTTP"
{
  "error": {
    "code": "insufficient_balance",
    "message": "The available balance does not cover this job's hold",
    "details": {
      "job_id": "01a0d3c5-6d70-7d32-95e6-07c356bd2bce"
    }
  }
}
```

</CodeTabs>

A `422 validation_error` lists each problem in `details.errors`, with `loc` (the path to the
problem), `msg` and `type`:

```json
{
  "error": {
    "code": "validation_error",
    "message": "Request validation failed",
    "details": {
      "errors": [
        {"loc": ["body", "method"], "msg": "Field required", "type": "missing"},
        {
          "loc": ["body", "shots"],
          "msg": "Input should be greater than or equal to 0",
          "type": "greater_than_equal"
        }
      ]
    }
  }
}
```

An error never repeats what you sent. Treat a code you do not know like `internal_error` of its
HTTP status class.

## Error codes

The codes the device and job calls can answer:

| Code | HTTP | Meaning |
|---|---|---|
| `idempotency_key_required` | 400 | `POST /v1/jobs` without an `Idempotency-Key` header. |
| `unauthenticated` | 401 | The API key is missing, malformed, unknown or revoked. One message for every cause. |
| `insufficient_balance` | 402 | Your available balance is below the job's hold. `details = {job_id}`. |
| `negative_balance` | 402 | Your balance is below zero; no new job until you top up. `details = {job_id}`. |
| `key_budget_exceeded` | 402 | The key's budget does not cover the job. `details = {budget_usd_micro, spent_usd_micro, held_usd_micro, estimate_usd_micro}`. |
| `terms_not_accepted` | 403 | You have not accepted the current router terms. `details = {required_version, accept_url, terms_url}`. |
| `user_blocked` | 403 | The EigenOrbit account is blocked. |
| `ibm_account_not_connected` | 403 | IBM devices: you have no IBM Quantum account connected. `details = {device}`. |
| `ibm_connection_invalid` | 403 | IBM devices: your IBM connection stopped working. |
| `device_access_restricted` | 403 | The device is in limited preview and is not available to your account. `details = {device}`. |
| `job_not_found` | 404 | No job with this ID belongs to you. |
| `not_found` | 404 | No such route, or no calibration snapshot for the device. |
| `method_not_allowed` | 405 | The route exists for another HTTP method. |
| `idempotency_conflict` | 409 | The `Idempotency-Key` was already used with a different body. |
| `job_not_completed` | 409 | The result was asked for before the job completed. `details = {status}`. |
| `job_not_cancellable` | 409 | The job is completed, failed or rejected. `details = {status}`. |
| `result_expired` | 410 | The result was deleted after the retention period. `details = {expired_at}`. |
| `request_too_large` | 413 | The request body is above the size limit (`details = {max_bytes}`), or the job has more gates, observables, weights or inputs than the router accepts (`details = {field, max_items}`). |
| `validation_error` | 422 | The body, a header, a path parameter or a query parameter fails the schema, or the body is not JSON. `details.errors` lists the problems. |
| `unknown_device` | 422 | The device is not in the device list. `details = {device}` (empty on the calibration call). |
| `device_unavailable` | 422 | The device is offline or retired, or its status is too old to trust. `details = {device, status}`, plus `stale: true` for an old status. |
| `method_not_supported` | 422 | The device does not run this method. `details = {method, supported}`. |
| `batch_not_supported` | 422 | 2-D `weights` or `inputs`, or more input rows than a photonic device takes (`details = {max_rows}`). |
| `circuit_invalid` | 422 | `circuit_spec` or `observables` cannot be read, or the circuit is too wide for the device or the method. For example `details = {n_qubits, max_qubits}`. Also an angle expression that nests deeper than 32 levels or can exceed 1e15 in magnitude, and a `circuit_spec` or `observables` nested deeper than 68 JSON levels or holding an integer outside the 64-bit range (`details = {reason}`, plus `max_depth` for nesting). |
| `shots_invalid` | 422 | `shots` is outside the device's or the method's range. `details = {min_shots, max_shots}`. |
| `protocol_unsupported` | 426 | `EO-Protocol-Version` is missing or not supported. `details = {client_version, supported_min, supported_max, min_client_version}`. |
| `concurrency_limit_exceeded` | 429 | You have the most jobs in flight the router allows. `details = {limit, in_flight}`. |
| `rate_limited` | 429 | Your API key or account sent too many submits or estimates in a short time. `details = {retry_after_seconds}`, and the same number is in the `Retry-After` header. |
| `region_blocked` | 451 | The router, or IBM Quantum for an IBM device, is not available in your region. |
| `internal_error` | 500 | An unexpected router error. |
| `ledger_unavailable` | 503 | The balance service could not be reached. `details = {job_id}` on a submit. |

## Job errors

A job that ends `failed` or `rejected` carries `error = {code, message, category}`, and
`GET /v1/jobs/{job_id}` still answers `200`. `category` says who or what stopped the job: branch on
it for display and on `code` for logic.

| Job error code | Category |
|---|---|
| `insufficient_balance`, `negative_balance`, `user_blocked` | `rejected`: an admission rule |
| `vendor_rejected` for a circuit the device cannot run | `circuit`: your circuit or job parameters |
| `vendor_rejected` for anything else, `vendor_failed`, `vendor_unavailable` | `vendor`: the vendor, or the router's vendor setup |
| `ibm_credentials_rejected`, `ibm_quota_exhausted`, `ibm_target_mismatch`, `ibm_device_not_on_instance` | `vendor` (see [Connect your IBM Quantum account](/docs/ibm-quantum)) |
| `internal_error`, `ledger_unavailable` | `internal`: the router or its infrastructure |

- `vendor_rejected`: the vendor refused the task when it was submitted.
- `vendor_failed`: the vendor accepted the task and then reported it failed.
- `vendor_unavailable`: the router could not reach the vendor for long enough that it gave up.

With eigenkit, `handle.result()` raises `RouterError` for a job that did not complete.

## Which errors to retry

Retry with the same `Idempotency-Key`, so a retry never creates a second job:

- `502`, `503` and `504` answers, and a dropped connection. eigenkit does this by itself.
- `503 ledger_unavailable`: retry later.

Wait, then retry:

- `429 concurrency_limit_exceeded`: wait for a job to finish, or cancel one.
- `429 rate_limited`: wait the seconds in the `Retry-After` header, then send the request again. Use
  the same `Idempotency-Key` for a submit.
- `422 device_unavailable`: pick another device, or retry later.

Fix the cause, then send a new request:

- `400 idempotency_key_required`: add the header.
- `409 idempotency_conflict`: use a new key for a new body.
- The other `422` codes: correct the request.
- `413 request_too_large`: send a smaller body or a smaller job.
- `402 insufficient_balance` and `402 negative_balance`: top up, then submit with a new
  `Idempotency-Key`. The old key answers the same rejection again.
- `402 key_budget_exceeded`: raise or remove the key's budget in the web app.
- `403 terms_not_accepted`: accept the terms at `details.accept_url`.
- `403 ibm_account_not_connected` and `403 ibm_connection_invalid`: connect or reconnect your IBM
  account.
- `426 protocol_unsupported`: upgrade the client with `pip install -U eigenorbit-router-client`.
  Over HTTP, send `EO-Protocol-Version: 1`.

Do not retry:

- `401 unauthenticated`: check the key in `EIGENORBIT_ROUTER_API_KEY`.
- `403 user_blocked`: signing in again cannot help.
- `403 device_access_restricted`: the device is in limited preview. Pick another device.
- `410 result_expired`: the result is gone.
- `451 region_blocked`.
- `409 job_not_completed`: poll the job instead, and read the result once it is `completed`.

## Idempotency-Key

`POST /v1/jobs` needs an `Idempotency-Key` header: 1 to 128 characters from `A` to `Z`, `a` to
`z`, `0` to `9`, `.`, `_`, `:` and `-`. Send a new key for each new job, for example a UUID, and
the same key on every retry of that job.

- A missing key answers `400 idempotency_key_required`; a malformed one `422 validation_error`.
- The first request with a key answers `202` with the new job.
- The same key with the same body answers `200` with the existing job and the header
  `Idempotent-Replayed: true`. The bodies are compared after parsing, so key order and whitespace
  do not matter.
- The same key with a different body answers `409 idempotency_conflict`.
- The same key after a rejection, for example `402 insufficient_balance`, answers the same
  rejection.
- Keys are yours alone: another user's key never matches.

`POST /v1/jobs/estimate` takes no key: it changes nothing.

eigenkit sends a new key for each call and reuses it on its own retries. If every attempt loses its
answer, eigenkit raises `router_unreachable` with the key in `details["idempotency_key"]`: the job
may already exist. Submit again with that key to get the same job back instead of a second,
separately billed one. The eigenkit sample uses `circuit`, `weights` and `inputs` from the
[Quickstart](/docs/quickstart) script.

<CodeTabs syncKey="client">

```python title="eigenkit"
from eigenorbit_router_client import RouterError

try:
    values = circuit(weights, inputs)
except RouterError as error:
    if error.code != "router_unreachable":
        raise
    handle = circuit.compiled.submit(
        weights, inputs, idempotency_key=error.details["idempotency_key"]
    )
    values = handle.result()
```

```bash title="HTTP"
IDEMPOTENCY_KEY=$(uuidgen)

# Send this command again, unchanged, if its answer is lost.
curl https://router.eigenorbit.com/v1/jobs \
  --request POST \
  --header 'Content-Type: application/json' \
  --header 'EO-Protocol-Version: 1' \
  --header "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --header "Authorization: Bearer $EIGENORBIT_ROUTER_API_KEY" \
  --data '{
    "device": "braket/sv1",
    "method": "run",
    "shots": 0,
    "circuit_spec": {
      "n_qubits": 1,
      "n_weights": 1,
      "n_inputs": 0,
      "gates": [{"n": "RY", "q": [0], "p": [{"t": "WeightRef", "i": 0}]}]
    },
    "observables": [{"terms": [{"coeff": 1.0, "paulis": [["Z", 0]]}]}],
    "weights": [0.5],
    "inputs": []
  }'
```

</CodeTabs>

## Reference

- [Submit a job](/docs/api/jobs#submit-a-job)
- [Estimate a job](/docs/api/jobs#estimate-a-job)
- [Get a job](/docs/api/jobs#get-a-job)
- [Get a job result](/docs/api/jobs#get-a-job-result)
- [Cancel a job](/docs/api/jobs#cancel-a-job)
- [List devices](/docs/api/devices#list-devices)
- [Get device calibration](/docs/api/devices#get-device-calibration)
