[Bug]: the retry loop retries failures that cannot change, so a bad key costs 11 attempts and up to 5 minutes

Author: sxh313Created Sep 28, 2026Updated Sep 28, 2026

What happened?

retry_with catches Exception and retries it — with no distinction between "this failed for a reason that repeating can change" and "this failed because the request is wrong". A rejected API key, a model that does not exist, a malformed request and a payload that is too large are all answered identically when asked again, so the loop spends every one of its attempts and all of its sleep time on an answer that was already final on attempt 1.

Measured against main @ e839e55, Python 3.12.13, openai==1.86.0, with a real OpenRouterClient pointed at a local ThreadingHTTPServer that always answers the same status (max_retries=2 here to keep the run short; trae_config.yaml.example:34 and :43 both ship 10). The count below is retries our decorator chose to make, read from its own Will sleep for notice — the SDK's internal retry policy is a separate thing in a separate library and is not counted:

main  @ e839e55 : HTTP 401 -> our loop retried 2 times in 35.4s, ends in AuthenticationError(status_code=401)
                : HTTP 404 -> our loop retried 2 times in 55.4s, ends in NotFoundError(status_code=404)
with the fix    : HTTP 401 -> our loop retried 0 times in  0.3s, ends in AuthenticationError(status_code=401)
                : HTTP 404 -> our loop retried 0 times in  0.4s, ends in NotFoundError(status_code=404)

The exception the user finally gets is identical on both sides — the status code was known on the first attempt and simply not consulted; only the 35 s and the 55 s of sleeping are extra.

The status is on the exception the whole time — AuthenticationError.status_code == 401, NotFoundError.status_code == 404 — and the loop never looks at it.

At the shipped max_retries: 10 that is 11 attempts and 10 sleeps of a random 3–30 s (retry_utils.py:34, :44, :50), i.e. 30–300 s of waiting to re-raise an error that was final immediately, and each round prints the failure plus a full traceback (retry_utils.py:46–48). The user sees minutes of OpenRouter API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided'}}. Will sleep for 20 seconds and will retry. for what is a one-line config typo.

Same defect, measured without a network, at the decorator level (max_retries=5): a stub raising a status-carrying 401 is called 6 times on main —

tests/utils/test_retry_utils.py::TestPermanentFailuresAreNotRetried::test_a_rejected_key_fails_on_the_first_attempt
    AssertionError: 6 != 1

What did you expect to happen?

A failure whose answer cannot change by asking again should raise on the first attempt. Three things make this a narrow change rather than a policy rewrite:

  • 429 and friends must keep retrying. A rate limit literally says "ask again later", and 408, 409 and 425 are client-side codes that are transient by construction, so they belong on the retrying side of the line even though they are 4xx.
  • 5xx and connection problems must keep retrying, unchanged. Nothing here touches the case the loop exists for.
  • Errors that carry no usable status keep retrying, unchanged. retry_with guards five call sites — openai_client.py:93, openai_compatible_base.py:142 (which serves OpenRouter, Azure and Doubao), anthropic_client.py:97, google_client.py:95 and ollama_client.py:103 — and I checked what each of them can actually raise rather than assuming. openai.APIStatusError('x', response=httpx.Response(401, ...), body=None).status_code is 401, and so are openai.AuthenticationError's and anthropic.APIStatusError's. openai.APIConnectionError carries no status at all. google.genai.errors.ClientError(401, ...) keeps the number on .code with .status_code absent, so google's behaviour does not change here. The ollama client raises ResponseError(e.response.text, e.response.status_code) for an HTTP failure (ollama/_client.py:124) and a bare ResponseError(err) — status -1 — otherwise, so an ollama 404 for a missing model does stop being retried while its non-HTTP problems (like #275's validation error) do not.

That is why the check has to be keyed on the status being present and an int in the client range, not on exception class names: it acts only where the provider has actually said which class of failure this is, and leaves every "I have no idea" case on today's behaviour.

Traceback

Not a crash — the failure is that a terminal error is treated as a transient one. The re-raised exception is correct; the 30–300 s and the 11 tracebacks spent getting there are not.

What is your system, Python, dependency version?

  • OS: Windows 11 (Windows-11-10.0.26200-SP0); the retry loop is pure stdlib time/random, so this is host-independent and reproduces on Linux unchanged
  • Python: 3.12.13 (repo venv from uv sync --all-extras); openai==1.86.0, anthropic==0.54.0, google-genai==1.24.0
  • Commit: e839e55 (main)

Additional information that you believe is relevant to this bug

This is the defect #499 deliberately left out. I filed and fixed the empty-key case in #497/#499, and wrote in #497: "I am deliberately not touching the retry loop here. retry_utils.py:37 catches bare Exception, so a permanent AuthenticationError (bad key) is retried exactly like a transient timeout — real, but a different change with its own blast radius, and I would rather file it separately than widen this one." PR #499's body lists the same item under "Not included, deliberately". This issue is that filing. The two are complementary and do not overlap: #499 catches a missing key at construction time, before any request; this one handles a key (or model, or request) that is present and refused at request time. #499 does not change any timing here, and this change does not make #499's message reachable any differently.

A user hit this and pasted the notice. #162 is a report of exactly this loop cycling on a permanent 401 — the key was valid but lacked a scope (Missing scopes: api.responses.write), which no number of retries can grant. The reporter's own words:

OpenAI API call failed: Error code: 401 - {'error': {'message': "You have insufficient permissions for this operation. Missing scopes: api.responses.write. …"}} will sleep for 12 seconds and will retry.

That thread's diagnosis was the key's permissions, which is not in dispute here; the point is that the loop's response to a 401 was to sleep and ask again, and that is what the user was left staring at. #275 is a different failure: an Ollama validation error carrying no HTTP status at all, so it stays retried under this proposal and is unaffected by it.

Duplicate checks. I enumerated the files of all 78 open PRs: none touches retry_utils.py. #179's title is the nearest-sounding report ("…after max retries: Error 1: 404 page not found"), but neither "after max retries" nor "Failed to get response" exists anywhere in trae_agent/ today, so that message is not this code path and I am not claiming it as an instance of this defect.

Why CI does not see it. Makefile:42 (make uv-test, which .github/workflows/unit-test.yml runs) sets SKIP_OLLAMA_TEST=true SKIP_OPENROUTER_TEST=true SKIP_GOOGLE_TEST=true, so 17 tests are skipped on every run, and on main no test asserts anything about how many times retry_with calls its function — the loop is entirely unmeasured there (grep -rn retry_with tests/ on main returns nothing).

Plan, if there is no objection: a is_permanent_failure(error) helper in retry_utils.py that returns True only for a status code that is 400 <= code < 500 and not in {408, 409, 425, 429}, plus a two-line early raise in the except block. Tests will assert attempt counts, not messages: permanent 4xx → 1 call and no sleep; 408/409/425/429 → still retried; 5xx → still retried; an error with no status attribute → still retried. time.sleep will be patched so nothing waits.

I will keep the retry count semantics otherwise untouched: no change to max_retries, no exponential backoff, no jitter policy, no new dependency. Backoff tuning is a separate conversation and I would not fold it in here.