项目文件夹

文件
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

238 行
7.1 KiB
Python

"""Tests for the OpenRouter OpenAI-chat provider."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.anthropic.stream_contracts import (
parse_sse_text,
text_content,
)
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.open_router import OpenRouterProvider
from free_claude_code.providers.openai_chat import OpenAIChatProvider
from tests.providers.request_factory import make_messages_request
from tests.providers.support import (
REASONING_OFF,
immediate_admission,
reasoning_for,
)
class AsyncStream:
def __init__(self, chunks):
self._chunks = chunks
self.closed = False
def __aiter__(self):
return self._iter()
async def _iter(self):
for chunk in self._chunks:
yield chunk
async def aclose(self):
self.closed = True
def make_request(**overrides):
return make_messages_request("moonshotai/kimi-k2.6:free", **overrides)
@pytest.fixture
def open_router_provider():
return OpenRouterProvider(
ProviderConfig(
api_key="test_openrouter_key",
base_url="https://openrouter.ai/api/v1",
rate_limit=10,
rate_window=60,
),
admission=immediate_admission(),
)
def _chunk(
*,
content: str | None = None,
reasoning_content: str | None = None,
reasoning_details: list[dict] | None = None,
finish_reason: str | None = None,
):
delta = SimpleNamespace(
content=content,
reasoning_content=reasoning_content,
tool_calls=None,
)
if reasoning_details is not None:
delta.reasoning_details = reasoning_details
choice = SimpleNamespace(delta=delta, finish_reason=finish_reason)
return SimpleNamespace(choices=[choice], usage=None)
def test_init_uses_openai_chat_provider(open_router_provider):
assert isinstance(open_router_provider, OpenAIChatProvider)
assert open_router_provider._api_key == "test_openrouter_key"
assert open_router_provider._base_url == "https://openrouter.ai/api/v1"
def test_build_request_body_uses_openai_chat_shape(open_router_provider):
body = open_router_provider._build_request_body(make_request())
assert body["model"] == "moonshotai/kimi-k2.6:free"
assert body["temperature"] == 0.5
assert body["messages"] == [
{"role": "system", "content": "System prompt"},
{"role": "user", "content": "Hello"},
]
assert body["max_tokens"] == 100
assert "extra_body" not in body
def test_build_request_body_default_max_tokens(open_router_provider):
body = open_router_provider._build_request_body(make_request(max_tokens=None))
assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
def test_openrouter_extra_body_rejects_overriding_reserved_fields(
open_router_provider,
):
with pytest.raises(InvalidRequestError, match="model"):
open_router_provider._build_request_body(
make_request(extra_body={"model": "hijack"})
)
def test_openrouter_extra_body_allows_provider_keys(open_router_provider):
body = open_router_provider._build_request_body(
make_request(extra_body={"transforms": ["no-web"], "plugins": []}),
reasoning=REASONING_OFF,
)
assert body["extra_body"] == {
"transforms": ["no-web"],
"plugins": [],
"reasoning": {"enabled": False},
}
def test_build_request_body_disables_reasoning_when_client_disables_it(
open_router_provider,
):
request = make_request(thinking={"type": "disabled"})
body = open_router_provider._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["extra_body"]["reasoning"] == {"enabled": False}
def test_build_request_body_maps_thinking_budget_to_reasoning_max_tokens(
open_router_provider,
):
request = make_request(thinking={"type": "enabled", "budget_tokens": 4096})
body = open_router_provider._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["extra_body"]["reasoning"] == {"max_tokens": 4096}
def test_build_request_body_replays_openrouter_reasoning_details(
open_router_provider,
):
detail = {"type": "reasoning.encrypted", "data": "opaque"}
request = MessagesRequest.model_validate(
{
"model": "m",
"messages": [
{
"role": "assistant",
"content": [
{
"type": "redacted_thinking",
"data": '{"type":"reasoning.encrypted","data":"opaque"}',
},
{"type": "text", "text": "Need a tool."},
],
},
{"role": "user", "content": "continue"},
],
}
)
body = open_router_provider._build_request_body(
request, reasoning=reasoning_for(request)
)
assistant = next(msg for msg in body["messages"] if msg["role"] == "assistant")
assert assistant["reasoning_details"] == [detail]
@pytest.mark.asyncio
async def test_stream_maps_reasoning_content_and_details(open_router_provider):
redacted = {"type": "reasoning.encrypted", "data": "opaque"}
stream = AsyncStream(
[
_chunk(reasoning_content="plan "),
_chunk(reasoning_details=[redacted]),
_chunk(content="done", finish_reason="stop"),
]
)
with patch.object(
open_router_provider._client.chat.completions,
"create",
new_callable=AsyncMock,
return_value=stream,
):
events = [
event
async for event in open_router_provider.stream_response(make_request())
]
event_text = "".join(events)
assert "thinking_delta" in event_text
assert "plan " in event_text
assert "redacted_thinking" in event_text
assert "opaque" in event_text
assert "done" in text_content(parse_sse_text(event_text))
assert stream.closed
@pytest.mark.asyncio
async def test_model_infos_filter_tool_models_and_thinking_metadata(
open_router_provider,
):
open_router_provider._client.models.list = AsyncMock(
return_value=SimpleNamespace(
data=[
SimpleNamespace(
id="tool-model",
supported_parameters=["tools", "reasoning"],
),
SimpleNamespace(id="plain-model", supported_parameters=[]),
]
)
)
infos = await open_router_provider.list_model_infos()
assert {(info.model_id, info.supports_thinking) for info in infos} == {
("tool-model", True)
}
@pytest.mark.asyncio
async def test_cleanup_closes_openai_client(open_router_provider):
open_router_provider._client = MagicMock()
open_router_provider._client.close = AsyncMock()
await open_router_provider.cleanup()
open_router_provider._client.close.assert_awaited_once()