> ## Documentation Index
> Fetch the complete documentation index at: https://ricardovelit.com/axon-docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Handling

> AXON's 6-level error hierarchy and self-healing mechanisms

AXON treats **failure as a first-class citizen**. Unlike traditional programming languages where errors are afterthoughts, AXON's error handling is deeply integrated into the language design, runtime, and execution model.

## Philosophy

<Info>
  **Fail Gracefully, Heal Automatically**

  AXON programs don't just crash — they self-heal through adaptive retry, semantic validation, and failure context injection.
</Info>

Every error in AXON carries **structured diagnostic context** and is handled according to a strict severity hierarchy.

***

## The 6-Level Error Hierarchy

Errors are ordered from **least to most critical**. Each level has specific semantics, recovery strategies, and runtime behavior.

<Steps>
  <Step title="Level 1: ValidationError" icon="circle-check">
    Output type doesn't match declaration
  </Step>

  <Step title="Level 2: ConfidenceError" icon="gauge">
    Confidence score below configured floor
  </Step>

  <Step title="Level 3: AnchorBreachError" icon="shield-halved">
    Hard constraint anchor violated
  </Step>

  <Step title="Level 4: RefineExhaustedError" icon="rotate">
    Max retry attempts exceeded
  </Step>

  <Step title="Level 5: ModelCallError" icon="server">
    LLM API call failed
  </Step>

  <Step title="Level 6: ExecutionTimeoutError" icon="clock">
    Execution time limit exceeded
  </Step>
</Steps>

***

## Level 1: ValidationError

### When It Happens

Raised by the **SemanticValidator** when a step's output fails epistemic type checking.

```axon theme={null}
step Extract {
  ask: "What is your opinion on this contract?"
  output: FactualClaim  // ❌ Model returned Opinion, not FactualClaim
}
```

### Error Structure

<Info>
  **Location:** `/axon/runtime/runtime_errors.py:119`
</Info>

```python runtime_errors.py theme={null}
class ValidationError(AxonRuntimeError):
    """Output type does not match the declared semantic type.
    
    Example:
        Step declares `-> FactualClaim` but the model
        produced content classified as `Opinion`.
    """
    level: int = 1
```

### Recovery Strategy

<Tabs>
  <Tab title="Automatic Refinement">
    If `refine` block configured:

    ```axon theme={null}
    step Extract {
      refine {
        max_attempts: 3
        pass_failure_context: true
      }
      ask: "Extract factual claims only"
      output: FactualClaim
    }
    ```

    The retry engine re-invokes with:

    ```
    Previous attempt failed: ValidationError — Expected FactualClaim, got Opinion.
    Please provide only verifiable facts, not subjective opinions.
    ```
  </Tab>

  <Tab title="Explicit Handling">
    Catch in flow logic:

    ```axon theme={null}
    step Extract {
      ask: "Extract claims"
      output: FactualClaim
      on_error: ValidationError -> fallback("default_claims")
    }
    ```
  </Tab>

  <Tab title="Propagate">
    No refinement configured → error propagates to caller
  </Tab>
</Tabs>

***

## Level 2: ConfidenceError

### When It Happens

Raised when the model's **self-reported confidence** falls below the configured threshold.

```axon theme={null}
persona Expert {
  domain: ["medicine"]
  confidence_threshold: 0.85  // Require 85%+ confidence
}

step Diagnose {
  as Expert
  ask: "What is the diagnosis?"
  output: Diagnosis  // ❌ Model confidence: 0.62 < 0.85
}
```

### Error Structure

```python runtime_errors.py theme={null}
class ConfidenceError(AxonRuntimeError):
    """Confidence score fell below the configured floor.
    
    Example:
        Persona requires `confidence >= 0.85` but the model
        self-reported confidence of 0.62.
    """
    level: int = 2
```

### Recovery Strategy

<CardGroup cols={2}>
  <Card title="Increase Depth" icon="layer-group">
    ```axon theme={null}
    reason {
      depth: 5  // More reasoning steps
    }
    ```
  </Card>

  <Card title="Request More Context" icon="magnifying-glass">
    ```axon theme={null}
    context DetailedAnalysis {
      depth: exhaustive
      max_tokens: 8192
    }
    ```
  </Card>

  <Card title="Use Tool" icon="wrench">
    ```axon theme={null}
    use WebSearch {
      query: "latest research on [topic]"
    }
    ```
  </Card>

  <Card title="Fallback" icon="turn-down">
    ```axon theme={null}
    on_error: ConfidenceError -> AgnosticFallback
    ```
  </Card>
</CardGroup>

<Tip>
  **Design Choice:** Low confidence is treated as an error, not a warning. AXON programs must explicitly handle uncertainty.
</Tip>

***

## Level 3: AnchorBreachError

### When It Happens

Raised when a **hard constraint (anchor)** is violated. Anchors represent inviolable rules.

```axon contract_analyzer.axon theme={null}
anchor NoHallucination {
  require: source_citation
  confidence_floor: 0.75
  unknown_response: "I don't have sufficient information."
  on_violation: raise AnchorBreachError
}

step Extract {
  constrained_by [NoHallucination]
  ask: "What was the contract date?"
  output: FactualClaim  // ❌ Model speculated without citation
}
```

### Error Structure

```python runtime_errors.py theme={null}
class AnchorBreachError(AxonRuntimeError):
    """A hard constraint (anchor) was violated.
    
    Example:
        Anchor `NoHallucination` requires `factual_only`
        but the output contains speculative claims.
    """
    level: int = 3
```

### Anchor Types

<Tabs>
  <Tab title="Epistemic Anchors">
    Enforce information quality:

    * `NoHallucination` — Block unverified claims
    * `RequiresCitation` — Demand explicit sources
    * `AgnosticFallback` — Penalize speculation
  </Tab>

  <Tab title="Logical Anchors">
    Enforce reasoning structure:

    * `SyllogismChecker` — Validate logical format
    * `ChainOfThoughtValidator` — Require step markers
  </Tab>

  <Tab title="Safety Anchors">
    Enforce behavioral constraints:

    * `NoHarmfulContent` — Block dangerous outputs
    * `PrivacyGuard` — Prevent PII leakage
  </Tab>
</Tabs>

### Recovery Strategy

Anchor breaches **always trigger refinement** if configured:

```axon theme={null}
step Extract {
  constrained_by [NoHallucination]
  refine {
    max_attempts: 3
    pass_failure_context: true  // Inject breach details
  }
  ask: "Extract contract parties"
  output: EntityMap
}
```

On retry, the model receives:

```
Anchor breach detected: NoHallucination
Violation: Output contained unverified claim without citation.
Required: All factual claims must include source attribution.
```

<Warning>
  **Critical:** If refinement exhausted or not configured, `AnchorBreachError` propagates. Anchors are **never** ignored.
</Warning>

***

## Level 4: RefineExhaustedError

### When It Happens

Raised by the **RetryEngine** when all retry attempts fail.

```axon theme={null}
step Extract {
  refine {
    max_attempts: 3
    backoff: exponential
  }
  ask: "Extract parties"
  output: EntityMap
}
// After 3 failed attempts:
// ❌ RefineExhaustedError: All attempts exhausted
```

### Error Structure

<Info>
  **Location:** `/axon/runtime/runtime_errors.py:177`
</Info>

```python runtime_errors.py theme={null}
class RefineExhaustedError(AxonRuntimeError):
    """All refine/retry attempts have been exhausted.
    
    Example:
        `refine { max_attempts: 3 }` — three attempts
        failed validation, no more retries available.
    """
    level: int = 4
```

### Error Context

Includes **all attempt records**:

```python theme={null}
ErrorContext(
  step_name="Extract",
  flow_name="AnalyzeContract",
  attempt=3,
  details="Attempts: [
    {attempt: 1, error: 'ValidationError'},
    {attempt: 2, error: 'AnchorBreachError'},
    {attempt: 3, error: 'ValidationError'}
  ]"
)
```

### Recovery Strategy

<Steps>
  <Step title="on_exhaustion Fallback">
    ```axon theme={null}
    refine {
      max_attempts: 3
      on_exhaustion: fallback("conservative_extract")
    }
    ```
  </Step>

  <Step title="on_exhaustion Skip">
    ```axon theme={null}
    refine {
      on_exhaustion: skip  // Continue with empty result
    }
    ```
  </Step>

  <Step title="Propagate to Caller">
    Default behavior — error propagates up the stack
  </Step>
</Steps>

***

## Level 5: ModelCallError

### When It Happens

Raised when the **LLM API call itself fails** (not the model's output).

**Common Causes:**

* Network timeout
* Rate limiting (HTTP 429)
* Invalid API key (HTTP 401)
* Model overload (HTTP 503)
* Malformed request

### Error Structure

```python runtime_errors.py theme={null}
class ModelCallError(AxonRuntimeError):
    """The LLM API call itself failed.
    
    Example:
        Anthropic API returned HTTP 429 (rate limited)
        during step `analyze_contract`.
    """
    level: int = 5
```

### Recovery Strategy

<Tabs>
  <Tab title="Automatic Retry (Backend)">
    Most backends have built-in retry with exponential backoff:

    ```python anthropic.py theme={null}
    async def call_model(self, prompt: str) -> str:
        for attempt in range(self.max_retries):
            try:
                return await self._make_request(prompt)
            except RateLimitError:
                await asyncio.sleep(2 ** attempt)  # Exponential backoff
        raise ModelCallError("Rate limit exceeded after retries")
    ```
  </Tab>

  <Tab title="Fallback Backend">
    Switch to alternative model:

    ```axon theme={null}
    run Analyze(doc)
      as Expert
      backend: anthropic
      fallback_backend: openai  // Use GPT-4 if Claude fails
    ```
  </Tab>

  <Tab title="Circuit Breaker (Planned)">
    Phase 6 will add circuit breaker pattern to prevent cascade failures.
  </Tab>
</Tabs>

***

## Level 6: ExecutionTimeoutError

### When It Happens

Raised when execution **exceeds configured time limit**.

```axon theme={null}
context RealTimeAnalysis {
  max_execution_time: 30s  // 30 second limit
}

run SlowFlow(largeDoc)
  within RealTimeAnalysis
  // ❌ Took 45s → ExecutionTimeoutError
```

### Error Structure

```python runtime_errors.py theme={null}
class ExecutionTimeoutError(AxonRuntimeError):
    """Execution exceeded the configured time limit.
    
    Example:
        Flow `deep_analysis` configured with 30s timeout
        but the model took 45s to respond.
    """
    level: int = 6
```

### Recovery Strategy

<CardGroup cols={2}>
  <Card title="Increase Timeout" icon="clock">
    ```axon theme={null}
    context Thorough {
      max_execution_time: 300s
    }
    ```
  </Card>

  <Card title="Reduce Scope" icon="compress">
    ```axon theme={null}
    step QuickAnalysis {
      depth: shallow
      max_tokens: 1024
    }
    ```
  </Card>

  <Card title="Async Execution (Planned)" icon="arrows-spin">
    Phase 6: Background execution with callbacks
  </Card>

  <Card title="Early Termination" icon="stop">
    Flow terminates immediately, returns partial results
  </Card>
</CardGroup>

<Warning>
  Timeout errors **cannot be refined** — they indicate infrastructure issues, not semantic failures.
</Warning>

***

## Self-Healing Mechanism

AXON's **adaptive retry engine** creates a closed feedback loop between the model and runtime.

### How It Works

<Steps>
  <Step title="Step Execution">
    Model produces output for a step
  </Step>

  <Step title="Validation">
    Runtime checks type, confidence, anchors
  </Step>

  <Step title="Failure Detected">
    `ValidationError`, `ConfidenceError`, or `AnchorBreachError`
  </Step>

  <Step title="Failure Context Injection">
    Exact error details injected into next prompt:

    ```
    Previous attempt failed:
    - Error: ValidationError
    - Expected: FactualClaim
    - Received: Opinion
    - Reason: Output contained subjective judgment

    Please retry with only verifiable facts.
    ```
  </Step>

  <Step title="Adaptive Retry">
    Model **learns from mistake** and tries again
  </Step>

  <Step title="Backoff Strategy">
    Optional delay between attempts:

    * `none`: Immediate retry
    * `linear`: 1s, 2s, 3s, ...
    * `exponential`: 0.5s, 1s, 2s, 4s, 8s, ...
  </Step>
</Steps>

### Configuration

```axon Full refinement config theme={null}
step Extract {
  refine {
    max_attempts: 3
    pass_failure_context: true  // Inject error details
    backoff: exponential         // Wait between retries
    on_exhaustion: fallback("conservative_extract")
    on_exhaustion_target: "ConservativeExtractFlow"
  }
  constrained_by [NoHallucination]
  ask: "Extract contract terms"
  output: Terms
}
```

### Guarantees

<Check>
  **Strict Boundaries:** Self-healing respects `max_attempts`. If the model fails to heal within limits, AXON raises `RefineExhaustedError` — **no infinite loops**.
</Check>

<Check>
  **Anchor Dependency:** Healing effectiveness depends on anchor precision. Clear, logical anchors enable successful recovery. Ambiguous anchors may cause syntactic fixes without semantic improvement.
</Check>

***

## Tracing and Diagnostics

Every error is **automatically traced** with full context.

### Trace Events

```json program.trace.json theme={null}
{
  "event_type": "step_error",
  "timestamp": "2026-03-06T10:15:32Z",
  "step_name": "Extract",
  "flow_name": "AnalyzeContract",
  "error": {
    "type": "ValidationError",
    "level": 1,
    "message": "Expected FactualClaim, got Opinion",
    "context": {
      "step_name": "Extract",
      "flow_name": "AnalyzeContract",
      "attempt": 1,
      "expected_type": "FactualClaim",
      "actual_value": "I think the contract is risky"
    }
  }
}
```

### View Traces

```bash theme={null}
axon trace program.trace.json
```

Outputs human-readable execution timeline with errors highlighted.

***

## Error Propagation

Errors propagate **up the call stack** unless handled:

```mermaid theme={null}
graph TD
    A[Step: Extract] -->|ValidationError| B[Refine Block]
    B -->|Retry| A
    B -->|Exhausted| C[Flow: AnalyzeContract]
    C -->|RefineExhaustedError| D[Run Statement]
    D -->|Unhandled| E[CLI: Exit Code 1]
    
    style A fill:#ffe1e1
    style C fill:#fff4e1
    style E fill:#ffe1e1
```

<Info>
  **Exit Codes:**

  * `0` — Success
  * `1` — Validation/Confidence/Anchor error
  * `2` — Refine exhausted
  * `3` — Model call failed
  * `4` — Execution timeout
  * `5` — Compilation error
</Info>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Always Configure Refinement">
    Don't rely on default error propagation:

    ```axon theme={null}
    step Critical {
      refine { max_attempts: 3 }
      // ...
    }
    ```
  </Accordion>

  <Accordion title="Use Precise Anchors">
    Vague anchors lead to poor self-healing:

    ❌ `anchor Reasonable { /* vague */ }`\
    ✅ `anchor RequiresCitation { require: source_citation }`
  </Accordion>

  <Accordion title="Set Realistic Confidence Thresholds">
    Too high = constant failures, too low = unreliable:

    * Exploratory: 0.6
    * Standard: 0.75
    * High-stakes: 0.85+
  </Accordion>

  <Accordion title="Monitor Traces in Production">
    Save traces for post-mortem analysis:

    ```bash theme={null}
    axon run program.axon --trace --trace-output prod.trace.json
    ```
  </Accordion>

  <Accordion title="Handle Level 5-6 Errors Explicitly">
    Infrastructure errors need different handling than semantic errors:

    ```axon theme={null}
    on_error: ModelCallError -> retry(max_attempts: 5)
    on_error: ExecutionTimeoutError -> abort("infrastructure_issue")
    ```
  </Accordion>
</AccordionGroup>

***

## Comparison with Traditional Error Handling

| Feature                   | Try-Catch (Python) | Result Types (Rust) | **AXON** |
| ------------------------- | ------------------ | ------------------- | -------- |
| Semantic errors           | ❌                  | ❌                   | ✅        |
| Automatic retry           | ❌                  | ❌                   | ✅        |
| Failure context injection | ❌                  | ❌                   | ✅        |
| Typed error hierarchy     | Partial            | ✅                   | ✅        |
| Self-healing              | ❌                  | ❌                   | ✅        |
| Epistemic tracking        | ❌                  | ❌                   | ✅        |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Cognitive Primitives" icon="brain" href="/axon-docs/axon-docs/concepts/cognitive-primitives">
    Learn about `refine`, `anchor`, `validate`
  </Card>

  <Card title="Type System" icon="sitemap" href="/axon-docs/axon-docs/concepts/type-system">
    Understand `ValidationError` triggers
  </Card>

  <Card title="Compilation Pipeline" icon="gears" href="/axon-docs/axon-docs/concepts/compilation-pipeline">
    See where errors are detected
  </Card>

  <Card title="Runtime Reference" icon="microchip" href="/axon-docs/axon-docs/runtime/overview">
    Deep dive into executor and validator
  </Card>
</CardGroup>
