Skip to content

perf(provider): fail fast on credential/channel exhaustion and add failover soft cooldown - #11641

Open
JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:perf/fail-fast-credential-500-and-fallback-cooldown
Open

JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:perf/fail-fast-credential-500-and-fallback-cooldown

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Eliminates multi-minute latency spikes during upstream relay/gateway credential or channel exhaustion when fallback chat providers are configured:

  1. Fail fast on deterministic credential/channel/quota exhaustion responses in request_retry.py instead of spending ~90–140s retrying the identical failing request with exponential backoff.
  2. Add a lightweight, bounded, in-memory per-provider soft cooldown (60s) in ToolLoopAgentRunner so consecutive turns after a failover try healthy fallback providers first while still preserving the configured order and keeping the primary provider as a last resort.

Root Cause

  1. astrbot/core/provider/sources/request_retry.py previously treated every HTTP 5xx (and 429 when retry_rate_limits=True) as retryable with wait_exponential(min=0.2s, max=30s). When an upstream relay or gateway returned a deterministic exhaustion error such as HTTP 500 "当前无可用凭证", "无可用渠道", "no available credential", "no available channel", "no healthy upstream", or HTTP 429 "insufficient_quota", AstrBot still retried up to request_max_retries times before handing off to the configured fallback provider.
  2. ToolLoopAgentRunner._iter_llm_responses_with_fallback() had no cross-turn memory of recent failovers (a fresh runner is instantiated per turn). Even immediately after primary provider P failed over to a healthy fallback provider F, the very next turn still probed P first and repeated the full failure path before falling back to F again.

Changes

  1. Fail-Fast Deterministic Exhaustion Detection (astrbot/core/provider/sources/request_retry.py)

    • Add _is_deterministic_exhaustion_error() with defensive payload extraction (details, body, response_json, response.json()/response.text, message, and str(error)), safely handling unread streaming httpx.Response bodies and JSON unicode escapes without ever masking the original exception.
    • Treat deterministic credential, channel, upstream-pool, and quota exhaustion markers (无可用凭证, 无可用渠道, no available credential, no available channel, no healthy upstream, insufficient quota / insufficient_quota) on HTTP 429 and 5xx responses as non-retryable so requests fail fast and hand off immediately to fallback providers.
    • Preserve existing retry behavior for all transient transport errors (ConnectError, APIConnectionError, APITimeoutError) and transient HTTP 500/502/503/504/429 errors.
  2. Lightweight Per-Provider Failover Soft Cooldown (astrbot/core/agent/runners/tool_loop_agent_runner.py)

    • Add a thread-safe, bounded, zero-disk-I/O in-memory monotonic cooldown table (PROVIDER_FAILOVER_COOLDOWN_S = 60.0, PROVIDER_FAILOVER_COOLDOWN_MAX_ENTRIES = 256, plus clear_provider_failover_cooldowns()).
    • Record soft cooldown for failed candidate provider(s) only when another candidate succeeds in the same failover sequence; clear cooldown immediately whenever a provider succeeds; record nothing if all candidates fail or if execution is stopped/steered/cancelled.
    • Stably partition candidates into [healthy..., cooled_down...] without mutating configured provider lists or ever removing a candidate:
      • Healthy fallbacks are tried first during the 60s window in their exact configured order.
      • Explicit request.model overrides remain bound strictly to the configured primary provider (candidate is primary_provider) and never leak onto fallback providers.
      • If all healthy fallbacks also fail, the cooled-down primary provider is still attempted as a last resort.
      • Once the 60s monotonic window expires, the primary provider is automatically probed first again.
  3. Tests (No New Standalone Test Files)

    • Extended existing tests/test_request_retry.py to cover fail-fast handling for deterministic exhaustion errors across OpenAI SDK, httpx.HTTPStatusError (including unicode-escaped JSON), and .code/.details SDK exception shapes, as well as continued retrying on transient 500/502/503/504/429 and unread streaming responses.
    • Extended existing tests/test_tool_loop_agent_runner.py (with deterministic monotonic clock mocking) to verify healthy-fallback preference during cooldown, explicit request.model isolation, automatic primary restoration after cooldown expiry, last-resort primary fallback when fallbacks fail, multi-fallback order preservation, no cooldown on total outage, and bounded cache eviction.

Files Changed

  • astrbot/core/provider/sources/request_retry.py
  • astrbot/core/agent/runners/tool_loop_agent_runner.py
  • tests/test_request_retry.py
  • tests/test_tool_loop_agent_runner.py

Verification

  • python -m py_compile astrbot/core/provider/sources/request_retry.py astrbot/core/agent/runners/tool_loop_agent_runner.py tests/test_request_retry.py tests/test_tool_loop_agent_runner.py: passed.
  • ruff check .: passed (All checks passed!).
  • ruff format --check .: passed (606 files already formatted).
  • git diff --check origin/master..HEAD: passed (0 issues).
  • pytest tests/test_request_retry.py tests/test_tool_loop_agent_runner.py tests/unit/test_provider_stats.py: 115 passed, 0 failed.
  • pytest tests/test_openai_source.py tests/test_gemini_source.py tests/test_anthropic_source.py tests/agent/test_context_manager.py: 187 passed, 0 failed.

建议合并顺序 (Recommended Merge Order)

  • Fully independent PR touching 4 files (request_retry.py, tool_loop_agent_runner.py, test_request_retry.py, test_tool_loop_agent_runner.py) with zero file overlap against sibling AstrBot PR branches; can be merged in any order.

Summary by Sourcery

Reduce delays during provider exhaustion and make subsequent turns prefer providers that recently succeeded.

New Features:

  • Prioritize healthy providers after a successful failover by temporarily cooling down providers that failed, while keeping them available as last-resort candidates.

Bug Fixes:

  • Fail fast on credential, channel, upstream-pool, and quota exhaustion errors instead of retrying the same request.

Enhancements:

  • Keep transient transport and HTTP errors retryable and preserve configured provider order among candidates with the same cooldown status.

Tests:

  • Extend retry and agent-runner tests to cover exhaustion detection, cooldown ordering and expiry, fallback behavior, and bounded cooldown storage.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 7 issues

Sourcery assessment

Approval pending. 6 findings to address first.

Blocking findings: astrbot/core/agent/runners/tool_loop_agent_runner.py:891, astrbot/core/provider/sources/request_retry.py:166, astrbot/core/provider/sources/request_retry.py:91, astrbot/core/agent/runners/tool_loop_agent_runner.py:968, astrbot/core/agent/runners/tool_loop_agent_runner.py:868, and 1 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

return

candidates = [self.provider, *self.fallback_providers]
primary_provider = getattr(self, "_primary_provider", self.provider)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Primary provider stays behind fallback

When a fallback succeeds and the same runner makes another LLM request after the primary cooldown expires, self.provider still points to the successful fallback, so configured_candidates puts it ahead of _primary_provider and _order_candidates_with_cooldown preserves that order once both providers are healthy; the primary is not probed first as configured.

Build configured_candidates from _primary_provider rather than the mutable self.provider.

Also at astrbot/core/agent/runners/tool_loop_agent_runner.py:892.


if (
status_code == 429 or 500 <= status_code <= 599
) and _is_deterministic_exhaustion_error(error):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Quota failures still delay fallback

When an OpenAI-compatible provider returns HTTP 429 with an exhaustion marker and its configured API keys are also exhausted, retry_provider_request stops retrying, but ProviderOpenAIOfficial.text_chat catches the 429 and _handle_api_error still sleeps and rotates through API keys; fallback waits until that loop exhausts.

Make the OpenAI key-rotation handler recognize deterministic exhaustion and skip retries or waits that cannot recover.

if response is not None:
parsed_response = None
try:
parsed_response = response.json()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Large errors exhaust memory

When a configured upstream returns an extremely large HTTP error body, _iter_error_texts calls response.json() on the full upstream error body without a size limit, creating another decoded object while classifying the exception; a sufficiently large error response from a configured provider can exhaust process memory and interrupt service.

Bound the response-body bytes inspected for exhaustion markers before decoding or parsing them.

break

if resp.role != "err":
self._record_failover_outcome(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Stopped turns still cool down providers

When a stop is requested before the non-streaming fallback loop records a successful response after an earlier candidate failed, the non-streaming path calls _record_failover_outcome without checking the stop state, so it cools down earlier failed providers even though the turn is aborted; later requests then deprioritize those providers.

Check the stop state before calling _record_failover_outcome on the non-streaming success path.

expires_at = now + cooldown_s
for key in failed_keys:
_PROVIDER_FAILOVER_COOLDOWNS.pop(key, None)
_PROVIDER_FAILOVER_COOLDOWNS[key] = expires_at

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Older failures re-cool recovered providers

When concurrent requests share provider P, one fails on P and waits on F, and another succeeds on P before F succeeds, a request that failed on provider P and is still waiting on fallback F can write a fresh cooldown for P after another request succeeds on P and clears its entry; later turns then deprioritize P despite that successful probe.

Order cooldown updates by the time or generation of each provider outcome so a failure observed before a later success cannot reapply a cooldown.


cooldown_s = self.PROVIDER_FAILOVER_COOLDOWN_S
max_entries = max(1, self.PROVIDER_FAILOVER_COOLDOWN_MAX_ENTRIES)
now = time.monotonic()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Concurrent updates shorten cooldown

When two runner threads record failures for the same provider and the thread that sampled time first acquires the lock last, _record_failover_outcome samples the time before acquiring the lock, then replaces an existing cooldown unconditionally. A thread delayed before the lock can overwrite a later thread's expiry with its earlier timestamp, causing the provider to leave cooldown early.

Sample the monotonic time while holding the lock and avoid replacing an existing cooldown with an earlier expiry.



def _iter_error_texts(error: BaseException) -> Iterator[str]:
"""Yield readable error text fragments from provider SDK exceptions."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · New docstrings omit required sections

These documented functions take parameters and, in some cases, return values, but their docstrings omit the applicable Args: and Returns: sections. They therefore do not follow the required Google format.

Add the applicable Google-format Args: and Returns: sections to these docstrings.

Also at astrbot/core/provider/sources/request_retry.py:122, astrbot/core/agent/runners/tool_loop_agent_runner.py:813, astrbot/core/agent/runners/tool_loop_agent_runner.py:843.

From AGENTS.md L78:

* **Google Format**: All docstrings must strictly use the Google format (`Args:`, `Returns:`, `Raises:`).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant