# Errors and timeouts

## Three timeouts

|  | Bounds | Owner | Default |
| --- | --- | --- | --- |
| Call | One HTTP request or SSE stream, and gaps within it | Provider transport | Always on |
| Exec | One `exec`, retry sleeps included | `runtime.exec(timeout_s=)`, or `OPENPROGRAM_EXEC_TIMEOUT_S` | Unbounded (0) |
| Task | One Agent turn or benchmark sample | The caller, which alone knows the budget | Caller's |

## Length of a reply

Chat replies have no limit on tool interactions or total time; a stream that keeps producing is never cut for running long. User cancellation always applies. Explicit `runtime.exec` deadlines, program call-round parameters and declared budgets of standalone GUI or browser tools are not overridden.

## Call stack

| Layer | Bounds | Retries |
| --- | --- | --- |
| `Runtime.exec` | Sets one absolute deadline in a ContextVar (`utils/http_transport/deadline.py`); checks it before each attempt and each sleep | `max_retries` 3 (`OPENPROGRAM_MAX_RETRIES`), `1.5·2^n` s, ±25% |
| `Runtime._call` → `_run_async` | No running loop: `asyncio.run` on this thread. Running loop (Web, worker): a pool thread, deadline forwarded | none |
| `AgentSession._run_with_retry` | Draws on the invocation's transport allowance | 2 s, 4 s, 8 s |
| `retry_stream` (Codex), retry loop (completions) | Reads the deadline before each attempt and sleep | 5 attempts, 2 s base, 30 s cap |
| Shared httpx client | Connect, write, pool 30 s; keepalive ~60 s; force-IPv4; proxy | none |
| `_parse_sse_stream`, Codex WebSocket | `wait = min(idle, stall, total, deadline)` | none |
| `streaming/stream._delivered` | Every provider's stream passes here. Draws on the invocation's transport allowance; one attempt under a Goal or job reservation | [Re-sends](#resend) a transport failure: 5 attempts, 2 s base, 30 s cap |
| `streaming/stream._metered` | The [idle bound](#idle-bound) for every provider that has none of its own | none |

## Transport budgets

| Budget | Default | Override |
| --- | --- | --- |
| Connect, write, pool | 30 s | `OPENPROGRAM_HTTPX_{CONNECT,WRITE,POOL}_TIMEOUT_S` |
| TCP dead-peer detection | ~60 s (30 + 10 × 3) | `OPENPROGRAM_TCP_KEEPALIVE` |
| No event ([idle bound](#idle-bound)) | 300 s | `OPENPROGRAM_STREAM_IDLE_TIMEOUT_S` (0 turns it off); Codex also `OPENPROGRAM_SSE_DATA_STALL_TIMEOUT_S` |
| No bytes at all | 600 s | `OPENPROGRAM_SSE_IDLE_TIMEOUT_S` |
| Total for one stream | none (0) | `OPENPROGRAM_SSE_TOTAL_TIMEOUT_S` |
| httpx read backstop | idle + 60 s | `OPENPROGRAM_HTTPX_READ_TIMEOUT_S` |
| Large prompts | × 1.25 above 50k tokens, × 1.5 above 100k, × 2 above 200k | by `context_tokens` |
| Force IPv4, proxy | off, automatic | `OPENPROGRAM_FORCE_IPV4`, `HTTP(S)_PROXY` |

## Idle bound

A reply that stops arriving while its connection stays open ends its attempt after 300 s without an event, as `StreamIdleTimeout`: a transport error, retried by the layer that owns the attempt and shown as a retry.

- Keepalive pings and comment lines are not events.
- The wait for response headers counts as silence.
- The stalled stream is closed before the error is raised.
- A stop ends the wait at once.

| Transport | Bounded in | Retried by |
| --- | --- | --- |
| Codex subscription, WebSocket and HTTP | `read_budget.ReadBudget`, every frame or data line | `retry_stream` |
| Chat Completions (DeepSeek, xAI, OpenAI-compatible) | The provider's request and chunk loop | Its own retry loop |
| Gemini subscription | Each attempt's request and data lines; its own waits between attempts are not silence | `stream._delivered` |
| OpenAI and Azure Responses, Anthropic, Google, Bedrock, plugin providers | `stream._metered`, every event | `stream._delivered` |

A provider that bounds itself sets `bounds_own_stream_idle`.

boto3 blocks, so Bedrock reads on a thread of its own:

- The request and each event-stream read run there; each event is handed to the loop, so a stall never pauses other sessions.
- Closing the stream shuts its socket. botocore's own 60 s read timeout also applies to each read.
- The Bedrock SDK transport is disabled in the product until its network path is managed.

A server-requested wait longer than `OPENPROGRAM_RETRY_AFTER_CAP_S` is not slept through: Gemini subscription fails at once with the rate-limit error, as `retry_stream` does.

## Re-sending a failed reply

A reply that stalls or whose connection drops before its final event says nothing about the request, so `stream._delivered` sends the same request again. It serves the conversation turn path, `AgentSession` and one-shot calls alike.

| Case | What happens |
| --- | --- |
| Failure before any content | Sent again after a `retry` event. Codex and Chat Completions do this in their own loops first; a failure they spent their attempts on arrives flagged and is not sent again |
| Failure after reasoning, text or a tool call | The whole request is sent again and the partial is void, as Codex CLI and Claude Code do. The `retry` event carries `restart`; the reply's row and the loop's partial message drop the failed response's text and reasoning, so a steer during the wait commits none of it. Codex instead keeps the partial (`stop_reason="length"`) and the turn continues from it |
| Tools | Never run twice: tools run only after a response's final event, and a failed response has none |
| Reply going out to a channel | Paragraphs already sent cannot be recalled. The unsent text of the failed response is dropped, and the new response skips the opening it repeats word for word. A new response with other wording is sent whole after what went out |
| Not re-sent | Rate limit, overload, auth or a bad request (SDK retries and failover own those); a request under a Goal or job reservation; anything after a stop |
| Bound spent | The failure is flagged `transport_exhausted`, so neither `AgentSession` nor exec retries it again |
| Usage | An attempt that reached the provider and ended without a final message is recorded: with the tokens it reported, or as one request whose cost is unknown. Reaching it means streamed content, reported tokens, or silence for the idle bound; an adapter's `start` event does not count. A refusal or a connection that failed before any content is not recorded |

The consumer sees one `start` for the request, however many attempts it took. The redaction and failover wrappers own their producer task, so a stop reaches the provider request under them.

| Why 300 s |  |
| --- | --- |
| Codex CLI | `stream_idle_timeout_ms` 300 000, then up to 5 stream retries, on the same backend |
| Claude Code | Event-level stream watchdog 300 s; a smaller setting is raised to 300 s to absorb thinking pauses and proxy buffering |
| Longest healthy silence measured | gpt-6.1-sol, xhigh, 15–18k reasoning tokens over 5–6 min: 14 s between events with a reasoning summary, 20 s without one. 2 697 of 2 700 recorded Codex requests reached their first content within 101 s |

## Stopping a call

| Mechanism | Effect |
| --- | --- |
| Deadline | End to end; overrun bounded by one connect attempt. SSE waits are clamped to what remains. |
| `transport_exhausted` | `retry_stream` marks a spent budget; exec does not restart it, and keeps reason and retryable honest |
| `ExecInterrupt(BaseException)` | Passes every `except Exception` retry layer. Only the outermost owner raises it. |
| `OPENPROGRAM_EXEC_TIMEOUT_S` | Process default for `exec`; 0 is unbounded. Needs no signals, which Python delivers only to the main thread. |
| Stop while a reply streams | The turn ends without waiting for the provider to close: the read in flight is cancelled and handed to the turn's loop (`event_stream.leave_unwinding`). A bounded close that runs out of time is handed over the same way, still running: cancelling it would cancel the provider a second time and cut its socket close short. |
| The turn's loop closing | On a thread of its own, in `asyncio.run`'s order: the reads and closes a stop handed over get 2 s to end (a socket close is a round trip) and are cancelled after that, the provider clients close, the tasks the turn left are cancelled, async generators are shut down and the loop closes |
| Tasks that appear while it closes | The close of an abandoned stream generator, or a socket close a cancelled task left running, runs to its end. Async generators are shut down only once no task is left, repeated until nothing new appears. This has 1 s; what is still running then is cancelled and named in a warning. |
| Reply ended inside a block | Its final message holds the text and thinking as content blocks, not the adapter's working dict, at `stream._extract_final`. An unfinished tool call stays as the adapter left it. |

A benchmark runner with a sample budget subclasses `ExecInterrupt` for its watchdog, stops on authentication errors and scores by `LLMError.reason`.

**Not built: a hard limit on a synchronous `_call`**

Python cannot kill a thread: the caller would return while `_call` runs on until its socket fails, possibly writing model-call nodes or store state. The deadline, the idle bound and the SSE budgets already bound stalls. Subprocess isolation for benchmark samples is also not built.

## Classification

`classify_error` in `utils/failures/errors.py`:

| Order | Basis | Reason | Retryable |
| --- | --- | --- | --- |
| 1 | HTTP 429 | `RATE_LIMIT`; `AUTHORIZATION` if a spent quota | yes; no |
| 1 | HTTP 500, 502, 503, 504 | `PROVIDER_INTERNAL` | yes |
| 1 | HTTP 401, 402, 403 | `AUTHORIZATION` if the body says the credit is spent (`BILLING_MARKERS`); else `AUTHENTICATION`, `AUTHORIZATION` | no |
| 1 | HTTP 403 whose body is a web page, not the API's JSON: the network edge in front of the provider refused the caller's address. The message keeps the page's words, not its markup | `NETWORK_BLOCK` | no |
| 1 | HTTP 400 | `INVALID_REQUEST`, `CONTEXT_LENGTH`, `CONTENT_POLICY` | no |
| 2 | Transport exception type (`ConnectError`, `ReadTimeout`, ...); SDK `APIConnectionError`, `APITimeoutError`; anything caused by one | `TRANSPORT` | yes |
| 3 | Message substring | matching reason | by reason |
|  | No match | `UNKNOWN` | no |

`LLMError` carries `reason`, `retryable`, `http_status`, `retry_after_s`, `attempts`, `elapsed_s`, `had_image`, `provider`, `model`, `last_error_type`, `cause`. A deadline hit is `TIMEOUT`, never retryable. A spent budget of a retryable error stays retryable: retry with a new budget, not at once.

An exception with no verdict may show as `UNKNOWN`, non-retryable; `error_retryable_inferred` marks that, and only such messages keep Runtime's bounded fallback. An explicit verdict, known reason or spent transport budget is authoritative.

`error_kind` names a finer, stable category beside the reason, found on the exception or anything it wraps: a stalled stream and a reset connection are both `TRANSPORT`, only the first is `stream_idle`. The others are `stream_total`, `memory_unavailable`, `model_unavailable` and `auth`.

## Recovery allowances

| Allowance | Spent by | Size |
| --- | --- | --- |
| `limit` | Structured, length and repetitive-output repairs | 2 by default |
| `transport_limit` | `reserve("transport")` | stream retries minus the first attempt: 4 |

One `RecoveryState` per invocation. A dropped connection never spends a repair. A request that succeeds refunds its transport retries. An explicit limit of 0 disables both.

## Waiting for the network

| Aspect | Rule |
| --- | --- |
| Starts when | Transport retries are spent on failures that cannot reach the endpoint (`ConnectError`, `ConnectTimeout`, `ConnectionRefusedError`, DNS, or an SDK error caused by one) and nothing was committed |
| Does | Re-tries every 5, 10, 20, then 30 s, with a `retry` event of reason `network_wait`, shown as "Waiting for the network" |
| Success | Continues the turn, refunds the outage's retries |
| Other failure | Retryable: a fresh budget. Non-retryable: raised. |
| Ends | At `OPENPROGRAM_NETWORK_WAIT_MAX_S` (1800 s, 0 disables) or the deadline, flagged `transport_exhausted`; at once on cancel |
| Never for | 5xx, 429, committed output, a single-attempt policy, a recovery limit of 0 |
| Where | `retry_stream` (Codex), openai-completions. Anthropic relies on its SDK and does not wait. |

## DNS at the policy boundary

A `DNS_ERROR` from `socket.gaierror` is raised as `httpx.ConnectError`, so bounded transport recovery applies before anything is committed. Every attempt still resolves, validates and pins. Empty or malformed answers and denied origins stay policy failures. No DNS fallback, private-address exception or unbounded retry.

## Nested Codex authentication

Codex Runtime uses the provider's active account, as direct chat does; an explicit profile pins its own. `CredentialProvider` refresh is authoritative. Synchronous and asynchronous calls keep the terminal reason, verdict and Retry-After through `AgentSession`. A rejected OAuth token, or any explicit non-retryable failure, makes exactly one provider request.

[Fault-tolerance policy and comparison](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/reliability/llm-fault-tolerance.html)
