agent: retry transient API errors (429/5xx/529) with backoff #153

Closed
opened 2026-10-15 20:18:04 +00:00 by hermes · 0 comments
Collaborator

Problem

crates/hx-ai/src/anthropic.rs (~l.341) and codex.rs (~l.375) return Error::Api{status, body} on any non-2xx. Mid-stream failures surface as Error::Http. The only retry in agent.rs is a single retry on an empty reply. One 429/529/5xx therefore aborts a turn that may already carry a large context. Found by code reading; no measured failure rate yet.

Change

Wrap provider.stream() in Agent::run_inner:

  • retry on status 408, 429, 500, 502, 503, 529 and on connection errors before the first stream event
  • 3 attempts, backoff 1s/4s/16s, honour retry-after, cap total wait (~30s)
  • never retry after any stream event was emitted (the TUI would show duplicates)
  • emit Event::Info("retrying in Ns (status)")
  • abort must interrupt the wait

Effect

Fewer lost turns. No token change. Confidence in the benefit: medium (depends on how often overloads happen).

Risk

Retrying a 429 can burn subscription quota faster; the wait cap limits it.

Verify

Add a mode to tests/fake_anthropic.py that returns 529 once, then 200. Assert the turn completes and exactly 2 requests were made. Also assert a 400 is not retried.

## Problem `crates/hx-ai/src/anthropic.rs` (~l.341) and `codex.rs` (~l.375) return `Error::Api{status, body}` on any non-2xx. Mid-stream failures surface as `Error::Http`. The only retry in `agent.rs` is a single retry on an empty reply. One 429/529/5xx therefore aborts a turn that may already carry a large context. Found by code reading; no measured failure rate yet. ## Change Wrap `provider.stream()` in `Agent::run_inner`: - retry on status 408, 429, 500, 502, 503, 529 and on connection errors before the first stream event - 3 attempts, backoff 1s/4s/16s, honour `retry-after`, cap total wait (~30s) - never retry after any stream event was emitted (the TUI would show duplicates) - emit `Event::Info("retrying in Ns (status)")` - abort must interrupt the wait ## Effect Fewer lost turns. No token change. Confidence in the benefit: medium (depends on how often overloads happen). ## Risk Retrying a 429 can burn subscription quota faster; the wait cap limits it. ## Verify Add a mode to `tests/fake_anthropic.py` that returns 529 once, then 200. Assert the turn completes and exactly 2 requests were made. Also assert a 400 is not retried.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: johannes/hx#153