# Guardrail Failure Handling

A policy match and a guardrail failure are different events. A match means the guardrail evaluated content and returned a verdict. A failure means the check could not produce a decision or AISIX could not present the content for evaluation.

Failure policies decide whether traffic stops or continues without a verdict. AISIX fails closed by default; fail-open settings preserve availability but record that content bypassed a check. Held streams apply additional safety rules described in [Streaming Guardrail Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/streaming-behavior.md).

## When a Guardrail Cannot Complete Its Check[​](#when-a-guardrail-cannot-complete-its-check "Direct link to When a Guardrail Cannot Complete Its Check")

A guardrail can fail before producing a verdict for one of two reasons:

| Failure                                        | Affected Guardrails                                      | Examples                                                                                   |
| ---------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| A screening backend does not return a decision | Remote providers, semantic screening, and custom scripts | Connection errors, throttling, timeouts, script exceptions, or unreadable verdicts         |
| AISIX cannot present the content as delivered  | Every guardrail kind, including keyword and PII          | An unreadable Messages request, invalid MCP result, or transcript containing invalid UTF-8 |

Remote-provider failures apply to AWS Bedrock, Azure AI Content Safety, Alibaba Cloud, Lakera, OpenAI Moderation, and Presidio guardrails. Built-in keyword and PII guardrails never call a backend, but their failure policy still governs content AISIX cannot decode for them.

## Choose Failure Policies[​](#choose-failure-policies "Direct link to Choose Failure Policies")

Failure policies control whether AISIX refuses or releases content when evaluation cannot finish. Both input and output checks default to fail closed.

| Setting            | Check Side | Guardrail Kinds                   | Default |
| ------------------ | ---------- | --------------------------------- | ------- |
| `fail_open`        | Input      | Every kind                        | `false` |
| `output_fail_open` | Output     | Every kind except keyword and PII | `false` |
| `fail_open`        | Output     | Keyword and PII                   | `false` |

In block mode:

* `false` refuses traffic when the applicable check cannot complete.
* `true` releases traffic and records a bypass.

### Which Hook Each Setting Governs[​](#which-hook-each-setting-governs "Direct link to Which Hook Each Setting Governs")

The field to configure depends on the hook and guardrail kind. Remote guardrails use `fail_open` for input and `output_fail_open` for output. Keyword and PII have no `output_fail_open`; their single `fail_open` value governs both hooks. Sending `output_fail_open` for either built-in kind is rejected.

In AISIX Enterprise or AISIX Cloud, `fail_open` is a top-level guardrail field. `output_fail_open` belongs inside the kind-specific `config` object. In a format-v2 resources file, both fields appear directly on the guardrail entry.

Monitor mode and held streams modify parts of this default behavior.

## How Monitor Mode Handles Failures[​](#how-monitor-mode-handles-failures "Direct link to How Monitor Mode Handles Failures")

Monitor mode prevents a guardrail verdict from changing traffic, but it does not turn every processing failure into an allow. Failures raised while AISIX prepares or rewrites content still follow their applicable policy.

| Failure                                                        | Monitor-Only Chain                                                                                                                               |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Screening backend fails                                        | AISIX serves the request. A fail-closed evaluation records `would_block`; a fail-open evaluation records a bypass.                               |
| Request, MCP result, or transcript is unreadable               | The applicable failure policy still decides whether AISIX refuses or releases it.                                                                |
| Stream overflow, empty held stream, or mask write-back failure | Cannot occur because a monitor-only chain does not hold or rewrite output. An enforcing guardrail in the same chain can still cause the refusal. |

Use block mode with a fail-closed policy when an unavailable screening backend must stop traffic.

## What Happens to Content AISIX Cannot Read[​](#what-happens-to-content-aisix-cannot-read "Direct link to What Happens to Content AISIX Cannot Read")

AISIX evaluates each applicable guardrail independently. A guardrail can refuse unreadable content only when its hook covers that side of the exchange and its failure policy is closed.

| Applicable Guardrails                                    | Outcome                                                     | Usage Record                     |
| -------------------------------------------------------- | ----------------------------------------------------------- | -------------------------------- |
| At least one guardrail covers that side and fails closed | AISIX refuses the content with `unscannable_body`.          | Guardrail blocked                |
| Every guardrail covering that side fails open            | AISIX releases the content.                                 | Bypass reason `unscannable_body` |
| No guardrail covers that side                            | AISIX handles the content as if no guardrail were attached. | No guardrail refusal or bypass   |

Direction and failure policy must belong to the same guardrail. An output-only fail-closed guardrail does not cause an input-only fail-open guardrail to refuse an unreadable request.

Inference and audio routes normally return a fail-closed refusal with HTTP `422`. MCP returns HTTP `200` with an error-marked tool result so the agent can treat the refusal as tool output. See [Guardrail Refusals](https://docs.api7.ai/ai-gateway/reference/headers-and-error-codes.md#guardrail-refusals) for protocol-specific envelopes.

## Transcripts AISIX Could Not Decode[​](#transcripts-aisix-could-not-decode "Direct link to Transcripts AISIX Could Not Decode")

A non-streaming transcription or translation response can contain invalid UTF-8. AISIX scans a best-effort decode, but the original bytes remain the response payload.

| Output Guardrail State                                | Outcome                                                                              |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------ |
| At least one applicable output guardrail fails closed | AISIX returns `422` with `unscannable_body` and records a guardrail block.           |
| Every applicable output guardrail fails open          | AISIX relays the original bytes after the readable text passes and records a bypass. |
| No guardrail covers output                            | AISIX relays the original bytes without a guardrail record.                          |

A policy match in the readable text can block independently. One event can therefore carry both `guardrail_blocked` and a bypass reason of `unscannable_body`.

Valid UTF-8 `text`, `srt`, and `vtt` responses are unaffected. Parsed JSON transcripts cannot contain invalid text. AISIX follows the body the provider returned rather than the requested `response_format` when the body does not parse as JSON.

## Decode Paths Outside the Failure Policy[​](#decode-paths-outside-the-failure-policy "Direct link to Decode Paths Outside the Failure Policy")

Not every best-effort decode invokes a guardrail failure policy. Two non-JSON paths scan best-effort text and can relay the original body even when the guardrail's failure policy is closed:

| Path                                            | Behavior                                                                                        |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| Batch or Fine-tuning response                   | An output guardrail scans the best-effort decode, and AISIX can still relay the original bytes. |
| Opaque passthrough request or buffered response | The applicable hook scans the best-effort decode, and AISIX can still relay the original body.  |

Neither path records `unscannable_body`. A malformed recognized envelope is not an exception; it follows the configured failure policy.

A multipart prompt part with invalid UTF-8 on transcription, translation, or image editing is rejected with HTTP `400` before guardrails run. It records neither a guardrail refusal nor a bypass.

## When AISIX Cannot Apply a Mask[​](#when-aisix-cannot-apply-a-mask "Direct link to When AISIX Cannot Apply a Mask")

An MCP mask verdict must be written back into the original tool arguments or result. If the JSON was parsed but AISIX cannot apply the rewrite safely, it refuses the tool call or result with `mask_writeback_failed`.

This safety failure does not consult `fail_open` or `output_fail_open`. Other surfaces that cannot represent masked content follow the outcomes in [Surfaces That Cannot Apply a Mask](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/content-coverage.md#surfaces-that-cannot-apply-a-mask).

## Failures While Holding a Stream[​](#failures-while-holding-a-stream "Direct link to Failures While Holding a Stream")

Once an enforcing output guardrail holds a stream, AISIX uses stricter rules than ordinary unreadable-content handling:

| Condition                                                                                              | Outcome                                                                | Recorded Evidence                      |
| ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | -------------------------------------- |
| Nothing scannable remains                                                                              | AISIX refuses the response.                                            | Failure tag `unscannable_body`         |
| The holding buffer reaches its limit, and every holding guardrail uses `on_buffer_exceeded: fail_open` | AISIX releases the held content and continues without output scanning. | Bypass reason `output_buffer_exceeded` |
| The holding buffer reaches its limit, and at least one holding guardrail fails closed                  | AISIX refuses the response.                                            | Action `blocked_buffer_exceeded`       |

The general `fail_open` and `output_fail_open` settings do not control these outcomes. Buffer overflow uses `on_buffer_exceeded`; AISIX always refuses a held stream with no scannable content. Keyword and PII output guardrails can encounter these conditions because both hold streamed output for enforcement. A monitor-only guardrail cannot.

MCP results and non-streaming transcripts continue to use the normal output failure policy because they are not held streams. See [Streaming Guardrail Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/streaming-behavior.md) for limits and frame processing.

## Caller Responses[​](#caller-responses "Direct link to Caller Responses")

When AISIX refuses traffic, it preserves the protocol expected by the requested surface rather than returning one universal error shape:

| Surface                                | Caller Response                                                                                                                                                                     |
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OpenAI-compatible non-streaming routes | HTTP `422` with an OpenAI-style `content_filter` envelope                                                                                                                           |
| Chat Completions streaming             | HTTP `200`, followed by a terminal SSE error event when the stream is refused                                                                                                       |
| Responses                              | A native Responses path can refuse with HTTP `422` before delivery. A bridged stream uses HTTP `200`, followed by an `error` event and `response.failed`.                           |
| Passthrough routes                     | A buffered refusal uses HTTP `422`. After HTTP `200`, a streaming refusal uses the Anthropic envelope for a recognized Messages stream and the Chat Completions envelope otherwise. |
| Anthropic non-streaming                | HTTP `422` with `invalid_request_error` and `error.code` `content_filter` or `guardrail_unavailable`                                                                                |
| Anthropic streaming                    | HTTP `200`, followed by a terminal SSE error event using the Anthropic envelope                                                                                                     |
| Realtime                               | WebSocket error frame followed by a close                                                                                                                                           |
| A2A                                    | HTTP `422` with a JSON-RPC error envelope                                                                                                                                           |
| MCP                                    | HTTP `200` with a result marked `isError`, so the agent receives tool output rather than a protocol error                                                                           |

See [Guardrail Refusals](https://docs.api7.ai/ai-gateway/reference/headers-and-error-codes.md#guardrail-refusals) for exact envelopes and failure tags.

## Interpret Bypass Reasons[​](#interpret-bypass-reasons "Direct link to Interpret Bypass Reasons")

When fail-open behavior lets traffic continue, AISIX records the bounded reason in `guardrail_bypassed_reason`, shown in AISIX Enterprise and AISIX Cloud as **Bypass reason**. Every proxied route's usage event can carry the field; retroactive Batch billing rows cannot because no gateway request produced them.

The value can be a kind-specific tag such as `lakera_timeout` or a gateway tag such as `unscannable_body` or `output_buffer_exceeded`. Tags contain at most 64 lowercase letters, digits, and underscores.

When several bypasses occur, the first reason wins.

| Recorded Fields                       | Interpretation                                                                                                          |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Bypass reason only                    | At least one applicable check failed open and traffic continued.                                                        |
| Bypass reason and `guardrail_blocked` | One check failed open, but another guardrail or hook later blocked. Some content may already have reached the provider. |
| Empty bypass reason                   | No fail-open event was recorded. This does not prove that every relayed byte was inspected.                             |

### Metrics and Bypasses[​](#metrics-and-bypasses "Direct link to Metrics and Bypasses")

Usage events explain one request, while metrics aggregate bypass behavior across traffic. `aisix_guardrail_bypasses_total` counts guardrail executions that bypassed and gateway-raised `unscannable_body` or `output_buffer_exceeded` passes. The `result="bypassed"` slice of `aisix_guardrail_latency_seconds` counts only timed guardrail executions.

A backend failure appears in both metrics and the usage record. A gateway-raised pass appears in the bypass counter and usage record, but not in the latency histogram. See [Guardrail Metrics](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#guardrail-metrics) for the histogram contract.
