# Errors & Recovery

> OpenGen returns structured JSON error envelopes with Cache-Control no-store on every non-2xx response, exposes RateLimit, RateLimit-Policy, and Retry-After headers for backpressure, and attaches typed structuredError objects to jobs. On network timeouts or submission-unknown states, recover read-only via GET /v1/generations/lookup or MCP job_get without blind paid retries.

## Agent Prompt

```text
Handle OpenGen API errors and timeouts safely using https://opengen.dev/docs/errors:
1. Never invent a new Idempotency-Key after a timeout, 5xx, or dropped connection on POST https://opengen.dev/v1/generations — call read-only GET https://opengen.dev/v1/generations/lookup?idempotencyKey=... or MCP job_get({ idempotencyKey }) first.
2. Never treat a 404 lookup on an in-flight request as proof of rejection, and NEVER submit a replacement job when status is submission-unknown or structuredError.recovery is "operator".
3. Inspect RateLimit, RateLimit-Policy, and Retry-After headers on 429 responses before backing off; only retry read/status polls automatically, or replay POST with the exact persisted Idempotency-Key and byte-identical payload.
4. On 400 invalid_generation, read error.issues[] and inspect GET https://opengen.dev/v1/models/{provider}/{model} (or get_model) to correct unsupported arguments before asking the user to re-confirm budget.
```

## Standard error envelopes

Every HTTP error response is served with `Cache-Control: no-store` and returns a consistent JSON object. Schema validation failures on canonical generation requests (`400 invalid_generation`) also attach an `issues[]` array pinpointing each offending field:

```json
{
  "error": {
    "code": "invalid_generation",
    "message": "input.duration: Duration is outside this model capability.",
    "issues": [
      {
        "code": "unsupported_duration",
        "field": "input.duration",
        "message": "Duration is outside this model capability.",
        "limit": "4–12",
        "received": 30
      }
    ]
  }
}
```

Over Streamable HTTP MCP (`/mcp` and `/mcp/readonly`), tool failures set `isError: true` and carry the same `{ "error": { "code", "message" } }` object in `structuredContent` and text content.

## HTTP status codes and API error codes

| Status | Verified `error.code` Values                                                                                                                                                                                                                                               | Cause & Recommended Action                                                                                                                                                                                |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | `invalid_generation`, `invalid_input`, `idempotency_key_required`, `idempotency_required`, `invalid_prefer_header`, `invalid_status_wait`, `invalid_upload`, `invalid_asset_query`, `invalid_activity_query`, `invalid_input_url`, `invalid_input_media`, `invalid_base64` | Request failed schema, header, or container validation. Inspect `error.issues[]` or `GET /v1/models/{provider}/{model}` and fix the request before retrying                                               |
| `401`  | `unauthorized`                                                                                                                                                                                                                                                             | Missing, expired, malformed, or revoked Bearer token, session cookie, or audience-mismatched OAuth token. Refresh OAuth token or rotate API key                                                           |
| `402`  | `insufficient_balance`, `budget_exceeded`                                                                                                                                                                                                                                  | Workspace `availableMicros` is below the required reservation, or the route estimate exceeds `maxCostMicros`. Top up at `/billing` or adjust `maxCostMicros` with explicit user approval                  |
| `403`  | `insufficient_scope`, `policy_denied`, `origin_denied`                                                                                                                                                                                                                     | Token lacks `read`/`generate` scope, request violates a governance routing policy or spend cap, or a cookie-bearing request failed CSRF `Origin` validation                                               |
| `404`  | `not_found`, `collection_not_found`, `generation_schema_not_found`, `asset_not_found`, `workspace_not_found`                                                                                                                                                               | Owned job, asset, model, or collection does not exist in this workspace. Note: `404` on `/v1/generations/lookup` is **not** proof that a still-in-flight submission failed                                |
| `405`  | `method_not_allowed`                                                                                                                                                                                                                                                       | Unsupported HTTP verb (for example `GET /mcp` returns `405` with `Allow: POST, OPTIONS`)                                                                                                                  |
| `406`  | `Not Acceptable` (JSON-RPC `-32000`)                                                                                                                                                                                                                                       | MCP caller sent an `Accept` header explicitly rejecting `application/json` (such as `application/json;q=0, text/event-stream`)                                                                            |
| `408`  | `input_download_timeout`                                                                                                                                                                                                                                                   | Public HTTPS URL import exceeded the 30-second fetch deadline                                                                                                                                             |
| `409`  | `idempotency_conflict`, `billing_hold`, `asset_not_ready`, `asset_write_in_progress`, `job_not_terminal`, `output_purge_pending_settlement`, `output_delivery_in_progress`, `workspace_changed`                                                                            | State conflict: reusing an `Idempotency-Key` with a modified body (including `webhookUrl`/`webhookEvents`), active billing hold, unready asset, or attempting to purge outputs before terminal settlement |
| `410`  | _(expired `/media` capability)_                                                                                                                                                                                                                                            | Signed first-party `/media/v1....` output link expired or job outputs were purged. Call `GET /v1/generations/{id}` (or MCP `job_get`) to mint a fresh link while retained                                 |
| `413`  | `upload_too_large`                                                                                                                                                                                                                                                         | Direct upload exceeded `4 MiB` (`multipart/form-data`), `3 MiB` (REST JSON `base64`), or `64 KiB` (MCP `upload_asset` `base64`). Switch to presigned single-PUT (`<= 100 MiB`)                            |
| `415`  | `invalid_upload`                                                                                                                                                                                                                                                           | Missing `multipart/form-data` boundary or unsupported `Content-Type`                                                                                                                                      |
| `422`  | `no_executable_route`, `invalid_generation_input`, `unsupported_operation`, `execution_scope_denied`                                                                                                                                                                       | Valid canonical request, but no candidate route matches your `routing` constraints, BYOK credentials, or server execution scope. Inspect `POST /v1/pricing/estimate` `candidates[].reason`                |
| `429`  | `rate_limited`, `slow_down`                                                                                                                                                                                                                                                | Rate limit or dispatch backpressure exceeded. Honor `Retry-After` and `RateLimit` / `RateLimit-Policy` headers before retrying reads or idempotent lookups                                                |
| `503`  | `database_not_configured`, `storage_not_configured`, `authentication_not_configured`, `vault_not_configured`, `webhook_signing_not_configured`                                                                                                                             | Optional installation subsystem is unconfigured on a self-hosted gateway                                                                                                                                  |

## Job `structuredError` taxonomy

When an admitted generation encounters an execution, policy, or delivery issue, `GET /v1/generations/{id}` and `GET /v1/generations/{id}/status` populate `structuredError` (`{ code, category, message, retryable, recovery, field?, providerCode? }`).

> [!IMPORTANT]
> `structuredError.retryable: true` means it is safe to **retry reading or resuming the same existing job** (`recovery: "same_job"`). It is **never** an authorization to submit a second paid generation!

| `structuredError.code`          | Category        | `retryable` | `recovery`     | Meaning                                                                              |
| ------------------------------- | --------------- | ----------- | -------------- | ------------------------------------------------------------------------------------ |
| `invalid_input`                 | `invalid_input` | `false`     | `edit_request` | Request contained an invalid or unsupported parameter                                |
| `provider_invalid_input`        | `invalid_input` | `false`     | `edit_request` | Upstream provider rejected an input parameter                                        |
| `policy_rejected`               | `policy`        | `false`     | `edit_request` | Rejected by applicable governance or safety policy                                   |
| `provider_policy_rejected`      | `policy`        | `false`     | `edit_request` | Upstream provider rejected the request under its content policy                      |
| `submission_rejected`           | `unknown`       | `false`     | `edit_request` | Upstream provider explicitly rejected submission before execution                    |
| `submission_unknown`            | `unknown`       | `false`     | `operator`     | Upstream acceptance could not be confirmed; hold stays active pending reconciliation |
| `provider_outcome_unknown`      | `unknown`       | `false`     | `operator`     | Upstream execution outcome is unresolved; keep job for reconciliation                |
| `provider_failed`               | `technical`     | `false`     | `operator`     | Upstream execution failed; settlement may require reconciliation                     |
| `status_unavailable`            | `technical`     | `true`      | `same_job`     | Upstream status check temporarily unavailable; keep polling the same job             |
| `capacity_full`                 | `technical`     | `true`      | `same_job`     | Dispatch pool at capacity; existing queued job waits for a slot                      |
| `input_preparation_unavailable` | `technical`     | `true`      | `same_job`     | Accepted input package not yet ready for dispatch; keep existing job                 |
| `delivery_unavailable`          | `technical`     | `true`      | `same_job`     | Output capture temporarily unavailable; resume reading the same job                  |
| `delivery_failed`               | `technical`     | `false`     | `operator`     | Private output delivery failed; inspect with operator support, do not resubmit       |
| `delivery_expired`              | `technical`     | `false`     | `operator`     | Upstream output expired before capture; inspect with operator support                |
| `credentials_unavailable`       | `technical`     | `false`     | `operator`     | Original provider connection changed or unavailable for this job                     |
| `start_deadline_exceeded`       | `technical`     | `false`     | `none`         | Local `queueStartDeadlineAt` passed before upstream submission                       |

## Rate limiting & backpressure headers

REST responses under `/v1/*` emit standard IETF draft **`RateLimit`** and **`RateLimit-Policy`** headers so automated clients and agents can self-throttle before hitting `429`:

- `RateLimit-Policy`: declares the active quota policy and window duration in seconds (for example `"public-read";q=300;w=60` on public catalog reads, `"public-estimate";q=120;w=60` on `POST /v1/pricing/estimate`, `"v1-read";q=120;w=60` on authenticated workspace reads, and `"v1-write";q=60;w=60` on authenticated mutations).
- `RateLimit`: reports the active policy's remaining quota and reset countdown in seconds (for example `"public-read";r=299;t=60` or `"v1-write";r=59;t=60`).
- `Retry-After`: included on `429` responses with an integer delay in seconds (for example `Retry-After: 3600` on OAuth `slow_down`, or bounded seconds on API rate limits).

When you receive `429`, wait at least `Retry-After` seconds (adding small jitter) before retrying read/poll calls. Never loop tightly against `GET /v1/generations/{id}` — prefer `GET /v1/generations/{id}/events` (SSE), `GET /v1/generations/{id}/status?waitMs=25000`, or [webhooks](/docs/webhooks).

## Safe recovery playbook (timeouts & `submission-unknown`)

Follow these strict rules whenever a network error or timeout interrupts a generation:

1. **Persist before submitting**: Store your generated `Idempotency-Key` and exact canonical JSON body before calling `POST /v1/generations`.
2. **Recover read-only first**: If the client disconnects before receiving the `202`/`200` response, call `GET /v1/generations/lookup?idempotencyKey=<key>` (or MCP `job_get({ idempotencyKey })` / `opengen job recover --idempotency-key <key>`).
3. **Never mint a replacement key blindly**: If `lookup` finds the job, persist its `id` and resume polling. If the job is in `status: "submission-unknown"`, reserved funds remain held until reconciliation confirms whether the provider accepted the task — **do not** submit a second job.
4. **Never mutate a replayed payload**: Re-sending the same `Idempotency-Key` with a different prompt, model, routing, `maxCostMicros`, `webhookUrl`, or `webhookEvents` fails with `409 idempotency_conflict`.

```bash tab="cURL"
# Read-only lost-submit recovery using the exact persisted Idempotency-Key
curl --fail-with-body \
  "$OPENGEN_API_URL/v1/generations/lookup?idempotencyKey=$(printf '%s' "$OPENGEN_IDEMPOTENCY_KEY" | jq -sRr @uri)" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"
```

```ts tab="TypeScript"
const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` };

async function lookupWithBackoff(idempotencyKey: string, attempts = 3) {
  for (let i = 0; i < attempts; i += 1) {
    const res = await fetch(
      `${baseUrl}/v1/generations/lookup?idempotencyKey=${encodeURIComponent(idempotencyKey)}`,
      { headers },
    );
    if (res.status === 429) {
      const retryAfter = Number(res.headers.get('Retry-After') ?? '2');
      await new Promise((r) => setTimeout(r, Math.max(1, retryAfter) * 1000));
      continue;
    }
    if (res.ok) return await res.json();
    if (res.status === 404) return null; // Not proof rejection occurred if POST is still in flight
    throw new Error(`Lookup failed with HTTP ${res.status}`);
  }
  throw new Error('Rate limited while recovering job; retry lookup later without resubmitting.');
}
```

```python tab="Python"
import os
import time
import httpx

base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}


def lookup_with_backoff(idempotency_key: str, attempts: int = 3):
    with httpx.Client(base_url=base_url, headers=headers, timeout=20.0) as client:
        for _ in range(attempts):
            res = client.get("/v1/generations/lookup", params={"idempotencyKey": idempotency_key})
            if res.status_code == 429:
                delay = max(1, int(res.headers.get("Retry-After", "2")))
                time.sleep(delay)
                continue
            if res.status_code == 200:
                return res.json()
            if res.status_code == 404:
                return None  # Do not assume rejection if the original POST may still be in flight
            res.raise_for_status()
    raise RuntimeError("Rate limited during recovery; do not mint a new idempotency key.")
```

```json tab="MCP"
{
  "tool": "job_get",
  "arguments": {
    "idempotencyKey": "quickstart-2026-12-02-compass-01"
  }
}
```

```bash tab="CLI"
opengen job recover --idempotency-key "$OPENGEN_IDEMPOTENCY_KEY"
```
