> ## Documentation Index
> Fetch the complete documentation index at: https://developers.kardinal.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> If you're integrating Kardinal into an application with an SDK, start with Integration paths: https://developers.kardinal.ai/getting-started/integration-paths.md. It lists the sections to read, in order. If you follow Integration paths, you don't need llms-full.txt or openapi.yaml. Each step links the section you need.

# Errors, retries, and warnings

> How the Kardinal SDKs turn API errors into typed exceptions, which calls they retry and when, and how to read the warnings returned on a successful call.

Both SDKs map every API error to the same exception classes, with the same names in Python and TypeScript. All of them inherit from `KardinalError` and can be imported from the package root.

## Error families

| Exception | Raised on | What to do |
| - | - | - |
| `KardinalAuthError` | `401` `NOT_AUTHENTICATED`: missing, invalid, or expired key. From 1.1.0, also the `403` of a revoked or regenerated key, with `.status` set to `403` | Check the key — see [Troubleshooting authentication](https://developers.kardinal.ai/sdks/configuration.md#troubleshooting-authentication) |
| `KardinalLimitError` | From 1.1.0, a `403` `NOT_ALLOWED` that the SDK recognizes as a limit: a plan-size limit, an optimization quota, or insufficient credits. In 1.0.x, any `403` | Read `details` — see [Quotas and rate limits](#quotas-and-rate-limits) |
| `KardinalForbiddenError` | From 1.1.0, a `403` that the SDK can't classify | Read `details` and `errors` — see [Quotas and rate limits](#quotas-and-rate-limits) |
| `KardinalValidationError` | `400`: `INVALID_INPUT`, `ID_NOT_UNIQUE`, `KEYS_NOT_UNIQUE`, `INVALID_ID_REFERENCE`, `INVALID_VALUE`, `PRECONDITION_FAILED`, `NOT_IMPLEMENTED`. From 1.1.0, also the `403` of an archived plan updated, stopped, or restarted without `force`, with no field path in `errors` | Fix the plan — see [Validation errors](#validation-errors) |
| `KardinalNotFoundError` | Any `404`, reads included | Check the plan `id`; right after `submit`, use `wait` instead of `get` |
| `KardinalRateLimitError` | `429`: temporary overload | Retried automatically, except for `submit` |
| `KardinalServerError` | `500` `INTERNAL_SERVER_ERROR`, or any other `5xx` | Retried automatically, except for `submit` |
| `KardinalConnectionError` | No HTTP response at all (DNS, connection, or read failure) | Retried automatically, except for `submit` |
| `KardinalTimeoutError` | The time limit given to `solutions.wait` elapsed | Wait longer, or track the plan without blocking |
| `KardinalOptimizationError` | `solutions.wait` has no solution to return: `NO_SOLUTION`, `PLAN_SUPERSEDED`, `OPTIMIZATION_STALLED` | See [Waiting for the solution](https://developers.kardinal.ai/sdks/plan-lifecycle.md#waiting-for-the-solution) |
| `UnknownFieldError` | A key no model declares, found before sending | Fix the field name — see [Client-side errors](#client-side-errors) |

A code the SDK doesn't know yet falls back to the family matching its HTTP status, so a new code added by the API doesn't go unnoticed. For the meaning of each code, see the `Error` schema in the [API Reference](https://developers.kardinal.ai/api-reference/plan/create-a-plan.md).

```python Python theme={null}
from kardinal import KardinalLimitError, KardinalValidationError

try:
    plan = k.routing.plans.submit(plan_input)
except KardinalValidationError as e:
    print(e.code)    # INVALID_VALUE, ID_NOT_UNIQUE, ...
    print(e.errors)  # every error of the response, not only the first
    raise
except KardinalLimitError as e:
    print(e.details)  # which limit was hit
    raise
```

```ts TypeScript theme={null}
import { KardinalLimitError, KardinalValidationError } from "@kardinal-ai/sdk";

try {
  plan = await k.routing.plans.submit(planInput);
} catch (e) {
  if (e instanceof KardinalValidationError) {
    console.log(e.code); // INVALID_VALUE, ID_NOT_UNIQUE, ...
    console.log(e.errors); // every error of the response, not only the first
  } else if (e instanceof KardinalLimitError) {
    console.log(e.details); // which limit was hit
  }
  throw e;
}
```

## Common error attributes

Every exception carries the same attributes, named in each language's case:

| Python | TypeScript | Content |
| - | - | - |
| `code` | `code` | The API's error code, such as `INVALID_VALUE` or `NOT_ALLOWED` |
| `status` | `status` | The HTTP status |
| `errors` | `errors` | Every error object of the response |
| `details` | `details` | The `properties.details` of the error `code` came from: the only way to tell apart errors that share a code |
| `retryable` | `retryable` | Whether retrying is safe and may succeed, computed by the SDK |
| `warnings` | `warnings` | Amendments applied to the payload before the error was found; usually empty |
| `request_id` | `requestId` | The `X-Request-Id` response header, when the server sends one; usually empty |

`retryable` is true for a `429`, and for a `5xx` or a connection error — except when a `submit` may have reached the server, since the plan may then already exist.

## Validation errors

A `400` means the API refused the plan as sent. `errors` holds every problem found, each with its `code` and, in `properties.path`, the field concerned: fix them all before submitting again rather than one per attempt. Most structural mistakes never reach the API: the SDKs catch them locally first (see [Validating locally before you spend credits](https://developers.kardinal.ai/sdks/building-plans.md#validating-locally-before-you-spend-credits)).

## Quotas and rate limits

**`403`: usually a limit.** A `403` `NOT_ALLOWED` usually means a limit was hit. From 1.1.0, the SDKs sort a `403` by what its response carries, and `details` still tells the cases apart. Three cases are limits, and each raises `KardinalLimitError`:

* **Plan-size limit** (too many resources, orders, or stops, or more than 4 stops in an order without `successiveStops`): `errors` also holds one `INVALID_VALUE` entry per exceeded limit, naming the field and the allowed value. Shrink the plan.
* **Daily or monthly optimization quota**: wait, or ask for a higher quota. A restart with `plans.start` counts as one optimization against this quota.
* **Insufficient credits**: top up your credits in the Console.

Two other situations return a `403` that isn't a limit, and each raises another class from 1.1.0:

* **A revoked or regenerated key** raises `KardinalAuthError`, with `.status` set to `403`. `details` is `the token is invalid`, on every call, reads and deletes included. It isn't a `401`: only a missing, malformed, or expired key gets a `401`. Code that tests `status == 401` to detect a key problem therefore misses a revoked key. Catch `KardinalAuthError` from 1.1.0, or compare `details` with `the token is invalid` in any version. Use the current key from the Console.
* **An archived plan, updated, stopped, or restarted without `force`** raises `KardinalValidationError`, and `errors` has no field path. `details` is `Cannot update an archived plan, except with the 'force' query param`. Pass `force` to unarchive the plan, knowing that a forced update or restart bills every stop again (see [Re-optimizing with `update`](https://developers.kardinal.ai/sdks/plan-lifecycle#re-optimizing-with-update)).

Any other `403` raises `KardinalForbiddenError`. Read its `details` and `errors` to find the cause.

In 1.0.x, every `403` raises `KardinalLimitError`, and `details` is the only way to tell the cases apart.

See [Reaching a limit (403)](https://developers.kardinal.ai/reference/limits-and-quotas.md#reaching-a-limit-403) and [Pricing and credits](https://developers.kardinal.ai/reference/pricing-and-credits.md) for the values.

**`429`: a temporary overload, not a quota.** It comes with an empty body. The SDKs retry it on their own, honouring a `Retry-After` header if the API sends one, and backing off otherwise. See [Temporary overload (429)](https://developers.kardinal.ai/reference/limits-and-quotas.md#temporary-overload-429).

## What the SDKs retry

| Call | Retried after a network error, a `429`, or a `5xx` |
| - | - |
| `plans.get`, `plans.list`, `plans.get_status` / `getStatus`, `solutions.get`, `solutions.get_objectives` / `getObjectives` | Yes |
| `plans.update`, `plans.replace`, `plans.delete`, `plans.start`, `plans.stop` | Yes: replaying them is harmless |
| `solutions.wait` | Yes, on each call it makes |
| `plans.submit` | **Never** |

The number of retries is set by `max_retries` / `maxRetries` (3 by default), with a growing, randomized delay between attempts. `submit` is never retried because the API has no idempotency key: a retried `submit` could create the plan twice. After a failed `submit`, check with `plans.list` whether the plan exists before submitting again.

## Client-side errors

Some errors are raised before any request is sent:

* **`UnknownFieldError`** — `submit` refuses a plan containing a key no model declares, and lists each one with its path and the closest real field name. The API would drop such a key without an error: a misspelled `operationDurationn` would leave the stop with no service time, and the plan would still look valid.

  ```
  Unknown field(s) in the plan:
    plan.resources[0].maxWorkingDurationn       (did you mean maxWorkingDuration?)
    plan.orders[0].stops[0].operationDurationn  (did you mean operationDuration?)
  ```

  `update` sorts unknown keys by origin: a key the server sent, from a field added after your SDK version, is sent back untouched; a key you added is refused as a typo. To send a field the API supports but your SDK version doesn't know yet, name it explicitly: `allow_unknown=["aNewField"]` (Python) or `{ allowUnknown: ["aNewField"] }` (TypeScript). A name listed there is allowed anywhere in the plan, so prefer distinctive names.

* **Model validation** — a missing required field or a wrong type fails when the plan is built or parsed: `pydantic.ValidationError` in Python, `ZodError` in TypeScript.

* **Missing key** — `MissingApiKeyError` and `EmptyApiKeyError`, raised when creating the client — see [API key resolution](https://developers.kardinal.ai/sdks/configuration.md#api-key-resolution).

> [tab] Python
>
> On a plan this SDK didn't read from the API (built by hand, or loaded from a file), `update` can't tell where an unknown key came from: it raises an `UnknownFieldWarning` through Python's `warnings` module, only for a key within two edits of a real field, and sends the plan.

> [tab] TypeScript
>
> On a plan this client didn't read from the API in the same process, `update` can't tell where an unknown key came from: it reports a likely typo to the `onWarning` callback (`console.warn` by default) and sends the plan. The client remembers the keys the server sent for the last 64 plans it read.

## Warnings on successful calls

When the API accepts a plan but amends part of it — a `maxOptimizationDuration` clamped to your agency's cap, crow-fly distances forced in the sandbox, predictive traffic turned off — `submit`, `update`, and `replace` return the amendments in `warnings`:

```python Python theme={null}
plan = k.routing.plans.submit(plan_input)
for warning in plan.warnings:
    print(warning.code, warning.properties)  # for example, maxOptimizationDuration clamped
```

```ts TypeScript theme={null}
plan = await k.routing.plans.submit(planInput);
for (const warning of plan.warnings) {
  console.log(warning.code, warning.properties); // for example, maxOptimizationDuration clamped
}
```

Read them from that return value: warnings aren't stored with the plan, so a later `get` never returns them, only the amended values. Solutions, objective lists, and the references returned by `start` and `stop` carry a `warnings` field too. The [`Warning` schema](https://developers.kardinal.ai/api-reference/plan/create-a-plan) in the API Reference lists what each one means.

Every replacement currently has the code `INVALID_VALUE` and the message `The field value is not valid.`, the same as a validation error. Other warnings can use `INVALID_VALUE` too, or `ID_NOT_UNIQUE` and `KEYS_NOT_UNIQUE` for duplicates. The code and the message don't tell you what happened. Only `properties.path` does, and it is stable. In Python, read it with `(warning.properties or {}).get("path")`. `properties` is a dict and can be `None`, so `warning.properties.path` raises an `AttributeError`. In TypeScript, read it with `warning.properties?.path`.

Currently, the API replaces a value in three cases. It lowers `maxOptimizationDuration` to your agency's cap. In the sandbox, it turns predictive traffic off and forces crow-fly distances. The first case has the path `maxOptimizationDuration`. The other two share the path `resources.N.vehicleProfile`. `N` is the position of the resource in the plan the API returns, and that position follows the order of the plan you sent. A warning on any other path means the API accepted a value that is probably a mistake. It replaced nothing, so check that value.

The text in `properties.details` is not stable. It is English text written by the API. It contains the internal agency id. It writes durations in an internal format such as `6h0m0s`. Don't show `details` or `message` to the planner. Build your own message from the path and from the value stored at that path in the plan the API returned. For example:

* The path is `resources.1.vehicleProfile`, and the stored value there is `{"type": "fly", "kmph": 45}`. Take the `id` of that resource, `truck-2`, and show `truck-2: straight-line distances at 45 km/h`.
* The path is `maxOptimizationDuration`, and the stored value is `PT6H`. Show `Optimization time reduced to 6 hours`.

The SDKs also report each kind of warning once, so you see it without writing any code. The sandbox, for example, currently sends the crow-fly warning for every vehicle, a `fly` vehicle included, and you get one line for all of them. A vehicle sent with `withTraffic: true` gets a second warning on the same path, because the sandbox also turns its traffic off.

> [tab] Python
>
> `submit`, `update`, and `replace` log one line per kind of warning on the `kardinal` logger, at the `WARNING` level. Python prints it on stderr, with no logging setup. To silence the lines, raise the level of the logger:
>
> ```python theme={null}
> import logging
>
> logging.getLogger("kardinal").setLevel(logging.ERROR)
> ```
>
> If your application calls `logging.config.dictConfig` after the first warning, set `disable_existing_loggers` to `False` in that configuration. Otherwise, `dictConfig` disables the `kardinal` logger.

> [tab] TypeScript
>
> `submit`, `update`, and `replace` pass one line per kind of warning to `onWarning`, with an empty `fields` list. By default, `onWarning` is `console.warn`. A no-op handler, `onWarning: () => {}`, silences the lines. It also hides the typo warnings of `update`, which come with a non-empty `fields` list. This handler keeps the typo warnings only:
>
> ```ts theme={null}
> const typosOnly = new Kardinal({
>   onWarning: (message, fields) => {
>     if (fields.length > 0) console.warn(message);
>   },
> });
> ```
>
> If your handler throws, the SDK writes the failure with `console.error`. The call still returns the plan, because the API has already accepted it.

The wording of these lines may change in any release. A program should read the `warnings` of the returned plan instead. When the API rejects a plan, its warnings come with the error, and the SDKs don't report them.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.