Repository navigation
perf(provider): fail fast on credential/channel exhaustion and add failover soft cooldown - #11641
Conversation
…ilover soft cooldown
There was a problem hiding this comment.
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
| return | ||
|
|
||
| candidates = [self.provider, *self.fallback_providers] | ||
| primary_provider = getattr(self, "_primary_provider", self.provider) |
There was a problem hiding this comment.
🟡 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): |
There was a problem hiding this comment.
🟡 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() |
There was a problem hiding this comment.
🟡 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( |
There was a problem hiding this comment.
🟡 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 |
There was a problem hiding this comment.
🟡 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() |
There was a problem hiding this comment.
🟡 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.""" |
There was a problem hiding this comment.
⚪ 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:`).…nd harden concurrency/error parsing
Summary
Eliminates multi-minute latency spikes during upstream relay/gateway credential or channel exhaustion when fallback chat providers are configured:
request_retry.pyinstead of spending ~90–140s retrying the identical failing request with exponential backoff.ToolLoopAgentRunnerso 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
astrbot/core/provider/sources/request_retry.pypreviously treated every HTTP5xx(and429whenretry_rate_limits=True) as retryable withwait_exponential(min=0.2s, max=30s). When an upstream relay or gateway returned a deterministic exhaustion error such as HTTP500"当前无可用凭证","无可用渠道","no available credential","no available channel","no healthy upstream", or HTTP429"insufficient_quota", AstrBot still retried up torequest_max_retriestimes before handing off to the configured fallback provider.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 providerPfailed over to a healthy fallback providerF, the very next turn still probedPfirst and repeated the full failure path before falling back toFagain.Changes
Fail-Fast Deterministic Exhaustion Detection (
astrbot/core/provider/sources/request_retry.py)_is_deterministic_exhaustion_error()with defensive payload extraction (details,body,response_json,response.json()/response.text,message, andstr(error)), safely handling unread streaminghttpx.Responsebodies and JSON unicode escapes without ever masking the original exception.无可用凭证,无可用渠道,no available credential,no available channel,no healthy upstream,insufficient quota/insufficient_quota) on HTTP429and5xxresponses as non-retryable so requests fail fast and hand off immediately to fallback providers.ConnectError,APIConnectionError,APITimeoutError) and transient HTTP500/502/503/504/429errors.Lightweight Per-Provider Failover Soft Cooldown (
astrbot/core/agent/runners/tool_loop_agent_runner.py)PROVIDER_FAILOVER_COOLDOWN_S = 60.0,PROVIDER_FAILOVER_COOLDOWN_MAX_ENTRIES = 256, plusclear_provider_failover_cooldowns()).[healthy..., cooled_down...]without mutating configured provider lists or ever removing a candidate:request.modeloverrides remain bound strictly to the configured primary provider (candidate is primary_provider) and never leak onto fallback providers.Tests (No New Standalone Test Files)
tests/test_request_retry.pyto cover fail-fast handling for deterministic exhaustion errors across OpenAI SDK,httpx.HTTPStatusError(including unicode-escaped JSON), and.code/.detailsSDK exception shapes, as well as continued retrying on transient500/502/503/504/429and unread streaming responses.tests/test_tool_loop_agent_runner.py(with deterministic monotonic clock mocking) to verify healthy-fallback preference during cooldown, explicitrequest.modelisolation, 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.pyastrbot/core/agent/runners/tool_loop_agent_runner.pytests/test_request_retry.pytests/test_tool_loop_agent_runner.pyVerification
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)
request_retry.py,tool_loop_agent_runner.py,test_request_retry.py,test_tool_loop_agent_runner.py) with zero file overlap against siblingAstrBotPR 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:
Bug Fixes:
Enhancements:
Tests: