feat(chat): surface the provider's own retry waits

The 10-minute silence in #2693 does not come from the agent loop: a 401/429/5xx
is retried inside the provider on the configured schedule (5s → 120s per attempt,
8 attempts), and those sleeps emit no stream events at all. The turn looks
frozen until the final error.

- `LLMProvider` gains an optional async `retry_observer`, called before each
  retry sleep with the attempt number, total and delay. A failing observer is
  logged and ignored: visibility must never turn a retry into a failure.
- The agent loop attaches an observer before every model call and emits the same
  `provider_retry` notice the transport-retry path already used, now with the
  provider label, attempt count and `retry_delay_s` /
  `fallbacks_configured` in the trace metadata.
- Covered by unit tests for the observer contract (called once per retry, and
  inert when it raises).
This commit is contained in:
yaqi
2026-11-24 15:41:33 +08:00
parent 5c61a9bfe1
commit e5a20ba12e
3 changed files with 123 additions and 0 deletions

View File

@@ -706,6 +706,46 @@ class AgentLoop:
"""
apply_gateway_prompt_caching(kwargs, self.pipeline.binding, stable_history_end=True)
def _attach_retry_observer(self, *, stage: str, trace_meta: dict[str, Any]) -> None:
"""Make the provider's own retry sleeps visible on the stream.
The provider retries transient status codes on the configured schedule
(5s → 120s per attempt by default). Those waits are invisible to the
user, which is how a 502 turns into ten minutes of silence (#2693).
"""
provider = getattr(self.client, "_provider", None)
if provider is None or not hasattr(provider, "retry_observer"):
return
alternatives = fallback_count()
async def observe(*, attempt: int, total: int, delay: float, detail: str) -> None:
provider_name, model = provider_label(self.pipeline)
await self.stream.progress(
retry_notice(
self.pipeline._t,
provider=provider_name,
model=model,
attempt=attempt,
total=total,
),
source=self.source,
stage=stage,
metadata=merge_trace_metadata(
trace_meta,
{
"trace_kind": "warning",
"error_code": "provider_retry",
"provider": provider_name,
"retry_attempt": attempt,
"retry_total": total,
"retry_delay_s": delay,
"fallbacks_configured": alternatives,
},
),
)
provider.retry_observer = observe
def _project_request(
self,
messages: list[dict[str, Any]],
@@ -817,6 +857,9 @@ class AgentLoop:
{"trace_kind": "call_status", "call_state": "running"},
),
)
# Provider-level retries sleep for seconds to minutes and emit nothing on
# their own; without this the turn looks frozen (#2693 P0).
self._attach_retry_observer(stage=stage, trace_meta=trace_meta)
kwargs: dict[str, Any] = {
"model": self.pipeline.model,

View File

@@ -436,6 +436,21 @@ class LLMProvider(ABC):
delay,
(response.content or "")[:120].lower(),
)
# A retry that sleeps for seconds (the default schedule reaches
# 5s→120s per attempt) produces no stream events at all, so the turn
# looks frozen (#2693). The observer lets the caller surface each
# wait; it must never turn a retry into a failure.
observer = getattr(self, "retry_observer", None)
if observer is not None:
try:
await observer(
attempt=attempt,
total=len(delays) + 1,
delay=delay,
detail=(response.content or "")[:160],
)
except Exception: # pragma: no cover - visibility is best-effort
logger.debug("retry observer failed", exc_info=True)
await asyncio.sleep(delay)
async def chat_with_retry(

View File

@@ -0,0 +1,65 @@
"""Provider retry sleeps must be observable (#2693 P0)."""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse
class _FlakyProvider(LLMProvider):
"""Fails with a retryable 500 the first N times, then answers."""
def __init__(self, failures: int) -> None:
self.failures = failures
self.calls = 0
self.generation = SimpleNamespace(max_tokens=64, temperature=0.0, reasoning_effort=None)
def get_default_model(self) -> str:
return "demo-model"
async def chat(self, **kwargs): # noqa: ANN003 - mirrors the base signature
self.calls += 1
if self.calls <= self.failures:
return LLMResponse(content="HTTP 500 server error", finish_reason="error")
return LLMResponse(content="ok", finish_reason="stop")
@pytest.mark.asyncio
async def test_observer_sees_each_retry_before_the_sleep() -> None:
provider = _FlakyProvider(failures=2)
seen: list[tuple[int, int, float]] = []
async def observe(*, attempt: int, total: int, delay: float, detail: str) -> None:
seen.append((attempt, total, delay))
provider.retry_observer = observe
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hi"}],
retry_delays=(0.01, 0.01),
)
assert response.content == "ok"
assert provider.calls == 3
# Two retries, each announced before its sleep, with the caller's schedule.
assert [(a, t) for a, t, _ in seen] == [(1, 3), (2, 3)]
@pytest.mark.asyncio
async def test_failing_observer_never_breaks_the_retry() -> None:
provider = _FlakyProvider(failures=1)
async def observe(**kwargs): # noqa: ANN003
raise RuntimeError("the reporter is broken")
provider.retry_observer = observe
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hi"}],
retry_delays=(0.01,),
)
assert response.content == "ok"