# Errors and retries

> Retry a step with RetryPolicy, and choose Transient, Poison or Fatal to say what a failure means.

Source: https://docs.pyrula.io/workflows/guides/errors-and-retries/

A step that raises does not retry by default. The exception comes back out of
`ctx.step`, where the body can catch it. If nothing catches it, the run ends with
`run:error`.

```python
from pyrula.workflows import RetryPolicy, workflow


@workflow(name="sync")
async def sync(ctx, account: str) -> str:
    try:
        return await ctx.step(
            "pull",
            pull_account,
            account,
            retry=RetryPolicy(max_attempts=5, initial_backoff=0.5),
            timeout=30,
        )
    except ConnectionError:
        return "skipped: upstream down"
```

A failure the body catches is a recorded outcome. On replay the same call raises the same exception, so the body takes the same branch and the step doesn't re-run. The class must be importable from a loaded module.

Some exceptions can't be rebuilt: one with a non-JSON attribute (an HTTP response, a client object), a pydantic `ValidationError` or a class defined inside a function. Replay raises `pyrula.RecordedError` with the recorded `type_path` and `message` instead; it subclasses the original class when that is loaded, so `except` still matches.

A failure the body doesn't handle ends the attempt and is listed in `run:error.escaped_steps`, including one the body replaces with a new exception from its `except` block, with or without `from` (`from None` counts too), when it made no durable call there. A requeue or retry runs each listed step again. A failure the body handled isn't listed, and a replay serves the recorded failure instead: the body made a durable call after catching it (in the `except` block, a `finally` cleanup step or after `gather(..., return_exceptions=True)` returned it as a value). Compensation in a different task isn't seen, so run it in the `except` block.

## Return values

The return value is journaled in `run:complete`, so it must be JSON, a pydantic model or a dataclass. Anything else ends the run with `run:error`, code `result_not_serializable`, naming the type, with no retry. `NaN`, `inf` and a non-`str` `Enum` fail this way.

## Suspension

`ctx.sleep`, `ctx.wait_for_signal`, `ctx.interrupt`, pause, cancel and `ctx.continue_as_new` stop the body with a `BaseException` subclass, so `except Exception` doesn't catch them. Don't wrap durable calls in `except BaseException`; clean up in `finally`.

## RetryPolicy

```python
RetryPolicy(
    max_attempts=3,  # counts the first try; 1 = no retry
    initial_backoff=0.1,  # seconds
    max_backoff=30.0,
    backoff_multiplier=2.0,
    retryable=None,  # tuple of exception types; None = every Exception
    jitter=0.5,  # fraction of each delay randomized; 0 = exact, 1 = full jitter
)
```

`retry=` and `timeout=` (seconds per attempt) work on `ctx.step` and `ctx.once`. A retried step journals one `step:done` or `step:error`, the final outcome. When more than one attempt ran, that event also carries `attempts` (the total) and the most recent failed attempts under `retries`. `max_attempts` counts within one execution; a worker crash starts a new one at attempt 1.

A cancel requested during a retry backoff ends the run within about a second; a pause waits for the step's boundary.

A sync function can't have both `timeout=` and `retry=`, because a thread can't be cancelled. Pyrula raises `ValueError`; make the function `async def` or drop `timeout=`.

## Saying what a failure means

Raise one of these from a step to override `retryable`:

| Raise | Retried | Meaning |
|---|---|---|
| `Transient` | yes, up to `max_attempts` | A passing condition: network blip, lock contention. |
| `Poison` | never | Bad input. Retrying can't help. |
| `Fatal` | never | Broken invariant or missing config. |
| anything else | per `retryable` | |

```python
from pyrula.workflows import Poison, Transient


def charge(order):
    resp = gateway.charge(order)
    if resp.status == 429:
        raise Transient("rate limited")
    if resp.status == 422:
        raise Poison(f"card rejected: {resp.reason}")
    return resp.id
```

In a workflow `Poison` and `Fatal` both fail the step at once. A run ending on one writes `run:error` with code `poison` or `fatal`. Both take an optional `code=` identifier such as `"card.declined"` (never data), which lands in `run:error.user_code`. A [Kafka binding](https://docs.pyrula.io/workflows/guides/kafka.md) then applies its own `on_error` disposition.

A run that ends on `Transient` writes code `transient` with `error_type` naming the class, whether a step used up its retries or the body raised it with no `retry=` to catch it. A call Pyrula refuses, such as `ctx.sleep` inside a `ctx.gather` leg, writes `usage_error`, and fails the same way on every retry until you change the code.

## When the attempt itself breaks

If the workflow isn't registered on this worker or a corrupt event breaks replay, the worker retries up to `WorkerConfig.poison_max_retries` (3), then writes a terminal `run:error`.

## When the store fails under a run

A store outage doesn't fail the run: the worker abandons the attempt, appends `run:requeued` with `reason: store_unavailable` and the next claim replays the journal. Each requeue counts against `max_store_requeues` (default 20), then the run ends with `store_unavailable`. A Kafka-driven run is held instead ([Kafka](https://docs.pyrula.io/workflows/guides/kafka.md#a-store-outage-holds-the-record)). Runs stranded by a version mismatch are covered in [Versioning](https://docs.pyrula.io/workflows/guides/versioning.md).

## Retry a failed run

`RetryPolicy` covers attempts inside one run. Once a run has ended in `run:error`, `client.retry(name, run_id)` (or `pyrula runs retry`) starts a new linked run that serves every recorded step and runs the failed step onward live ([Retrying a failed run](https://docs.pyrula.io/workflows/concepts/replay-and-recovery.md#retrying-a-failed-run)). A cancelled run is refused with `retry_cancelled`.

## Stack trace and fingerprint

A failing step journals a redacted `error_stack` and an `error_fingerprint` on `step:error`, and `run:error` carries the same pair. The fingerprint hashes the exception class and your frames, so one bug groups across deploys.
