fix(aux): retry, fallback and refresh decisions come from classify_api_error

The auxiliary client decided every recovery step (same-provider retry,
credential refresh, pool rotation, unhealthy mark, provider fallback)
with private substring predicates and consulted classify_api_error only
to label telemetry. The logged reason and the action taken could
disagree, plugin transform_api_error_classification hooks and
ProviderProfile.classify_api_error overrides never steered an aux
decision, and the tables had drifted from the main loop's.

What changed:
- Each failed request is classified once, on the backend, model,
  endpoint and credential it was sent with (_classify_failure): the
  primary, a same-provider retry (its rebuilt client and model), a
  refreshed Nous client or healed
  model, a parameter-rung or backoff re-send, and a fallback candidate
  (its effective provider or destination; an async candidate classifies
  on the sync client it was converted from). The streamed-negotiation
  and affordable-402 checks classify on the same attempted provider,
  passed in by the caller. Every later rung reads the
  resulting Failure (error, verdict, whether a parameter rung's detector
  names the rejected field). A request boundary that already classified
  (a rebuilt same-provider retry, a judged stream negotiation) raises the
  typed _ClassifiedAttempt carrying its Failure, and recovery reads that
  instead of classifying again. The relay logical call records each
  failed attempt with the ladder's Failure for it and reports that
  verdict at close (one classification only when no verdict exists):
  classifier hooks fire once per failed request.
- The primary's retries, the candidates' parameter rungs and the ladder
  driver handle a failure after its except block ends, so a retry's own
  failure is classified as itself instead of through the previous
  error's context. The stream watchdogs raise their timeout from None.
- agent/auxiliary_error_policy.py (new): small pure functions over the
  verdict (same_provider_retry, auth_refresh, same_key_retry,
  benches_provider, fallback_label, ladder_accepts,
  stream_negotiation_reraises).
- The sync and async fallback-candidate helpers share one generator.
- context_compressor classifies a summary failure once; its
  session-preserving abort keys on the verdict's transport fact.
- The parameter rungs return a _ParameterRepair NamedTuple whose
  repaired flag tells provider fallback a rung changed the request.
- Deleted: the private _is_*_error predicates, _credential_rung_accepts,
  _FALLBACK_REASONS, the keyword tables, fallback_candidate_unavailable_
  reason and agent/auxiliary_error_shapes.py.

Behaviour changes:
- Transient failures (5xx, 408, overload, timeouts, connection failures
  incl. DNS/ECONNREFUSED and SDK transport classes) retry the same
  provider, then fall back.
- A missing model falls back on every route; a 404 free-tier body falls
  back; 400-coded billing and rate-limit bodies bench / rotate and fall
  back.
- RESOURCE_EXHAUSTED on a 429 is a rate limit unless it names a daily or
  weekly window, which is billing and benches the provider.
- An OpenRouter-wrapped upstream 429 and a 429 "overloaded" do not rotate
  a healthy key; a 429 naming a rate limit and a billing phrase stays a
  rate limit.
- A generic 403 falls back (auto routes; an explicit provider only with
  its task fallback_chain) without a credential refresh.
- Account gating of the model rotates (model-scoped) before falling back;
  a feature restriction falls back without touching the key.
- A rejection naming a request parameter with no applicable rung
  re-raises (primary and candidates); after a spent rung it falls back.
- A verdict with retryable=False skips the same-provider retry and the
  same-key rate-limit backoff; a plugin or profile verdict with
  should_fallback=False never reaches provider fallback. A verdict that
  is neither retryable nor should_fallback (data_policy_denied, the
  model's malformed tool-call arguments) re-raises even after a
  parameter rung changed the request: another provider would get the
  same content.
- An InterruptedError (a cancelled Codex stream) stops the call: no
  retry, no fallback.
- A missing or route-refused model on a fallback candidate quarantines
  that model only (model-scoped unhealthy key); siblings on the same
  provider stay eligible. The key holds the provider-normalized model,
  so a configured name and its resolved form (gpt-x / openai/gpt-x)
  match, and the discovery chain skips a hidden resolved model too.
- Aux pool selection (_select_pool_entry, _peek_pool_entry and the
  OpenRouter, Codex, Anthropic, xAI OAuth, plugin OAuth, named custom
  and API-key builders) passes the requested model, so a model-scoped cooldown on a key does not hide
  it from sibling models; CredentialPool.peek takes model= like
  select.
- 429 then a generic 403 on an explicit provider with no task chain
  re-raises the 403.
- Plugin and provider-profile classifiers steer every aux decision.

Tests: tests/agent/test_auxiliary_error_policy.py drives call_llm end to
end over one table of the behaviour decisions, plus regressions for a
failure after a 401 refresh, 429-then-403, retryable=False, OpenCode Go
classification (sync and async), a refreshed candidate's bad answer, a
Nous SSE error after refresh, a terminal verdict after a spent
parameter rung, one hook call per failed request (primary, retry and
candidate; streamed and plain, sync and async), TLS failure and a 502 connection reset in
compression, plugin overrides, an interrupt, a pinned custom provider's
model-scoped rotation, a candidate's model-scoped quarantine under its
resolved name, a sibling model keeping a pooled key, and a rebuilt
retry classified on its own model. Tests of
the removed predicates are deleted; ladder-internals tests are adapted
to the Failure tuple.

Part of the Code Health plan.
This commit is contained in:
kshitijk4poor
2026-11-04 00:22:13 +05:30
committed by kshitij
parent 3425329bc7
commit 49165bcaff
21 changed files with 945 additions and 858 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
"""What the auxiliary recovery ladder does with a failed request, read from ``classify_api_error``'s verdict.
The labels :func:`fallback_label` returns are the ones the logs, unhealthy marks and candidate quarantine
TTLs (agent/auxiliary_health.py) key on.
"""
from __future__ import annotations
from typing import Any, NamedTuple, Optional
import httpx
from agent.error_classifier import ClassifiedError, FailoverReason, classify_api_error
_R = FailoverReason
AUTH_ERROR, PAYMENT_ERROR, MODEL_INCOMPATIBLE = "auth error", "payment error", "model incompatible with route"
_TRANSIENT = frozenset({_R.timeout, _R.overloaded, _R.server_error})
# The request's own shape failed: another provider only helps once a parameter rung changed the request.
_REQUEST_SHAPE = frozenset({
_R.format_error, _R.role_alternation, _R.multimodal_tool_content_unsupported, _R.reasoning_mandatory,
_R.llama_cpp_grammar_pattern, _R.image_too_large, _R.image_corrupt, _R.invalid_encrypted_content,
_R.thinking_signature, _R.context_overflow, _R.payload_too_large,
_R.oauth_long_context_beta_forbidden,
})
_LABELS = {
_R.auth: AUTH_ERROR, _R.auth_permanent: AUTH_ERROR, _R.billing: PAYMENT_ERROR,
_R.rate_limit: "rate limit", _R.upstream_rate_limit: "rate limit", _R.model_not_found: "model not found",
_R.model_entitlement: MODEL_INCOMPATIBLE, _R.incomplete_response: "invalid provider response",
_R.overloaded: "provider overloaded", _R.server_error: "server error", _R.long_context_tier: "long context tier",
}
_PROVIDER_REFUSALS = _TRANSIENT | {_R.auth, _R.auth_permanent, _R.billing, _R.rate_limit, _R.upstream_rate_limit}
class Failure(NamedTuple):
"""A failed request, its verdict, and whether a parameter rung's detector names the rejected field."""
error: Exception
verdict: ClassifiedError
rejects_parameter: bool = False
def classify_attempt(error: Exception, provider: Optional[str], client: Any = None, model: Any = None,
base_url: Optional[str] = "") -> ClassifiedError:
"""``classify_api_error`` on the backend, model, endpoint and credential ``client`` was sent to."""
slug = str(provider or "").strip().lower()
url, key = getattr(client, "base_url", None), getattr(client, "api_key", None)
if isinstance(error, InterruptedError): # a cancelled task: no retry, no other provider
return ClassifiedError(_R.unknown, provider=slug, retryable=False, message=str(error))
return classify_api_error(
error, provider="" if slug == "auto" else slug, model=model if isinstance(model, str) else "",
base_url=str(url) if isinstance(url, (str, httpx.URL)) and str(url) else str(base_url or ""),
api_key=key if isinstance(key, str) else None)
def same_provider_retry(verdict: ClassifiedError) -> bool:
return verdict.reason in _TRANSIENT and verdict.retryable
def auth_refresh(verdict: ClassifiedError) -> bool:
return verdict.reason is _R.auth and verdict.should_rotate_credential
def same_key_retry(verdict: ClassifiedError) -> bool:
return verdict.reason is _R.rate_limit and verdict.retryable and not verdict.error_context.get("quota_exhausted")
def benches_provider(verdict: ClassifiedError) -> bool:
return verdict.reason is _R.billing or bool(verdict.error_context.get("quota_exhausted"))
def fallback_label(failure: Failure, *, rung_spent: bool = False) -> Optional[str]:
"""Why another provider should take this request, or None when the failure would follow it anywhere.
``rung_spent``: a parameter rung already changed the request and it still failed."""
verdict = failure.verdict
reason, context = verdict.reason, verdict.error_context
structured = "structured provider error" if context.get("statusless_structured") else None
if context.get("hook_declines_fallback"):
return None
if benches_provider(verdict):
return PAYMENT_ERROR
if reason is _R.timeout:
return "connection error" if context.get("transport") == "connection" else "request timed out"
if reason in _LABELS:
return _LABELS[reason]
if not (verdict.retryable or verdict.should_fallback): # terminal: every provider would get the same request
return None
if failure.rejects_parameter or reason in _REQUEST_SHAPE and not context.get("route_rejects_model"):
if rung_spent:
return MODEL_INCOMPATIBLE
return None if failure.rejects_parameter else structured
if context.get("route_rejects_model"):
return MODEL_INCOMPATIBLE
return reason.value.replace("_", " ") if verdict.should_fallback else structured
def ladder_accepts(failure: Failure, *, rung_spent: bool = False) -> bool:
"""A later rung (credential rotation, provider fallback) acts on this failure; else it re-raises."""
return failure.verdict.should_rotate_credential or fallback_label(failure, rung_spent=rung_spent) is not None
def stream_negotiation_reraises(verdict: ClassifiedError) -> bool:
"""A failed stream negotiation that is the provider's answer: re-raised, not re-sent non-streaming."""
return (verdict.reason in _PROVIDER_REFUSALS or verdict.status_code == 429 or benches_provider(verdict)
or "welcome_refusal" in verdict.error_context)

View File

@@ -1,54 +0,0 @@
"""Shape readers for auxiliary-call errors: where an SDK error carries its HTTP status, and the
status-less failures (HTTP-200 malformed answers, SSE ``error`` events) that still end a route.
botocore's ``ClientError`` keeps its status in ``response["ResponseMetadata"]`` rather than on an
attribute; the Bedrock client makes one attempt per call, so the auxiliary recovery ladder has to
read it there to retry a 503 or treat a ``ThrottlingException`` as a rate limit.
"""
from __future__ import annotations
from typing import Any
def _botocore_error(exc: Exception) -> tuple[Any, Any]:
"""``(HTTP status, error code)`` of a botocore ``ClientError``, whose ``response`` is the parsed
dict; ``(None, None)`` for any other exception. The Bedrock client makes one attempt per call,
so these classifiers own its retries the way they own the OpenAI SDK's (``max_retries=0``)."""
response = getattr(exc, "response", None)
if not isinstance(response, dict):
return None, None
return response.get("ResponseMetadata", {}).get("HTTPStatusCode"), response.get("Error", {}).get("Code")
def _exc_http_status(exc: Exception) -> Any:
"""HTTP status on the exception itself, its ``response``, or a botocore error's response metadata."""
return (getattr(exc, "status_code", None) or getattr(getattr(exc, "response", None), "status_code", None)
or _botocore_error(exc)[0])
def _is_invalid_aux_response_error(exc: Exception) -> bool:
"""HTTP-200 empty/malformed ChatCompletions — a capability failure routed like model incompatibility."""
if not isinstance(exc, RuntimeError):
return False
msg = str(exc).lower()
return "auxiliary " in msg and "llm returned invalid response" in msg and "choices[0].message" in msg
def _is_statusless_structured_provider_error(exc: Exception) -> bool:
"""Detect a structured provider failure that has no HTTP status.
OpenAI-compatible relays may commit SSE with status 200, then send an
OpenAI-style ``error`` event. The SDK raises a status-less ``APIError`` with
``body=data["error"]`` — the INNER error object or a bare string (an
``{"error": ...}`` wrapper is accepted too). Any non-empty structured error in
that status-less shape is a route failure; ordinary HTTP errors keep their
existing status-based classifiers, and message text alone is insufficient.
"""
if _exc_http_status(exc) is not None:
return False
body = getattr(exc, "body", None)
err = body.get("error") if isinstance(body, dict) and "error" in body else body
if isinstance(err, str):
return bool(err.strip())
return isinstance(err, dict) and any(err.get(k) for k in ("type", "code", "message"))

View File

@@ -10,41 +10,43 @@ from typing import Any, Awaitable, Callable, Dict, Optional
def _parameter_ladder(first_err: Exception, client: Any, kwargs: dict[str, Any], *,
task: Optional[str], tag: str):
from agent.auxiliary_client import _LadderRoute, _ladder_parameter_rungs
task: Optional[str], tag: str, provider: str, base_url: str):
"""Returns ``(response, None, False)`` or ``(None, failure, rung_spent)``."""
from agent.auxiliary_client import _failure, _LadderRoute, _ladder_parameter_rungs
# Keyword construction: the route tuple grows with every new ladder rung (a positional 13-tuple
# broke the moment a sibling PR added ``timeout``); fields this ladder never reads stay None.
route = _LadderRoute(**{**dict.fromkeys(_LadderRoute._fields), "client": client, "task": task,
"tag": tag, "async_mode": bool(tag), "resolved_provider": "",
"base_info": str(getattr(client, "base_url", "") or "")})
"tag": tag, "async_mode": bool(tag), "resolved_provider": provider,
"final_model": kwargs.get("model"),
"base_info": base_url or str(getattr(client, "base_url", "") or "")})
max_tokens = kwargs.get("max_tokens") or kwargs.get("max_completion_tokens")
resp, err, _ = yield from _ladder_parameter_rungs(first_err, route, kwargs, max_tokens)
if err is None:
return resp
raise err
repair = yield from _ladder_parameter_rungs(_failure(route, first_err), route, kwargs, max_tokens)
return repair.response, repair.failure, repair.repaired
def send_with_parameter_rungs(
send: Callable[[Any, dict[str, Any]], Any], client: Any, kwargs: dict[str, Any], *, task: Optional[str],
provider: str = "", base_url: str = "",
) -> Any:
"""``send(client, kwargs)``; on a parameter 400, retry through the parameter rungs. Any other
error (auth, payment, connection) propagates unchanged for the caller's own handling."""
from agent.auxiliary_client import _drive_ladder
try:
return send(client, kwargs)
except Exception as first_err:
ladder = _parameter_ladder(first_err, client, kwargs, task=task, tag="")
return _drive_ladder(ladder, lambda step: send(*step.args))
"""``send(client, kwargs)``; on a parameter 400, retry through the parameter rungs. Returns
``(response, None, False)`` or ``(None, failure, rung_spent)`` for the caller's own handling."""
from agent.auxiliary_client import _drive_ladder, _outcome
resp, first_err = _outcome(send, client, kwargs)
if first_err is None:
return resp, None, False
ladder = _parameter_ladder(first_err, client, kwargs, task=task, tag="", provider=provider, base_url=base_url)
return _drive_ladder(ladder, lambda step: send(*step.args))
async def send_with_parameter_rungs_async(
send: Callable[[Any, dict[str, Any]], Awaitable[Any]], client: Any, kwargs: dict[str, Any], *,
task: Optional[str],
task: Optional[str], provider: str = "", base_url: str = "",
) -> Any:
"""Async twin of :func:`send_with_parameter_rungs`."""
from agent.auxiliary_client import _drive_ladder_async
try:
return await send(client, kwargs)
except Exception as first_err:
ladder = _parameter_ladder(first_err, client, kwargs, task=task, tag=" (async)")
return await _drive_ladder_async(ladder, lambda step: send(*step.args))
from agent.auxiliary_client import _aoutcome, _drive_ladder_async
resp, first_err = await _aoutcome(send(client, kwargs))
if first_err is None:
return resp, None, False
ladder = _parameter_ladder(first_err, client, kwargs, task=task, tag=" (async)", provider=provider,
base_url=base_url)
return await _drive_ladder_async(ladder, lambda step: send(*step.args))

View File

@@ -4,18 +4,17 @@ from typing import Any, Optional
from hermes_cli.route_identity import normalize_route_base_url
def _unhealthy_cache_key(provider: str, base_url: Optional[str] = None) -> Any:
def _unhealthy_cache_key(provider: str, base_url: Optional[str] = None, model: Optional[str] = None) -> Any:
"""Provider-wide key, or endpoint-specific key for an explicit custom endpoint — prefixed with the
active profile home: a 402 on profile A's account must not hide the provider from profile B's
(differently funded) account in the same multiplexed process."""
from agent.auxiliary_client import _normalize_chain_label
from agent.auxiliary_client import _normalize_chain_label, _normalize_resolved_model
from hermes_constants import hermes_home_key
label = _normalize_chain_label(provider)
endpoint = normalize_route_base_url(_custom_health_base_url(provider, base_url))
home_key = hermes_home_key()
if endpoint:
return home_key, "custom-endpoint", endpoint
return home_key, label
key = (hermes_home_key(), "custom-endpoint", endpoint) if endpoint else (hermes_home_key(), label)
model = _normalize_resolved_model(model, provider) # configured ``gpt-x`` and wire ``openai/gpt-x`` share a key
return (*key, model.strip().lower()) if model and model.strip() else key
def _custom_health_base_url(provider: str, explicit_base_url: Optional[str] = None) -> str:
@@ -40,21 +39,6 @@ def _custom_health_base_url(provider: str, explicit_base_url: Optional[str] = No
def fallback_candidate_unavailable_reason(exc: Exception) -> Optional[str]:
"""Why a fallback candidate cannot serve this walk (``_FALLBACK_REASONS`` label), or None.
The same capacity classes that admitted the primary failure into the chain (payment/quota,
rate limit, connection, route-incompatible model, malformed response) mean "this lane is out
for now, try the next configured one"; anything else (a 400 request-shape error, a ValueError)
is the caller's bug and must still propagate. Auth errors are excluded on purpose: they have
their own refresh-then-quarantine path in the candidate helpers (#106367)."""
from agent.auxiliary_client import _FALLBACK_REASONS
return next(
(label for predicate, label in _FALLBACK_REASONS if label != "auth error" and predicate(exc)),
None,
)
# Quarantine hold per unavailable-reason label. Payment/quota depletion and a dead credential
# last hours, so those keep the long default TTL (None); a per-minute 429, a dropped connection or
# a garbled body clears in seconds — holding the lane for 10 minutes process-wide would hide a
@@ -64,10 +48,12 @@ _CANDIDATE_QUARANTINE_TTL: dict[str, Optional[float]] = {
"rate limit": _TRANSIENT_CANDIDATE_QUARANTINE_SECONDS,
"connection error": _TRANSIENT_CANDIDATE_QUARANTINE_SECONDS,
"invalid provider response": _TRANSIENT_CANDIDATE_QUARANTINE_SECONDS,
"provider overloaded": _TRANSIENT_CANDIDATE_QUARANTINE_SECONDS,
"server error": _TRANSIENT_CANDIDATE_QUARANTINE_SECONDS,
}
def fallback_candidate_quarantine_ttl(reason: Optional[str]) -> Optional[float]:
"""Seconds to hide a fallback candidate for ``reason`` (a ``_FALLBACK_REASONS`` label, or None
"""Seconds to hide a fallback candidate for ``reason`` (a ``fallback_label`` label, or None
for a stale credential); None means the long default TTL."""
return _CANDIDATE_QUARANTINE_TTL.get(reason or "")

View File

@@ -31,7 +31,7 @@ def resolve_plugin_oauth_client(req: Any) -> tuple[Any, Any]:
api_key = aux._normalize_api_key(req.explicit_api_key)
entry = None
if not api_key:
_exists, entry = aux._select_pool_entry(provider)
_exists, entry = aux._select_pool_entry(provider, req.model)
api_key = str(getattr(entry, "runtime_api_key", "") or "") if entry is not None else ""
base_url = (req.explicit_base_url or str(getattr(entry, "runtime_base_url", "") or "")
or _configured_endpoint(provider)).strip().rstrip("/")

View File

@@ -46,26 +46,25 @@ def rate_limit_wait(exc: Exception, attempt: int) -> Optional[float]:
attempt, base_delay=RATE_LIMIT_BACKOFF_BASE, max_delay=RATE_LIMIT_BACKOFF_CAP)
def rate_limit_retry_rungs(first_err: Exception, client: Any, kwargs: dict[str, Any], label: str):
"""Ladder rungs: wait, then re-send on the same client, up to ``RATE_LIMIT_RETRIES`` times while
the refusal stays a rate limit. Returns ``(response, None)`` or ``(None, last_err)``."""
from agent.auxiliary_client import (
_LadderStep, _credential_rung_accepts, _is_payment_error, _is_rate_limit_error, _rung,
)
def rate_limit_retry_rungs(failure: Any, route: Any, kwargs: dict[str, Any]):
"""Ladder rungs: wait, then re-send on the route's client, up to ``RATE_LIMIT_RETRIES`` times while
the refusal stays a per-key rate limit. Returns ``(response, None)`` or ``(None, last_failure)``."""
from agent import auxiliary_error_policy as aux_errors
from agent.auxiliary_client import _LadderStep, _rung
err = first_err
label = f"{route.task or 'call'}{route.tag}"
for attempt in range(1, RATE_LIMIT_RETRIES + 1):
wait = rate_limit_wait(err, attempt)
wait = rate_limit_wait(failure.error, attempt)
if wait is None:
logger.info("Auxiliary %s: provider asked for a %.0fs cooldown; not waiting it out",
label, rate_limit_retry_after(err) or 0.0)
label, rate_limit_retry_after(failure.error) or 0.0)
break
logger.info("Auxiliary %s: rate limited (attempt %d/%d); retrying after %.2fs",
label, attempt, RATE_LIMIT_RETRIES, wait)
yield _LadderStep("wait", (wait,))
resp, err = yield from _rung(_LadderStep("call", (client, kwargs)), _credential_rung_accepts)
if err is None:
resp, failure = yield from _rung(_LadderStep("call", (route.client, kwargs)), aux_errors.ladder_accepts, route)
if failure is None:
return resp, None
if not _is_rate_limit_error(err) or _is_payment_error(err):
if not aux_errors.same_key_retry(failure.verdict):
break
return None, err
return None, failure

View File

@@ -171,11 +171,11 @@ def consume_chat_stream(chunks: Any, acc: Any, no_progress: Optional[tuple[float
for chunk in chunks:
if acc.feed(chunk):
watchdog.progress()
except Exception as exc:
except Exception:
if not watchdog.fired:
raise
if not acc.finish_reason:
raise watchdog.timeout_error() from exc
raise watchdog.timeout_error() from None # the deadline is the verdict
finally:
watchdog.finish()
if watchdog.fired and not acc.finish_reason:

View File

@@ -24,7 +24,6 @@ from agent.auxiliary_client import (
CODEX_STREAM_STALL_MARKER,
AuxiliaryExplicitCancellation,
_coerce_llm_message,
_is_connection_error,
_message_field,
aux_interrupt_protection,
call_llm,
@@ -42,7 +41,7 @@ from agent.context_compressor_tail import (
elide_keeping_skill_safety_rule, with_skill_safety_rule, without_skill_safety_rule, tail_cut_progress_floor,
)
from agent.context_compressor_telemetry import CompressionTelemetryMixin
from agent.error_classifier import FailoverReason, classify_api_error
from agent.error_classifier import ClassifiedError, FailoverReason, classify_api_error
from agent.micro_compaction import MicroCompactionMixin
from agent.prompt_builder import STEER_DISPLAY_KIND
from agent.model_metadata import (
@@ -220,7 +219,7 @@ def _is_refusal_response(response: Any, content: str) -> bool:
return bool(_response_refusal_text(response)) or _is_summary_refusal(content)
def _is_summary_access_or_quota_error(exc: Exception) -> bool:
def _is_summary_access_or_quota_error(exc: Exception, verdict: Optional[ClassifiedError] = None) -> bool:
"""Return True for non-retryable summary auth, permission, or quota errors."""
# No active secret scope is a missing-credential failure of our own making;
@@ -236,7 +235,7 @@ def _is_summary_access_or_quota_error(exc: Exception) -> bool:
UnscopedSecretError = () # type: ignore[assignment]
if UnscopedSecretError and isinstance(exc, UnscopedSecretError):
return True
reason = classify_api_error(exc).reason
reason = (verdict or classify_api_error(exc)).reason
if reason is FailoverReason.rate_limit:
return False
if reason in {FailoverReason.auth, FailoverReason.auth_permanent}:
@@ -717,7 +716,7 @@ class _SummaryFailureKind:
return next((reason for flagged, reason in reasons if flagged), "failed")
def _classify_summary_failure(e: Exception) -> _SummaryFailureKind:
def _classify_summary_failure(e: Exception, verdict: ClassifiedError) -> _SummaryFailureKind:
"""Classify a summary-call exception by status code / message shape.
A "refusal content" RuntimeError (prose or provider ``refusal`` field) deliberately rides the
@@ -738,8 +737,8 @@ def _classify_summary_failure(e: Exception) -> _SummaryFailureKind:
# Malformed/non-JSON bodies (HTML 502 as application/json) surface as JSONDecodeError or
# APIResponseValidationError "expecting value"; treat as transient.
json_decode=isinstance(e, json.JSONDecodeError) or "expecting value" in err,
# httpx premature-close errors are transient; treat like a timeout, not a 60s cooldown.
streaming_closed=_is_connection_error(e) and not stall,
# Premature-close / dead-network errors (a TLS certificate failure too): short cooldown, then abort.
streaming_closed=(verdict.reason is FailoverReason.ssl_cert_verification or bool(verdict.error_context.get("transport"))) and not stall,
# HTTP 200 with empty body from a degraded provider, the sibling "no usable response" shapes from
# _validate_llm_response, and Gemini's prompt block of the summary request (once empty content).
empty_content=getattr(e, "code", None) == "gemini_prompt_blocked" or (isinstance(e, RuntimeError) and any(
@@ -749,7 +748,7 @@ def _classify_summary_failure(e: Exception) -> _SummaryFailureKind:
)),
# Truncated summary: one main-model retry, then ABORT preserving the session.
truncated=isinstance(e, RuntimeError) and _TRUNCATED_SUMMARY_MARKER in err,
overloaded=classify_api_error(e).reason is FailoverReason.overloaded
overloaded=verdict.reason is FailoverReason.overloaded
or any(marker in err for marker in ("overloaded", "at capacity", "over capacity")),
)
@@ -4103,8 +4102,9 @@ Write only the summary body. Do not include any preamble or prefix."""
_SUMMARY_FAILURE_COOLDOWN_SECONDS,
)
return None
kind = _classify_summary_failure(e)
access_error = _is_summary_access_or_quota_error(e)
verdict = classify_api_error(e)
kind = _classify_summary_failure(e, verdict)
access_error = _is_summary_access_or_quota_error(e, verdict)
# Auth/permission/quota failures are not retryable: flag so compress() preserves the
# session. A distinct summary_model still gets the one-shot main-model fallback.
if access_error:

View File

@@ -2160,12 +2160,12 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
self._current_id = entry.id
return entry, pending_refresh
def peek(self) -> Optional[PooledCredential]:
def peek(self, *, model: Optional[str] = None) -> Optional[PooledCredential]:
with self._lock:
current = self._current_unlocked()
if current is not None:
return current
available, _pending = self._available_entries()
available, _pending = self._available_entries(model=model)
return available[0] if available else None
def reclaim(self, credential_id: str, *, model: Optional[str] = None) -> Optional[PooledCredential]:

View File

@@ -167,7 +167,7 @@ for mode, status in [("sync", 402), ("async", 402), ("sync", 429)]:
error = {
"type": type(exc).__name__,
"status": getattr(exc, "status_code", None),
"payment": aux._is_payment_error(exc),
"payment": aux.aux_errors.benches_provider(aux.aux_errors.classify_attempt(exc, "")),
}
failure_requests = requests[start:]
cache = {

View File

@@ -45,3 +45,20 @@ def _fast_retry_backoff(request, monkeypatch):
# server-error retries don't burn real wall-clock seconds.
from agent import retry_utils as _retry_utils
monkeypatch.setattr(_retry_utils, "jittered_backoff", lambda *a, **k: 0.0)
def sdk_status_error(status: int, message: str, *, wrapped: bool = False, **error_fields):
"""An error shaped like openai-python's ``_make_status_error`` output (``wrapped``: a relay that keeps
the ``{"error": ...}`` envelope on the exception body). Shared by the aux error-policy tests."""
import httpx
import openai
body = {"message": message, **error_fields}
if wrapped:
body = {"error": body}
by_status = {400: openai.BadRequestError, 401: openai.AuthenticationError, 403: openai.PermissionDeniedError,
404: openai.NotFoundError, 429: openai.RateLimitError}
cls = by_status.get(status, openai.InternalServerError if status >= 500 else openai.APIStatusError)
request = httpx.Request("POST", "https://openrouter.ai/api/v1/chat/completions")
return cls(f"Error code: {status} - {{'error': {body!r}}}", response=httpx.Response(status, request=request),
body=body)

View File

@@ -54,7 +54,8 @@ def test_auxiliary_owned_refresh_does_not_spend_borrowed_rotation(tmp_path, monk
route = SimpleNamespace(client=SimpleNamespace(api_key="owned-token"), task="compression", tag="",
resolved_provider="anthropic", base_info="https://api.anthropic.com", resolved_model="fixture",
final_model="fixture", main_runtime=None)
retry = aux._ladder_credential_rungs(error, route, {}, False)
failure = aux.aux_errors.Failure(error, aux.aux_errors.classify_attempt(error, "anthropic"))
retry = aux._ladder_credential_rungs(failure, route, {}, False)
assert next(retry).kind == "retry_same_provider"
retry.close()
assert borrowed.read_bytes() == before

View File

@@ -355,7 +355,7 @@ class TestAggregateChatStream:
"""#100501: an endpoint that sends one chunk then goes silent fails at the task's no-progress
window as a timeout (so retry/fallback run), not at the request read timeout. Recovery rungs
go through the default relay callback and must keep the task's window."""
from agent.auxiliary_client import _should_skip_same_provider_retry
from agent.auxiliary_client import _classify_failure, _should_skip_same_provider_retry
_gates, call = sse
started = time.monotonic()
@@ -363,7 +363,8 @@ class TestAggregateChatStream:
call("m", "compression", via_relay_seam=via_relay_seam)
assert time.monotonic() - started < 5.0
assert "stalled: no new output for 0.4s" in str(excinfo.value)
assert _should_skip_same_provider_retry("compression", excinfo.value)
assert _should_skip_same_provider_retry(
"compression", _classify_failure(excinfo.value, "", None, None, None))
@pytest.mark.parametrize("case", ["reasoning_before_first_token", "provider_stale_timeout_before_first_token",
"stall_after_terminal_usage", "late_timer_after_pool_reuse"])

View File

@@ -3,7 +3,7 @@
Both auth-refresh rungs in ``agent/auxiliary_client.py`` perform their retry with a
bare ``yield`` inside a ``return`` statement:
if _is_auth_error(first_err) and client_is_nous:
if aux_errors.auth_refresh(failure.verdict) and client_is_nous:
step = _refreshed_nous_step(...)
if step is not None:
return (yield step), None # nous rung
@@ -13,8 +13,7 @@ bare ``yield`` inside a ``return`` statement:
``_rung()`` exists to convert a retry failure into ``(None, exc)`` -- but only when the
rung's accept predicate claims the error -- so the caller can fall through to the next
rung. An unclaimed failure (a 500, a malformed response) re-raises on purpose, since
``_ladder_provider_fallback`` only acts on the reasons in ``_FALLBACK_REASONS``.
rung. A failure no later rung acts on (``aux_errors.ladder_accepts``) re-raises on purpose.
Used this way no exception is caught: when the
refreshed client also fails (e.g. an out-of-credit 404 on a stale Nous runtime token),
the error escapes ``_aux_recovery_ladder`` and ``_ladder_provider_fallback`` never
@@ -99,9 +98,9 @@ def hermetic(monkeypatch):
"""Keep the ladder off the network and record the provider-fallback rung."""
chain_calls = []
def _fake_provider_fallback(first_err, route):
def _fake_provider_fallback(failure, route, **_kw):
"""Stands in for the last rung: a generator that performs no steps."""
chain_calls.append(first_err)
chain_calls.append(failure.error)
yield from ()
return "chain-response"
@@ -389,8 +388,8 @@ def test_exhausted_ladder_raises_the_narrowed_error(monkeypatch, hermetic):
monkeypatch.setattr(aux, "_refresh_nous_auxiliary_client",
lambda **kwargs: (_FakeClient(), AUX_MODEL))
def _no_chain(first_err, route):
hermetic.append(first_err)
def _no_chain(failure, route, **_kw):
hermetic.append(failure.error)
yield from ()
monkeypatch.setattr(aux, "_ladder_provider_fallback", _no_chain)

View File

@@ -21,11 +21,6 @@ from agent.auxiliary_client import (
async_call_llm,
_build_call_kwargs,
_resolve_codex_credential_and_base,
_is_payment_error,
_is_rate_limit_error,
_is_model_not_found_error,
_is_model_incompatible_error,
_is_statusless_structured_provider_error,
_refresh_nous_recommended_model,
_normalize_aux_provider,
_try_payment_fallback,
@@ -1356,118 +1351,6 @@ class TestAuxiliaryPoolAwareness:
# ── Payment / credit exhaustion fallback ─────────────────────────────────
class TestIsPaymentError:
"""_is_payment_error detects 402 and credit-related errors."""
def test_402_status_code(self):
exc = Exception("Payment Required")
exc.status_code = 402
assert _is_payment_error(exc) is True
@pytest.mark.parametrize("spelling", ["RESOURCE_EXHAUSTED", "ResourceExhausted", "resource-exhausted"])
@pytest.mark.parametrize("status", [None, 429])
def test_resource_exhausted_separator_variants_are_payment(self, spelling, status):
"""NIM / gRPC wrappers serialize the quota signal without the space; the fallback gate
must read every spelling like the literal ``resource exhausted`` (#85649)."""
exc = Exception(f"{spelling}: Worker local total request limit reached (32/32)")
if status is not None:
exc.status_code = status
assert _is_payment_error(exc) is True
def test_403_subscription_required_is_payment(self):
exc = Exception(
"this model requires a subscription, upgrade for access: "
"https://ollama.com/upgrade"
)
exc.status_code = 403
assert _is_payment_error(exc) is True
def test_404_generic_not_found_is_not_payment(self):
exc = Exception("Not Found")
exc.status_code = 404
assert _is_payment_error(exc) is False
# ── Daily / monthly quota exhaustion (#26803) ────────────────────────────
class TestIsModelNotFoundError:
"""_is_model_not_found_error detects stale/invalid model 404s, distinct
from payment errors."""
def test_nous_openrouter_catalog_404(self):
"""The exact incident error: a Portal-recommended model dropped from
the Nous → OpenRouter catalog."""
exc = Exception(
"Model 'gpt-5.4-mini' not found. The requested model does not "
"exist in our configuration or OpenRouter catalog."
)
exc.status_code = 404
assert _is_model_not_found_error(exc) is True
def test_billing_404_is_not_model_not_found(self):
"""Free-tier / credit 404s belong to _is_payment_error, not here —
the two predicates must not overlap."""
exc = Exception(
"Model 'gpt-5' is not available on the free tier. Upgrade."
)
exc.status_code = 404
assert _is_model_not_found_error(exc) is False
assert _is_payment_error(exc) is True
def test_out_of_funds_404_is_not_model_not_found(self):
exc = Exception(
"Your API key is blocked or out of funds. model_not_found"
)
exc.status_code = 404
# billing keyword wins — payment owns it
assert _is_model_not_found_error(exc) is False
class TestIsModelIncompatibleError:
"""_is_model_incompatible_error detects 400s where the route cannot run
the model at all (capability mismatch), distinct from not-found and
payment errors."""
def test_codex_chatgpt_account_model_gating(self):
"""The exact incident: an openai-codex/ChatGPT-account fallback asked
to compress a glm-5.2 conversation."""
exc = Exception(
"Error code: 400 - {'detail': \"The 'glm-5.2' model is not "
"supported when using Codex with a ChatGPT account.\"}"
)
exc.status_code = 400
assert _is_model_incompatible_error(exc) is True
def test_not_found_is_not_incompatible(self):
"""A model-does-not-exist 400 belongs to _is_model_not_found_error —
the two predicates must not overlap."""
exc = Exception("openrouter/foo/bar is not a valid model ID")
exc.status_code = 400
assert _is_model_incompatible_error(exc) is False
assert _is_model_not_found_error(exc) is True
def test_payment_400_is_not_incompatible(self):
"""A billing 400 that also contains capability-ish phrasing must be
rejected here — billing keywords win so the payment path owns it and
the two buckets don't overlap."""
exc = Exception("insufficient credits: model is not supported on free tier")
exc.status_code = 400
assert _is_model_incompatible_error(exc) is False
class TestRefreshNousRecommendedModel:
"""_refresh_nous_recommended_model picks a fresh model after a stale 404."""
@@ -1494,30 +1377,6 @@ class TestRefreshNousRecommendedModel:
assert out is None
class TestIsRateLimitError:
"""_is_rate_limit_error detects 429 rate-limit errors warranting fallback."""
def test_429_with_rate_limit_message(self):
exc = Exception("Rate limit exceeded, try again in 2 seconds")
exc.status_code = 429
assert _is_rate_limit_error(exc) is True
def test_openai_ratelimiterror_classname(self):
"""OpenAI SDK RateLimitError may omit .status_code — detect by class name."""
class RateLimitError(Exception):
pass
exc = RateLimitError("rate limit exceeded")
# No status_code set, but class name matches
assert _is_rate_limit_error(exc) is True
class TestTryPaymentFallback:
"""_try_payment_fallback skips the failed provider and tries alternatives."""
@@ -1593,20 +1452,6 @@ class TestCallLlmPaymentFallback:
pass
return caught.value
def test_statusless_structured_error_detection(self):
"""A status-less SDK stream error with a non-empty structured body counts (#101538)."""
assert _is_statusless_structured_provider_error(
self._sdk_stream_error({"type": "server_error", "code": "overloaded", "message": "busy"}))
assert _is_statusless_structured_provider_error(self._sdk_stream_error("service unavailable"))
assert not _is_statusless_structured_provider_error(self._sdk_stream_error({"metadata": {}}))
assert not _is_statusless_structured_provider_error(Exception("stream_error: mid_stream_failure"))
class _StatusCoded(Exception):
status_code = 503
body = {"type": "server_error"}
assert not _is_statusless_structured_provider_error(_StatusCoded("unavailable"))
def test_statusless_structured_error_after_param_strip_triggers_configured_fallback(self):
"""An in-stream error event on an explicit relay reaches the fallback chain, also when it
arrives on a parameter-strip retry (#101538)."""
@@ -2455,40 +2300,6 @@ class TestAuxClientNoSdkRetries:
assert captured.get("max_retries") == 0
class TestIsTimeoutError:
"""_is_timeout_error distinguishes a full-budget timeout from a fast
connection drop."""
def test_timed_out_string(self):
from agent.auxiliary_client import _is_timeout_error
assert _is_timeout_error(Exception("Request timed out.")) is True
def test_timeout_typename(self):
from agent.auxiliary_client import _is_timeout_error
class ReadTimeout(Exception):
pass
assert _is_timeout_error(ReadTimeout("slow")) is True
class TestIsConnectionError:
"""Tests for _is_connection_error detection."""
def test_connection_refused(self):
from agent.auxiliary_client import _is_connection_error
err = Exception("Connection refused")
assert _is_connection_error(err) is True
def test_normal_api_error_not_connection(self):
from agent.auxiliary_client import _is_connection_error
err = Exception("Bad Request: invalid model")
err.status_code = 400
assert _is_connection_error(err) is False
class TestKimiTemperatureOmitted:
"""Kimi/Moonshot models should have temperature OMITTED from API kwargs.
@@ -3087,7 +2898,8 @@ class TestAuxiliaryPoolRotationRetry:
)
assert resp.choices[0].message.content == "rotated-sync"
assert stale_client.chat.completions.create.call_count == 2
# A bare "usage limit reached" 429 is a spent plan window (billing): no same-key backoff retry.
assert stale_client.chat.completions.create.call_count == 1
assert fresh_client.chat.completions.create.call_count == 1
assert len(pool.rotate_calls) == 1
assert pool.rotate_calls[0]["status_code"] == 429

View File

@@ -3,7 +3,7 @@
xAI returns HTTP 403 (not 401) with "unauthenticated:bad-credentials" when
an OAuth2 access token has expired. These tests verify the three fixes:
1. _is_auth_error detects xAI 403 as an auth failure
1. the aux error policy reads xAI's 403 as a refreshable auth failure
2. _recoverable_pool_provider maps api.x.ai to xai-oauth
3. _refresh_provider_credentials includes xai-oauth refresh logic
"""
@@ -11,19 +11,15 @@ an OAuth2 access token has expired. These tests verify the three fixes:
import pytest
# ── _is_auth_error ──────────────────────────────────────────────────────────
def _import_is_auth_error():
from agent.auxiliary_client import _is_auth_error
return _is_auth_error
# ── auth refresh decision ───────────────────────────────────────────────────
class TestIsAuthErrorXaiOauth403:
"""Verify _is_auth_error correctly identifies xAI's 403 bad-credentials."""
"""The shared classifier reads xAI's 403 bad-credentials as a refreshable auth failure."""
@pytest.fixture(autouse=True)
def _import(self):
self.is_auth_error = _import_is_auth_error()
from agent.auxiliary_error_policy import auth_refresh, classify_attempt
self.is_auth_error = lambda exc: auth_refresh(classify_attempt(exc, "xai-oauth"))
def test_xai_403_bad_credentials_is_auth_error(self):
"""The exact error xAI returns for expired OAuth tokens."""

View File

@@ -10,6 +10,7 @@ import logging
import pytest
from agent import auxiliary_client as ac
from agent import auxiliary_error_policy as aux_errors
from agent.error_classifier import FailoverReason, classify_api_error
@@ -26,9 +27,10 @@ class _Err(Exception):
def test_openrouter_limit_403_is_billing_for_main_loop_and_aux_ladder(body):
exc = _Err(body, 403)
assert classify_api_error(exc).reason is FailoverReason.billing
assert ac._is_payment_error(exc)
# Every main-classifier billing phrase is an aux payment phrase (one table, no drift).
assert all(p in ac._PAYMENT_KEYWORDS for p in classify_api_error.__globals__["_BILLING_PATTERNS"])
# The aux ladder decides from the same verdict (one classifier, no drift).
verdict = aux_errors.classify_attempt(exc, "openrouter")
assert aux_errors.benches_provider(verdict)
assert aux_errors.fallback_label(aux_errors.Failure(exc, verdict)) == aux_errors.PAYMENT_ERROR
def test_absent_credentials_quarantine_is_debug_and_names_the_real_reason(caplog):
@@ -60,12 +62,11 @@ def test_vision_fallback_skips_text_only_main_model(monkeypatch):
])
def test_upstream_capacity_429_is_not_a_credential_to_bench(monkeypatch, body, benches_pool):
exc = _Err(body, 429)
assert ac._is_rate_limit_error(exc)
assert ac._is_overloaded_error(exc) is (not benches_pool)
assert classify_api_error(exc).reason is (
FailoverReason.rate_limit if benches_pool else FailoverReason.overloaded)
assert classify_api_error(exc).should_rotate_credential is benches_pool
# The predicate is only half the contract: _recover_provider_pool must not bench a credential
# The verdict is only half the contract: _recover_provider_pool must not bench a credential
# for an upstream-capacity 429, while a real per-key rate limit still rotates the pool.
class _StubPool:
def __init__(self):

View File

@@ -0,0 +1,358 @@
"""Auxiliary recovery decisions come from the shared classifier, driven end to end through ``call_llm``."""
from __future__ import annotations
import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import openai
import pytest
from agent.auxiliary_client import _try_openrouter, async_call_llm, call_llm
from agent.credential_pool import CredentialPool, PooledCredential as Key
from agent.error_classifier import FailoverReason
from agent.errors import InvalidProviderResponseError
from tests.agent.conftest import sdk_status_error as sdk
_REQ = httpx.Request("POST", "https://openrouter.ai/api/v1/chat/completions")
_MESSAGES = [{"role": "user", "content": "hi"}]
class _Plain(Exception):
pass
def _ok():
return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="fallback"))])
def run_ladder(error, *, provider="openrouter", retries=1, is_async=False, fallback_error=None, **call_kw):
"""``call_llm`` / ``async_call_llm`` on a client whose requests raise ``error`` (a list: one per request)."""
create = AsyncMock if is_async else MagicMock
primary = MagicMock(base_url="https://openrouter.ai/api/v1", api_key="sk-primary")
primary.chat.completions.create = create(side_effect=error)
fallback = MagicMock(base_url="https://api.example.com/v1")
fallback.chat.completions.create = create(side_effect=fallback_error, return_value=_ok())
marks, rotations, refreshes = [], [], []
with (
patch("agent.auxiliary_client._resolve_task_provider_model", return_value=(provider, "m", None, None, None)),
patch("agent.auxiliary_client._get_cached_client", return_value=(primary, "m")),
patch("agent.auxiliary_client._validate_llm_response", side_effect=lambda resp, _task, **_kw: resp),
patch("agent.auxiliary_client._transient_retry_count", return_value=retries),
patch("agent.auxiliary_client._TRANSIENT_RETRY_BACKOFF_BASE", 0.0),
patch("agent.auxiliary_client._recoverable_pool_provider", return_value="openrouter"),
patch("agent.auxiliary_client._recover_provider_pool", side_effect=lambda _p, e, **_k: rotations.append(e)),
patch("agent.auxiliary_client._mark_provider_unhealthy", side_effect=lambda *a, **kw: marks.append(a)),
patch("agent.auxiliary_client._try_configured_fallback_chain", return_value=(None, None, "")),
patch("agent.auxiliary_client._try_main_fallback_chain", return_value=(None, None, "")),
patch("agent.auxiliary_client._try_payment_fallback", return_value=(fallback, "fb", "fallback")),
patch("agent.auxiliary_client._try_main_agent_model_fallback", return_value=(fallback, "fb", "fallback")),
patch("agent.auxiliary_rate_limit_backoff.rate_limit_wait", return_value=0.0),
patch("agent.auxiliary_client._refresh_provider_credentials",
side_effect=lambda slug, **_kw: refreshes.append(slug) or True),
):
try:
if is_async:
result = asyncio.run(async_call_llm(messages=_MESSAGES, **call_kw))
else:
result = call_llm(messages=_MESSAGES, **call_kw)
except Exception as exc: # the outcome under test
result = exc
return SimpleNamespace(attempts=primary.chat.completions.create.call_count,
fallback_attempts=fallback.chat.completions.create.call_count,
fell_back=fallback.chat.completions.create.call_count > 0,
unhealthy=bool(marks), rotated=bool(rotations), refreshed=refreshes, result=result)
# (case id, error, route provider, expected outcome): the approved behaviour decisions.
BEHAVIOUR = [
("dns-refused", _Plain("[Errno 8] nodename nor servname provided, or not known"), "openrouter",
dict(attempts=2, fell_back=True)),
("http-500", sdk(500, "Internal Server Error"), "openrouter", dict(attempts=2, fell_back=True)),
("http-503", sdk(503, "Service Unavailable"), "openrouter", dict(attempts=2, fell_back=True)),
("http-408", sdk(408, "Request Timeout"), "openrouter", dict(attempts=2, fell_back=True)),
("429-overloaded", sdk(429, "The service may be temporarily overloaded, please try again later"),
"openrouter", dict(attempts=2, fell_back=True, rotated=False)),
("404-model-not-found", sdk(404, "model_not_found: The model 'x' does not exist"), "openrouter",
dict(attempts=1, fell_back=True)),
("404-free-tier-model", sdk(404, "model not found (free tier)"), "openrouter", dict(attempts=1, fell_back=True)),
("400-billing-body", sdk(400, "Insufficient credits. Add more using https://openrouter.ai/credits"),
"openrouter", dict(attempts=1, fell_back=True, unhealthy=True, rotated=True)),
("429-daily-window", sdk(429, "RESOURCE_EXHAUSTED: You have reached your daily limit."), "openrouter",
dict(fell_back=True, unhealthy=True)),
("429-resource-exhausted", sdk(429, "RESOURCE_EXHAUSTED: Worker local total request limit reached (32/32)"),
"openrouter", dict(fell_back=True, rotated=True, unhealthy=False)),
("429-rate-limit-with-billing-words", sdk(429, "Rate limit exceeded: insufficient credits for burst"),
"openrouter", dict(fell_back=True, rotated=True, unhealthy=False)),
("403-generic-auto", sdk(403, "Forbidden"), "auto", dict(attempts=1, fell_back=True, rotated=False)),
("403-quota", sdk(403, "Quota exceeded for this key"), "openrouter", dict(fell_back=True, unhealthy=True)),
("xai-bad-credentials", sdk(403, "unauthenticated:bad-credentials"), "xai-oauth",
dict(refreshed=["xai-oauth"])),
("account-gated-model", sdk(400, "model kimi-k2 is not supported for this account"), "openrouter",
dict(attempts=1, fell_back=True, rotated=True)),
("feature-restriction", sdk(400, "Tool use is not supported with this model"), "openrouter",
dict(attempts=1, fell_back=True, rotated=False)),
("parameter-400-no-rung", sdk(400, "Unsupported parameter: 'temperature' is not supported with this model."),
"openrouter", dict(attempts=1, fell_back=False, rotated=False)),
("statusless-account-wording", openai.APIError("model x-1 is not supported when using this account", _REQ,
body={"message": "gated"}), "openrouter",
dict(fell_back=True, rotated=True)),
("statusless-data-policy-denied", openai.APIError("denied", _REQ, body={"code": "data_policy_denied"}), "nous",
dict(attempts=1, fell_back=False)),
("statusless-sse-404-body", openai.APIError("Not Found", _REQ, body={"code": 404, "message": "Not Found"}),
"openrouter", dict(attempts=1, fell_back=True)),
("response-ended-prematurely", _Plain("RemoteProtocolError: response ended prematurely"), "openrouter",
dict(attempts=2, fell_back=True)),
("openrouter-upstream-429", sdk(429, "Provider returned error", wrapped=True, code=429,
metadata={"raw": "rate-limited upstream", "provider_name": "DeepInfra"}),
"openrouter", dict(attempts=1, fell_back=True, rotated=False)),
# An interrupted task stops: no same-provider retry, no other provider.
("interrupted", InterruptedError("Codex auxiliary Responses stream interrupted"), "openrouter",
dict(attempts=1, fell_back=False)),
]
@pytest.mark.parametrize("case,error,provider,expected", BEHAVIOUR, ids=[c[0] for c in BEHAVIOUR])
def test_behaviour(case, error, provider, expected):
outcome = run_ladder(error, provider=provider)
assert {key: getattr(outcome, key) for key in expected} == expected, (case, outcome.result)
@pytest.mark.parametrize("retry_error,fell_back", [ # a terminal verdict (no retry, no fallback) holds after a rung
pytest.param(sdk(400, "Bad Request"), True, id="format-error"),
pytest.param(sdk(403, "No endpoint qualifies.", code="data_policy_denied"), False, id="data-policy-denied"),
pytest.param(sdk(400, "invalid tool call arguments"), False, id="malformed-tool-args"),
])
def test_spent_parameter_rung(retry_error, fell_back):
first = sdk(400, "Unsupported parameter: 'temperature' is not supported with this model.")
outcome = run_ladder([first, retry_error], provider="nous", temperature=0.3)
assert (outcome.attempts, outcome.fell_back, outcome.rotated) == (2, fell_back, False)
@pytest.mark.parametrize("stream", [False, True], ids=["plain", "streamed"])
@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"])
def test_each_failed_request_is_classified_once(monkeypatch, is_async, stream):
"""The primary, its same-provider retry and the fallback candidate fail: one hook call per failed request."""
seen = []
monkeypatch.setattr("hermes_cli.plugins.get_plugin_error_classification", lambda **kw: seen.append(kw["error"]))
with patch("agent.auxiliary_client._aux_progress_active", return_value=stream):
outcome = run_ladder([sdk(503, "down"), sdk(503, "down")], is_async=is_async,
fallback_error=[sdk(404, "model not found"), sdk(404, "model not found")])
assert len(set(map(id, seen))) == len(seen) == outcome.attempts + outcome.fallback_attempts
def test_plugin_verdict_steers_and_retryable_false_is_honoured(monkeypatch):
from hermes_cli import plugins
verdict = {"reason": FailoverReason.server_error, "retryable": False, "should_fallback": True}
monkeypatch.setattr(plugins, "get_plugin_error_classification",
lambda **kw: verdict if "custom hiccup" in kw["error_message"] else None)
outcome = run_ladder(sdk(400, "custom hiccup"))
assert (outcome.attempts, outcome.fell_back) == (1, True)
@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"])
def test_streamed_attempt_is_judged_by_the_routes_provider_profile(monkeypatch, is_async):
"""An explicit route (no auto-routing tag) still gets its profile's verdict on a failed stream negotiation."""
import providers
hook = lambda *_a, **_k: {"reason": "server_error", "retryable": False, "should_fallback": True}
monkeypatch.setattr(providers, "get_provider_profile", lambda name: SimpleNamespace(classify_api_error=hook))
with patch("agent.auxiliary_client._aux_progress_active", return_value=True):
outcome = run_ladder(sdk(400, "custom hiccup"), is_async=is_async)
assert (outcome.attempts, outcome.fell_back) == (1, True) # no non-streaming resend before recovery
@pytest.mark.parametrize("hook,expected", [
({"reason": FailoverReason.model_not_found, "should_fallback": False}, (1, False)),
({"reason": FailoverReason.rate_limit, "retryable": False, "should_rotate_credential": True}, (1, True)),
], ids=["should-fallback-false", "rate-limit-retryable-false"])
def test_plugin_hook_overrides_win_over_aux_defaults(monkeypatch, hook, expected):
from hermes_cli import plugins
monkeypatch.setattr(plugins, "get_plugin_error_classification", lambda **kw: hook)
outcome = run_ladder(sdk(400, "plugin-owned failure"))
assert (outcome.attempts, outcome.fell_back) == expected
@pytest.mark.parametrize("retry_outcome", [ConnectionError("Connection refused"), TimeoutError("timed out")])
def test_failure_after_a_401_refresh_does_not_bench_the_refreshed_key(retry_outcome):
outcome = run_ladder([sdk(401, "invalid api key"), retry_outcome, retry_outcome])
assert outcome.refreshed == ["openrouter"]
assert (outcome.rotated, outcome.fell_back) == (False, True)
@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"])
def test_429_then_generic_403_reraises_the_403(is_async):
outcome = run_ladder([sdk(429, "Rate limit exceeded"), sdk(403, "Forbidden")], is_async=is_async)
assert isinstance(outcome.result, openai.PermissionDeniedError) and not outcome.fell_back
@pytest.mark.parametrize("is_async", [False, True], ids=["sync", "async"])
def test_opencode_go_candidate_classifies_on_its_concrete_provider(monkeypatch, is_async):
"""A sync candidate tagged opencode-go (converted to async by ``async_call_llm``) classifies on Go's
profile: the upstream throttle quarantines the candidate without rotating its key."""
import model_tools # registers the bundled provider profiles
from agent import auxiliary_error_policy as aux_errors
seen, real = [], aux_errors.classify_api_error
monkeypatch.setattr(aux_errors, "classify_api_error",
lambda exc, **kw: seen.append((kw["provider"], (v := real(exc, **kw)).reason)) or v)
body = {"error": {"type": "server_error", "message": "Upstream request failed: Rate limit exceeded."}}
transport = httpx.MockTransport(lambda request: httpx.Response(429, json=body, request=request))
go = openai.OpenAI(api_key="sk-go", base_url="https://opencode.ai/zen/go/v1", max_retries=0,
http_client=httpx.Client(transport=transport))
go._hermes_aux_effective_provider = "opencode-go" # type: ignore[attr-defined]
primary = MagicMock(base_url="https://openrouter.ai/api/v1", api_key="sk-primary")
primary.chat.completions.create = (AsyncMock if is_async else MagicMock)(side_effect=sdk(503, "down"))
with (
patch("agent.auxiliary_client._resolve_task_provider_model", return_value=("openrouter", "m", None, None, None)),
patch("agent.auxiliary_client._get_cached_client", return_value=(primary, "m")),
patch("agent.auxiliary_client._openai_http_client_kwargs",
return_value={"http_client": httpx.AsyncClient(transport=transport)}),
patch("agent.auxiliary_client._transient_retry_count", return_value=0),
patch("agent.auxiliary_client._recoverable_pool_provider", return_value=None),
patch("agent.auxiliary_client._try_configured_fallback_chain", return_value=(go, "go-model", "auto")),
patch("agent.auxiliary_client._try_main_agent_model_fallback", return_value=(None, None, "")),
patch("agent.auxiliary_client._mark_provider_unhealthy"),
pytest.raises(openai.APIError),
):
if is_async:
asyncio.run(async_call_llm(task="title_generation", messages=_MESSAGES))
else:
call_llm(task="title_generation", messages=_MESSAGES)
assert ("opencode-go", FailoverReason.upstream_rate_limit) in seen
def _wire(handle, *, key, url="https://openrouter.ai/api/v1"):
return openai.OpenAI(api_key=key, base_url=url, max_retries=0, http_client=httpx.Client(
transport=httpx.MockTransport(handle)))
def test_refreshed_nous_stream_error_falls_back():
"""401, Nous refresh, then the refreshed key's SSE ``error`` event: classified as itself (fallback)."""
sse = lambda request: httpx.Response(200, content=b'data: {"error": "backend worker failed"}\n\n',
headers={"content-type": "text/event-stream"}, request=request)
primary = _wire(lambda r: httpx.Response(401, json={"error": {"message": "bad key"}}, request=r), key="sk-old")
refreshed = _wire(sse, key="sk-fresh", url="https://inference-api.nousresearch.com/v1")
fallback = MagicMock(base_url="https://api.example.com/v1")
fallback.chat.completions.create = MagicMock(return_value=_ok())
with (
patch("agent.auxiliary_client._aux_progress_active", return_value=True),
patch("agent.auxiliary_client._resolve_task_provider_model", return_value=("nous", "m", None, None, None)),
patch("agent.auxiliary_client._get_cached_client", return_value=(primary, "m")),
patch("agent.auxiliary_client._refresh_nous_auxiliary_client", return_value=(refreshed, "m2")),
patch("agent.auxiliary_client._refresh_nous_recommended_model", return_value=None),
patch("agent.auxiliary_client._transient_retry_count", return_value=0),
patch("agent.auxiliary_client._recoverable_pool_provider", return_value=None),
patch("agent.auxiliary_client._mark_provider_unhealthy"),
patch("agent.auxiliary_client._try_configured_fallback_chain", return_value=(None, None, "")),
patch("agent.auxiliary_client._try_main_agent_model_fallback", return_value=(fallback, "fb", "fallback")),
):
assert call_llm(task="title_generation", messages=_MESSAGES).choices[0].message.content == "fallback"
def test_invalid_answer_classifies_as_incomplete_response():
from agent.error_classifier import classify_api_error
assert classify_api_error(InvalidProviderResponseError("x")).reason is FailoverReason.incomplete_response
def test_tls_certificate_failure_keeps_compressions_session_preserving_abort():
import ssl
from agent.context_compressor import ContextCompressor
with patch("agent.context_compressor.get_model_context_length", return_value=100000):
compressor = ContextCompressor(model="test", quiet_mode=True, protect_first_n=2, protect_last_n=2,
abort_on_summary_failure=False)
msgs = [{"role": "user" if i % 2 == 0 else "assistant", "content": f"msg {i}"} for i in range(12)]
error = ssl.SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed")
with patch("agent.context_compressor.call_llm", side_effect=error):
assert compressor.compress(msgs, current_tokens=999999, force=True) == msgs
assert compressor._last_summary_network_failure and compressor._last_compress_aborted
def test_relay_connection_reset_502_keeps_compressions_session_preserving_abort():
from agent.context_compressor import ContextCompressor
with patch("agent.context_compressor.get_model_context_length", return_value=100000):
compressor = ContextCompressor(model="test", quiet_mode=True, protect_first_n=2, protect_last_n=2,
abort_on_summary_failure=False)
msgs = [{"role": "user" if i % 2 == 0 else "assistant", "content": f"msg {i}"} for i in range(12)]
with patch("agent.context_compressor.call_llm", side_effect=sdk(502, "upstream: connection reset by peer")):
assert compressor.compress(msgs, current_tokens=999999, force=True) == msgs
assert compressor._last_summary_network_failure
def test_pinned_custom_provider_entitlement_benches_only_the_model():
from agent.auxiliary_client import _recover_provider_pool
from agent.auxiliary_error_policy import classify_attempt
error = sdk(400, "model kimi-k2 is not supported for this account")
pool = MagicMock()
with patch("agent.auxiliary_client.pool_for_aux_provider", return_value=pool):
_recover_provider_pool("custom:relay", error, verdict=classify_attempt(error, "custom:relay", model="kimi-k2"))
assert pool.mark_exhausted_and_rotate.call_args.kwargs["model"] == "kimi-k2"
key = Key("openrouter", "k1", "k1", "api_key", 0, "manual", "sk-or", model_cooldowns={"openai/gpt-gated": 9e9})
with patch("agent.auxiliary_client.load_pool", lambda _p: CredentialPool("openrouter", [key])): # sibling models keep the key
assert [_try_openrouter(model=m)[0] is None for m in ("gpt-ok", "gpt-gated")] == [False, True]
def test_missing_model_on_a_candidate_hides_only_that_model(monkeypatch):
from agent import auxiliary_client as aux
monkeypatch.setattr(aux, "_aux_unhealthy_until", {})
monkeypatch.setattr(aux, "_aux_unhealthy_reason", {})
aux._quarantine_fallback_candidate("title_generation", "fallback_chain[0](openrouter)", "openrouter",
sdk(404, "model not found"), reason="model not found", model="old-model")
assert aux._is_provider_unhealthy("openrouter", model="old-model")
assert not aux._is_provider_unhealthy("openrouter", model="new-model")
assert not aux._is_provider_unhealthy("openrouter")
aux._quarantine_fallback_candidate("t", "fb", "openrouter", sdk(404, "x"), reason="model not found", model="openai/gpt-retired")
assert aux._is_provider_unhealthy("openrouter", model="gpt-retired") # resolved name written, configured name read
with patch.object(aux, "_get_provider_chain", return_value=[("openrouter", lambda: (MagicMock(), "openai/gpt-retired")), (
"nous", lambda: (MagicMock(), "m"))]), patch.object(aux, "_discovery_chain_allowed"):
assert aux._try_payment_fallback("zai")[2] == "nous" # discovery skips the hidden model too
def test_a_rebuilt_retry_is_classified_on_the_request_it_sent(): # e.g. a fast-model task rebuilt on the main model
models, clients = [], [MagicMock(base_url="https://openrouter.ai/api/v1", **{"chat.completions.create.side_effect": sdk(
400, f"model {model} is not supported for this account")}) for model in ("kimi-k2", "glm-5")]
with patch.multiple(
"agent.auxiliary_client", _resolve_task_provider_model=lambda *_a: ("openrouter", "kimi-k2", None, None, None),
_get_cached_client=lambda *_a, **_k: (clients[0], "kimi-k2"), _prepare_same_provider_retry=lambda **_k: (
clients[1], {"model": "glm-5"}), _recover_provider_pool=lambda _p, _e, **kw: models.append(kw["verdict"].model) or True,
), pytest.raises(openai.APIError):
call_llm(task="title_generation", messages=_MESSAGES)
assert models == ["kimi-k2", "glm-5"] # the verdict models handed to pool rotation, in order
def _candidate_outcome(first, refreshed):
from agent.auxiliary_client import _call_fallback_candidate_sync
marks, raised = [], None
with (
patch("agent.auxiliary_client._mark_provider_unhealthy", side_effect=lambda *a, **k: marks.append(k)),
patch("agent.auxiliary_client._refresh_provider_credentials", return_value=True),
patch("agent.auxiliary_client._get_cached_client", return_value=(refreshed, "fb-model")),
):
try:
_call_fallback_candidate_sync(
first, "fb-model", "openrouter", task="title_generation", messages=_MESSAGES, temperature=None,
max_tokens=16, tools=None, effective_timeout=30.0, effective_extra_body={}, reasoning_config=None)
except Exception as exc: # the outcome under test
raised = type(exc)
return raised, [(k["reason"], k["ttl"]) for k in marks]
@pytest.mark.parametrize("body", [b"null", b'{"success": false, "data": {"error": {"message": "crashed"}}}'])
def test_refreshed_candidates_bad_answer_is_not_a_stale_credential(body):
"""401, refresh, then a bad answer: the same outcome the answer gets with no 401 before it."""
bad = lambda: _wire(lambda r: httpx.Response(200, content=body, headers={"content-type": "application/json"},
request=r), key="sk-fresh")
stale = _wire(lambda r: httpx.Response(401, json={"error": {"message": "bad key"}}, request=r), key="sk-old")
after_refresh = _candidate_outcome(stale, bad())
assert ("stale fallback credential", None) not in after_refresh[1]
assert after_refresh == _candidate_outcome(bad(), None)

View File

@@ -12,6 +12,7 @@ from unittest.mock import MagicMock
from agent.auxiliary_client import (
_call_fallback_candidate_sync,
_drive_ladder,
_failure,
_is_reasoning_field_rejection,
_ladder_parameter_rungs,
_LadderRoute,
@@ -59,7 +60,7 @@ def test_primary_rungs_chain_in_provider_order_and_strip_each_field_once():
step_client, step_kwargs = step.args
return step_client.chat.completions.create(**step_kwargs)
resp, err, final_kwargs = _drive_ladder(_ladder_parameter_rungs(first_err, route, kwargs, 64), perform)
resp, err, final_kwargs, _repaired = _drive_ladder(_ladder_parameter_rungs(_failure(route, first_err), route, kwargs, 64), perform)
assert err is None and resp.choices[0].message.content == "ok"
assert not {"temperature", "max_tokens", "reasoning_effort"} & set(final_kwargs)
@@ -138,9 +139,9 @@ def test_rate_limit_after_parameter_strip_falls_through_to_later_rungs():
kwargs = {"model": "m", "messages": [], "max_tokens": 64}
first_err = _Bad400("Error code: 400 - Unsupported parameter: 'max_tokens' is not supported with this model.")
resp, err, final_kwargs = _drive_ladder(
_ladder_parameter_rungs(first_err, route, kwargs, 64),
resp, err, final_kwargs, _repaired = _drive_ladder(
_ladder_parameter_rungs(_failure(route, first_err), route, kwargs, 64),
lambda step: step.args[0].chat.completions.create(**step.args[1]))
assert resp is None and err is rate_limited
assert resp is None and err.error is rate_limited
assert "max_tokens" not in final_kwargs

View File

@@ -104,7 +104,7 @@ def test_auxiliary_retries_share_logical_relay_identity(monkeypatch):
"test-model",
"openrouter",
None,
"unknown", # recovered from the unclassifiable invalid first response
"incomplete_response", # recovered from the invalid first response (HTTP 200, no choices)
)
]
@@ -177,7 +177,7 @@ def test_auxiliary_provider_fallback_closes_one_real_logical_call(
assert turn.logical_llm_calls == {}
assert logical_outputs == [
{
"error_class": "unknown",
"error_class": "incomplete_response",
"model": "openrouter/test-model",
"outcome": "success",
"provider": "openrouter",
@@ -259,8 +259,8 @@ def test_auxiliary_provider_fallback_records_one_terminal_model_route(
assert snapshot[0]["resource"]["hermes_version"] == "test-version"
assert snapshot[0]["dimensions"] == {
"call_role": "auxiliary",
# The success keeps the error it recovered from; an invalid shape classifies as unknown.
"error_class": "unknown",
# The success keeps the error it recovered from; an invalid shape is an incomplete response.
"error_class": "incomplete_response",
"model": "accepted/model",
"outcome": "success",
"provider": "openrouter",