项目文件夹

文件
Ali Khokhar af12e7b2bb Coordinate provider recovery under concurrent load (#1205)
## Problem

Concurrent transient failures could start independent retry, replay,
continuation, and repair loops while holding provider concurrency slots.
This multiplied upstream attempts and could delay or strand terminal
errors under fan-out.

## Changes

| Before | After |
| --- | --- |
| Retry paths owned separate attempt budgets. | One logical-execution
session caps all upstream work at five attempts. |
| Concurrent failures backed off independently. | One provider-owned
recovery episode elects a single half-open probe while followers
coalesce. |
| Backoff occupied stream concurrency. | Concurrency is held only while
an upstream operation or stream is active. |
| Provider catalog calls and stream creation used separate admission
paths. | Every upstream operation uses one provider-generation admission
controller. |
| Cancellation could leave recovery ownership or follower state
unresolved. | Cancellation releases permits, transfers probe ownership,
and unregisters waiting followers. |
| Late in-flight failures could cross an exhausted episode boundary. |
Every coalesced execution retains that generation's terminal outcome. |
| Replay tests allowed loose lifecycle assertions. | Exact SSE contracts
prove retries and continuations emit one unduplicated response. |
| Recovery wrappers could mask final diagnostics. | Final responses and
traces retain the raw provider failure and request ID. |

<!-- greptile_comment -->

<details open><summary><h3>Greptile Summary</h3></summary>

This PR coordinates provider recovery and retry work under concurrent
load. The main changes are:

- One five-attempt budget for each logical execution.
- Provider-wide recovery episodes with one elected probe.
- Shared admission for streams, catalog calls, rate limits, and
concurrency.
- Concurrency permits held only during active upstream work.
- Cancellation-safe probe ownership and preserved final diagnostics.
</details>

<h3>Confidence Score: 5/5</h3>

This looks safe to merge.

No blocking issues found in the changed code.

<details><summary><h3><a href="https://www.greptile.com/trex"><img
alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="20" align="absmiddle"></a> T-Rex Logs</h3></summary>

**What T-Rex did**
- Reviewed the coordinated-recovery-01-before.log to understand how the
exhausted generation outcome was not preserved in a late in-flight
failure.
- Reviewed the coordinated-recovery-02-after.log to confirm that the
updated implementation preserves the exhausted generation outcome for
the same focused contract set.
- Validated that the provider-admission-full-current.log shows the
complete requested test file passed under Python 3.14 with uv run pytest
-n 0.

<a
href="https://app.greptile.com/trex/runs/15050270/artifacts"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifactsDark.svg?v=4"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"><img
alt="View all artifacts"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"></picture></a>

<sub><a href="https://www.greptile.com/trex"><img alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="14" align="absmiddle"></a> Ran code and verified through
T-Rex</sub>
</details>

<details open><summary><h3>Important Files Changed</h3></summary>

| Filename | Overview |
|----------|----------|
| src/free_claude_code/providers/admission.py | Adds shared admission,
retry budgets, recovery episodes, probe election, and cancellation
handling. |
| src/free_claude_code/providers/openai_chat/provider.py | Moves stream
creation, replay, continuation, and repair onto one admission-owned
retry session. |
| src/free_claude_code/providers/stream_recovery.py | Selects replay,
continuation, repair, or final failure using the remaining shared
attempt budget. |
| src/free_claude_code/providers/failure_policy.py | Adds recovery
exhaustion handling and preserves the underlying provider error for
final classification. |
| src/free_claude_code/providers/runtime/factory.py | Creates one
admission controller per provider generation and passes it through
provider factories. |

</details>

<details open><summary><h3>Sequence Diagram</h3></summary>

<a href="#gh-light-mode-only">

```mermaid
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant E as Execution
participant A as Admission controller
participant P as Provider
participant F as Concurrent follower

E->>A: Open attempt
A->>P: Send upstream request
P-->>E: Retryable failure
E->>A: Open recovery episode
F->>A: Request admission
A-->>F: Coalesce and wait
E->>A: Claim probe
A->>P: Send half-open probe
alt Probe succeeds
    P-->>E: Valid response
    E->>A: Close recovery episode
    A-->>F: Release waiter
else Probe fails
    P-->>E: Retryable failure
    E->>A: Schedule next probe or finalize error
end
```

</a>
<a href="#gh-dark-mode-only">

```mermaid
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant E as Execution
participant A as Admission controller
participant P as Provider
participant F as Concurrent follower

E->>A: Open attempt
A->>P: Send upstream request
P-->>E: Retryable failure
E->>A: Open recovery episode
F->>A: Request admission
A-->>F: Coalesce and wait
E->>A: Claim probe
A->>P: Send half-open probe
alt Probe succeeds
    P-->>E: Valid response
    E->>A: Close recovery episode
    A-->>F: Release waiter
else Probe fails
    P-->>E: Retryable failure
    E->>A: Schedule next probe or finalize error
end
```

</a>
</details>

<sub>Reviews (2): Last reviewed commit: ["Harden coordinated retry
lifecycle
invar..."](https://github.com/alishahryar1/free-claude-code/commit/2e871c8649d148b5eb71d21f80bf870ae2d11708)
| [Re-trigger
Greptile](https://app.greptile.com/api/retrigger?id=45554917)</sub>

<!-- /greptile_comment -->
2026-07-19 22:43:29 -07:00

166 行
4.8 KiB
Python

"""Provider construction from declarative profiles and exceptional adapters."""
from collections.abc import Callable
from free_claude_code.application.errors import UnknownProviderError
from free_claude_code.config.provider_catalog import PROVIDER_CATALOG
from free_claude_code.config.settings import Settings
from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import BaseProvider, ProviderConfig
from free_claude_code.providers.openai_chat import (
OPENAI_CHAT_PROFILES,
create_openai_chat_provider,
)
from .config import build_provider_config
ProviderFactory = Callable[
[ProviderConfig, Settings, ProviderAdmissionController], BaseProvider
]
def _create_nvidia_nim(
config: ProviderConfig,
settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.nvidia_nim import NvidiaNimProvider
return NvidiaNimProvider(
config,
nim_settings=settings.nim,
admission=admission,
)
def _create_open_router(
config: ProviderConfig,
_settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.open_router import OpenRouterProvider
return OpenRouterProvider(config, admission=admission)
def _create_mistral(
config: ProviderConfig,
_settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.mistral import MistralProvider
return MistralProvider(config, admission=admission)
def _create_deepseek(
config: ProviderConfig,
_settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.deepseek import DeepSeekProvider
return DeepSeekProvider(config, admission=admission)
def _create_lmstudio(
config: ProviderConfig,
_settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.lmstudio import LMStudioProvider
return LMStudioProvider(config, admission=admission)
def _create_cloudflare(
config: ProviderConfig,
settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.cloudflare import CloudflareProvider
return CloudflareProvider(
config,
account_id=settings.cloudflare_account_id,
admission=admission,
)
def _create_gemini(
config: ProviderConfig,
_settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.gemini import GeminiProvider
return GeminiProvider(config, admission=admission)
def _create_vertex(
config: ProviderConfig,
settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.vertex import VertexProvider
return VertexProvider(
config,
project_id=settings.vertex_project_id,
location=settings.vertex_location,
admission=admission,
)
def _create_github_models(
config: ProviderConfig,
_settings: Settings,
admission: ProviderAdmissionController,
) -> BaseProvider:
from free_claude_code.providers.github_models import GitHubModelsProvider
return GitHubModelsProvider(config, admission=admission)
_SPECIAL_PROVIDER_FACTORIES: dict[str, ProviderFactory] = {
"nvidia_nim": _create_nvidia_nim,
"open_router": _create_open_router,
"mistral": _create_mistral,
"deepseek": _create_deepseek,
"lmstudio": _create_lmstudio,
"cloudflare": _create_cloudflare,
"gemini": _create_gemini,
"vertex": _create_vertex,
"github_models": _create_github_models,
}
_profiled_ids = set(OPENAI_CHAT_PROFILES)
_special_ids = set(_SPECIAL_PROVIDER_FACTORIES)
if _profiled_ids & _special_ids or _profiled_ids | _special_ids != set(
PROVIDER_CATALOG
):
raise AssertionError(
"Every provider must have exactly one construction owner: "
f"profiles={_profiled_ids!r} special={_special_ids!r} "
f"catalog={set(PROVIDER_CATALOG)!r}"
)
def create_provider(provider_id: str, settings: Settings) -> BaseProvider:
"""Create a provider instance for a supported provider id."""
descriptor = PROVIDER_CATALOG.get(provider_id)
if descriptor is None:
raise UnknownProviderError.for_provider(provider_id, PROVIDER_CATALOG)
config = build_provider_config(descriptor, settings)
admission = ProviderAdmissionController(
provider_name=provider_id,
rate_limit=config.rate_limit or 40,
rate_window=config.rate_window or 60.0,
max_concurrency=config.max_concurrency,
)
factory = _SPECIAL_PROVIDER_FACTORIES.get(provider_id)
if factory is not None:
return factory(config, settings, admission)
return create_openai_chat_provider(provider_id, config, admission)